1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-2008 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* If ls_mode is LS_MULTI_COL,
18 the multi-column format is the default regardless
19 of the type of output device.
20 This is for the `dir' program.
22 If ls_mode is LS_LONG_FORMAT,
23 the long format is the default regardless of the
24 type of output device.
25 This is for the `vdir' program.
28 the output format depends on whether the output
30 This is for the `ls' program. */
32 /* Written by Richard Stallman and David MacKenzie. */
34 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
35 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
36 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
39 #include <sys/types.h>
48 # include <sys/ioctl.h>
51 #ifdef WINSIZE_IN_PTEM
52 # include <sys/stream.h>
53 # include <sys/ptem.h>
63 #include <selinux/selinux.h>
66 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
69 # define SA_NOCLDSTOP 0
70 # define sigprocmask(How, Set, Oset) /* empty */
72 # if ! HAVE_SIGINTERRUPT
73 # define siginterrupt(sig, flag) /* empty */
88 #include "filenamecat.h"
89 #include "hard-locale.h"
101 #include "quotearg.h"
103 #include "stat-time.h"
104 #include "strftime.h"
105 #include "strverscmp.h"
107 #include "areadlink.h"
109 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
110 : (ls_mode == LS_MULTI_COL \
114 proper_name ("Richard M. Stallman"), \
115 proper_name ("David MacKenzie")
117 #define obstack_chunk_alloc malloc
118 #define obstack_chunk_free free
120 /* Return an int indicating the result of comparing two integers.
121 Subtracting doesn't always work, due to overflow. */
122 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
124 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
125 # define st_author st_uid
142 /* Display letters and indicators for each filetype.
143 Keep these in sync with enum filetype. */
144 static char const filetype_letter[] = "?pcdb-lswd";
146 /* Ensure that filetype and filetype_letter have the same
147 number of elements. */
148 verify (sizeof filetype_letter - 1 == arg_directory + 1);
150 #define FILETYPE_INDICATORS \
152 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
153 C_LINK, C_SOCK, C_FILE, C_DIR \
162 /* For symbolic link, name of the file linked to, otherwise zero. */
167 enum filetype filetype;
169 /* For symbolic link and long listing, st_mode of file linked to, otherwise
173 /* SELinux security context. */
174 security_context_t scontext;
178 /* For symbolic link and color printing, true if linked-to file
179 exists, otherwise false. */
182 /* For long listings, true if the file has an access control list,
183 or an SELinux security context. */
187 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
189 /* Null is a valid character in a color indicator (think about Epson
190 printers, for example) so we have to use a length/buffer string
195 size_t len; /* Number of bytes */
196 const char *string; /* Pointer to the same */
200 # define tcgetpgrp(Fd) 0
203 static size_t quote_name (FILE *out, const char *name,
204 struct quoting_options const *options,
206 static char *make_link_name (char const *name, char const *linkname);
207 static int decode_switches (int argc, char **argv);
208 static bool file_ignored (char const *name);
209 static uintmax_t gobble_file (char const *name, enum filetype type,
210 ino_t inode, bool command_line_arg,
211 char const *dirname);
212 static bool print_color_indicator (const char *name, mode_t mode, int linkok,
213 bool stat_ok, enum filetype type);
214 static void put_indicator (const struct bin_str *ind);
215 static void add_ignore_pattern (const char *pattern);
216 static void attach (char *dest, const char *dirname, const char *name);
217 static void clear_files (void);
218 static void extract_dirs_from_files (char const *dirname,
219 bool command_line_arg);
220 static void get_link_name (char const *filename, struct fileinfo *f,
221 bool command_line_arg);
222 static void indent (size_t from, size_t to);
223 static size_t calculate_columns (bool by_columns);
224 static void print_current_files (void);
225 static void print_dir (char const *name, char const *realname,
226 bool command_line_arg);
227 static void print_file_name_and_frills (const struct fileinfo *f);
228 static void print_horizontal (void);
229 static int format_user_width (uid_t u);
230 static int format_group_width (gid_t g);
231 static void print_long_format (const struct fileinfo *f);
232 static void print_many_per_line (void);
233 static void print_name_with_quoting (const char *p, mode_t mode,
234 int linkok, bool stat_ok,
236 struct obstack *stack);
237 static void prep_non_filename_text (void);
238 static void print_type_indicator (bool stat_ok, mode_t mode,
240 static void print_with_commas (void);
241 static void queue_directory (char const *name, char const *realname,
242 bool command_line_arg);
243 static void sort_files (void);
244 static void parse_ls_color (void);
245 void usage (int status);
247 /* The name this program was run with. */
250 /* Initial size of hash table.
251 Most hierarchies are likely to be shallower than this. */
252 #define INITIAL_TABLE_SIZE 30
254 /* The set of `active' directories, from the current command-line argument
255 to the level in the hierarchy at which files are being listed.
256 A directory is represented by its device and inode numbers (struct dev_ino).
257 A directory is added to this set when ls begins listing it or its
258 entries, and it is removed from the set just after ls has finished
259 processing it. This set is used solely to detect loops, e.g., with
260 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
261 static Hash_table *active_dir_set;
263 #define LOOP_DETECT (!!active_dir_set)
265 /* The table of files in the current directory:
267 `cwd_file' points to a vector of `struct fileinfo', one per file.
268 `cwd_n_alloc' is the number of elements space has been allocated for.
269 `cwd_n_used' is the number actually in use. */
271 /* Address of block containing the files that are described. */
272 static struct fileinfo *cwd_file;
274 /* Length of block that `cwd_file' points to, measured in files. */
275 static size_t cwd_n_alloc;
277 /* Index of first unused slot in `cwd_file'. */
278 static size_t cwd_n_used;
280 /* Vector of pointers to files, in proper sorted order, and the number
281 of entries allocated for it. */
282 static void **sorted_file;
283 static size_t sorted_file_alloc;
285 /* When true, in a color listing, color each symlink name according to the
286 type of file it points to. Otherwise, color them according to the `ln'
287 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
288 regardless. This is set when `ln=target' appears in LS_COLORS. */
290 static bool color_symlink_as_referent;
292 /* mode of appropriate file for colorization */
293 #define FILE_OR_LINK_MODE(File) \
294 ((color_symlink_as_referent & (File)->linkok) \
295 ? (File)->linkmode : (File)->stat.st_mode)
298 /* Record of one pending directory waiting to be listed. */
303 /* If the directory is actually the file pointed to by a symbolic link we
304 were told to list, `realname' will contain the name of the symbolic
305 link, otherwise zero. */
307 bool command_line_arg;
308 struct pending *next;
311 static struct pending *pending_dirs;
313 /* Current time in seconds and nanoseconds since 1970, updated as
314 needed when deciding whether a file is recent. */
316 static struct timespec current_time;
318 static bool print_scontext;
319 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
321 /* Whether any of the files has an ACL. This affects the width of the
324 static bool any_has_acl;
326 /* The number of columns to use for columns containing inode numbers,
327 block sizes, link counts, owners, groups, authors, major device
328 numbers, minor device numbers, and file sizes, respectively. */
330 static int inode_number_width;
331 static int block_size_width;
332 static int nlink_width;
333 static int scontext_width;
334 static int owner_width;
335 static int group_width;
336 static int author_width;
337 static int major_device_number_width;
338 static int minor_device_number_width;
339 static int file_size_width;
343 /* long_format for lots of info, one per line.
344 one_per_line for just names, one per line.
345 many_per_line for just names, many per line, sorted vertically.
346 horizontal for just names, many per line, sorted horizontally.
347 with_commas for just names, many per line, separated by commas.
349 -l (and other options that imply -l), -1, -C, -x and -m control
354 long_format, /* -l and other options that imply -l */
355 one_per_line, /* -1 */
356 many_per_line, /* -C */
361 static enum format format;
363 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
364 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
365 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
368 full_iso_time_style, /* --time-style=full-iso */
369 long_iso_time_style, /* --time-style=long-iso */
370 iso_time_style, /* --time-style=iso */
371 locale_time_style /* --time-style=locale */
374 static char const *const time_style_args[] =
376 "full-iso", "long-iso", "iso", "locale", NULL
378 static enum time_style const time_style_types[] =
380 full_iso_time_style, long_iso_time_style, iso_time_style,
383 ARGMATCH_VERIFY (time_style_args, time_style_types);
385 /* Type of time to print or sort by. Controlled by -c and -u.
386 The values of each item of this enum are important since they are
387 used as indices in the sort functions array (see sort_files()). */
391 time_mtime, /* default */
394 time_numtypes /* the number of elements of this enum */
397 static enum time_type time_type;
399 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
400 The values of each item of this enum are important since they are
401 used as indices in the sort functions array (see sort_files()). */
405 sort_none = -1, /* -U */
406 sort_name, /* default */
407 sort_extension, /* -X */
409 sort_version, /* -v */
411 sort_numtypes /* the number of elements of this enum */
414 static enum sort_type sort_type;
416 /* Direction of sort.
417 false means highest first if numeric,
418 lowest first if alphabetic;
419 these are the defaults.
420 true means the opposite order in each case. -r */
422 static bool sort_reverse;
424 /* True means to display owner information. -g turns this off. */
426 static bool print_owner = true;
428 /* True means to display author information. */
430 static bool print_author;
432 /* True means to display group information. -G and -o turn this off. */
434 static bool print_group = true;
436 /* True means print the user and group id's as numbers rather
439 static bool numeric_ids;
441 /* True means mention the size in blocks of each file. -s */
443 static bool print_block_size;
445 /* Human-readable options for output. */
446 static int human_output_opts;
448 /* The units to use when printing sizes other than file sizes. */
449 static uintmax_t output_block_size;
451 /* Likewise, but for file sizes. */
452 static uintmax_t file_output_block_size = 1;
454 /* Follow the output with a special string. Using this format,
455 Emacs' dired mode starts up twice as fast, and can handle all
456 strange characters in file names. */
459 /* `none' means don't mention the type of files.
460 `slash' means mention directories only, with a '/'.
461 `file_type' means mention file types.
462 `classify' means mention file types and mark executables.
464 Controlled by -F, -p, and --indicator-style. */
468 none, /* --indicator-style=none */
469 slash, /* -p, --indicator-style=slash */
470 file_type, /* --indicator-style=file-type */
471 classify /* -F, --indicator-style=classify */
474 static enum indicator_style indicator_style;
476 /* Names of indicator styles. */
477 static char const *const indicator_style_args[] =
479 "none", "slash", "file-type", "classify", NULL
481 static enum indicator_style const indicator_style_types[] =
483 none, slash, file_type, classify
485 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
487 /* True means use colors to mark types. Also define the different
488 colors as well as the stuff for the LS_COLORS environment variable.
489 The LS_COLORS variable is now in a termcap-like format. */
491 static bool print_with_color;
493 /* Whether we used any colors in the output so far. If so, we will
494 need to restore the default color later. If not, we will need to
495 call prep_non_filename_text before using color for the first time. */
497 static bool used_color = false;
501 color_never, /* 0: default or --color=never */
502 color_always, /* 1: --color=always */
503 color_if_tty /* 2: --color=tty */
506 enum Dereference_symlink
510 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
511 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
512 DEREF_ALWAYS /* -L */
517 C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
519 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
520 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE
523 static const char *const indicator_name[]=
525 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
526 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
530 struct color_ext_type
532 struct bin_str ext; /* The extension we're looking for */
533 struct bin_str seq; /* The sequence to output when we do */
534 struct color_ext_type *next; /* Next in list */
537 static struct bin_str color_indicator[] =
539 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
540 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
541 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
542 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
543 { 0, NULL }, /* no: Normal */
544 { 0, NULL }, /* fi: File: default */
545 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
546 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
547 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
548 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
549 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
550 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
551 { 0, NULL }, /* mi: Missing file: undefined */
552 { 0, NULL }, /* or: Orphaned symlink: undefined */
553 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
554 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
555 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
556 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
557 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
558 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
559 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
563 static struct color_ext_type *color_ext_list = NULL;
565 /* Buffer for color sequences */
566 static char *color_buf;
568 /* True means to check for orphaned symbolic link, for displaying
571 static bool check_symlink_color;
573 /* True means mention the inode number of each file. -i */
575 static bool print_inode;
577 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
578 other options that imply -l), and -L. */
580 static enum Dereference_symlink dereference;
582 /* True means when a directory is found, display info on its
585 static bool recursive;
587 /* True means when an argument is a directory name, display info
590 static bool immediate_dirs;
592 /* True means that directories are grouped before files. */
594 static bool directories_first;
596 /* Which files to ignore. */
600 /* Ignore files whose names start with `.', and files specified by
601 --hide and --ignore. */
604 /* Ignore `.', `..', and files specified by --ignore. */
605 IGNORE_DOT_AND_DOTDOT,
607 /* Ignore only files specified by --ignore. */
611 /* A linked list of shell-style globbing patterns. If a non-argument
612 file name matches any of these patterns, it is ignored.
613 Controlled by -I. Multiple -I options accumulate.
614 The -B option adds `*~' and `.*~' to this list. */
616 struct ignore_pattern
619 struct ignore_pattern *next;
622 static struct ignore_pattern *ignore_patterns;
624 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
625 variable itself to be ignored. */
626 static struct ignore_pattern *hide_patterns;
628 /* True means output nongraphic chars in file names as `?'.
629 (-q, --hide-control-chars)
630 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
631 independent. The algorithm is: first, obey the quoting style to get a
632 string representing the file name; then, if qmark_funny_chars is set,
633 replace all nonprintable chars in that string with `?'. It's necessary
634 to replace nonprintable chars even in quoted strings, because we don't
635 want to mess up the terminal if control chars get sent to it, and some
636 quoting methods pass through control chars as-is. */
637 static bool qmark_funny_chars;
639 /* Quoting options for file and dir name output. */
641 static struct quoting_options *filename_quoting_options;
642 static struct quoting_options *dirname_quoting_options;
644 /* The number of chars per hardware tab stop. Setting this to zero
645 inhibits the use of TAB characters for separating columns. -T */
646 static size_t tabsize;
648 /* True means print each directory name before listing it. */
650 static bool print_dir_name;
652 /* The line length to use for breaking lines in many-per-line format.
653 Can be set with -w. */
655 static size_t line_length;
657 /* If true, the file listing format requires that stat be called on
660 static bool format_needs_stat;
662 /* Similar to `format_needs_stat', but set if only the file type is
665 static bool format_needs_type;
667 /* An arbitrary limit on the number of bytes in a printed time stamp.
668 This is set to a relatively small value to avoid the need to worry
669 about denial-of-service attacks on servers that run "ls" on behalf
670 of remote clients. 1000 bytes should be enough for any practical
671 time stamp format. */
673 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
675 /* strftime formats for non-recent and recent files, respectively, in
678 static char const *long_time_format[2] =
680 /* strftime format for non-recent files (older than 6 months), in
681 -l output. This should contain the year, month and day (at
682 least), in an order that is understood by people in your
683 locale's territory. Please try to keep the number of used
684 screen columns small, because many people work in windows with
685 only 80 columns. But make this as wide as the other string
686 below, for recent files. */
688 /* strftime format for recent files (younger than 6 months), in -l
689 output. This should contain the month, day and time (at
690 least), in an order that is understood by people in your
691 locale's territory. Please try to keep the number of used
692 screen columns small, because many people work in windows with
693 only 80 columns. But make this as wide as the other string
694 above, for non-recent files. */
698 /* The set of signals that are caught. */
700 static sigset_t caught_signals;
702 /* If nonzero, the value of the pending fatal signal. */
704 static sig_atomic_t volatile interrupt_signal;
706 /* A count of the number of pending stop signals that have been received. */
708 static sig_atomic_t volatile stop_signal_count;
710 /* Desired exit status. */
712 static int exit_status;
717 /* "ls" had a minor problem (e.g., it could not stat a directory
719 LS_MINOR_PROBLEM = 1,
721 /* "ls" had more serious trouble. */
725 /* For long options that have no equivalent short option, use a
726 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
729 AUTHOR_OPTION = CHAR_MAX + 1,
732 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
733 FILE_TYPE_INDICATOR_OPTION,
736 GROUP_DIRECTORIES_FIRST_OPTION,
738 INDICATOR_STYLE_OPTION,
739 QUOTING_STYLE_OPTION,
740 SHOW_CONTROL_CHARS_OPTION,
747 static struct option const long_options[] =
749 {"all", no_argument, NULL, 'a'},
750 {"escape", no_argument, NULL, 'b'},
751 {"directory", no_argument, NULL, 'd'},
752 {"dired", no_argument, NULL, 'D'},
753 {"full-time", no_argument, NULL, FULL_TIME_OPTION},
754 {"group-directories-first", no_argument, NULL,
755 GROUP_DIRECTORIES_FIRST_OPTION},
756 {"human-readable", no_argument, NULL, 'h'},
757 {"inode", no_argument, NULL, 'i'},
758 {"numeric-uid-gid", no_argument, NULL, 'n'},
759 {"no-group", no_argument, NULL, 'G'},
760 {"hide-control-chars", no_argument, NULL, 'q'},
761 {"reverse", no_argument, NULL, 'r'},
762 {"size", no_argument, NULL, 's'},
763 {"width", required_argument, NULL, 'w'},
764 {"almost-all", no_argument, NULL, 'A'},
765 {"ignore-backups", no_argument, NULL, 'B'},
766 {"classify", no_argument, NULL, 'F'},
767 {"file-type", no_argument, NULL, FILE_TYPE_INDICATOR_OPTION},
768 {"si", no_argument, NULL, SI_OPTION},
769 {"dereference-command-line", no_argument, NULL, 'H'},
770 {"dereference-command-line-symlink-to-dir", no_argument, NULL,
771 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
772 {"hide", required_argument, NULL, HIDE_OPTION},
773 {"ignore", required_argument, NULL, 'I'},
774 {"indicator-style", required_argument, NULL, INDICATOR_STYLE_OPTION},
775 {"dereference", no_argument, NULL, 'L'},
776 {"literal", no_argument, NULL, 'N'},
777 {"quote-name", no_argument, NULL, 'Q'},
778 {"quoting-style", required_argument, NULL, QUOTING_STYLE_OPTION},
779 {"recursive", no_argument, NULL, 'R'},
780 {"format", required_argument, NULL, FORMAT_OPTION},
781 {"show-control-chars", no_argument, NULL, SHOW_CONTROL_CHARS_OPTION},
782 {"sort", required_argument, NULL, SORT_OPTION},
783 {"tabsize", required_argument, NULL, 'T'},
784 {"time", required_argument, NULL, TIME_OPTION},
785 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
786 {"color", optional_argument, NULL, COLOR_OPTION},
787 {"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
788 {"context", no_argument, 0, 'Z'},
789 {"author", no_argument, NULL, AUTHOR_OPTION},
790 {GETOPT_HELP_OPTION_DECL},
791 {GETOPT_VERSION_OPTION_DECL},
795 static char const *const format_args[] =
797 "verbose", "long", "commas", "horizontal", "across",
798 "vertical", "single-column", NULL
800 static enum format const format_types[] =
802 long_format, long_format, with_commas, horizontal, horizontal,
803 many_per_line, one_per_line
805 ARGMATCH_VERIFY (format_args, format_types);
807 static char const *const sort_args[] =
809 "none", "time", "size", "extension", "version", NULL
811 static enum sort_type const sort_types[] =
813 sort_none, sort_time, sort_size, sort_extension, sort_version
815 ARGMATCH_VERIFY (sort_args, sort_types);
817 static char const *const time_args[] =
819 "atime", "access", "use", "ctime", "status", NULL
821 static enum time_type const time_types[] =
823 time_atime, time_atime, time_atime, time_ctime, time_ctime
825 ARGMATCH_VERIFY (time_args, time_types);
827 static char const *const color_args[] =
829 /* force and none are for compatibility with another color-ls version */
830 "always", "yes", "force",
831 "never", "no", "none",
832 "auto", "tty", "if-tty", NULL
834 static enum color_type const color_types[] =
836 color_always, color_always, color_always,
837 color_never, color_never, color_never,
838 color_if_tty, color_if_tty, color_if_tty
840 ARGMATCH_VERIFY (color_args, color_types);
842 /* Information about filling a column. */
850 /* Array with information about column filledness. */
851 static struct column_info *column_info;
853 /* Maximum number of columns ever possible for this display. */
854 static size_t max_idx;
856 /* The minimum width of a column is 3: 1 character for the name and 2
857 for the separating white space. */
858 #define MIN_COLUMN_WIDTH 3
861 /* This zero-based index is used solely with the --dired option.
862 When that option is in effect, this counter is incremented for each
863 byte of output generated by this program so that the beginning
864 and ending indices (in that output) of every file name can be recorded
865 and later output themselves. */
866 static size_t dired_pos;
868 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
870 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
871 #define DIRED_FPUTS(s, stream, s_len) \
872 do {fputs (s, stream); dired_pos += s_len;} while (0)
874 /* Like DIRED_FPUTS, but for use when S is a literal string. */
875 #define DIRED_FPUTS_LITERAL(s, stream) \
876 do {fputs (s, stream); dired_pos += sizeof (s) - 1;} while (0)
878 #define DIRED_INDENT() \
882 DIRED_FPUTS_LITERAL (" ", stdout); \
886 /* With --dired, store pairs of beginning and ending indices of filenames. */
887 static struct obstack dired_obstack;
889 /* With --dired, store pairs of beginning and ending indices of any
890 directory names that appear as headers (just before `total' line)
891 for lists of directory entries. Such directory names are seen when
892 listing hierarchies using -R and when a directory is listed with at
893 least one other command line argument. */
894 static struct obstack subdired_obstack;
896 /* Save the current index on the specified obstack, OBS. */
897 #define PUSH_CURRENT_DIRED_POS(obs) \
901 obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
905 /* With -R, this stack is used to help detect directory cycles.
906 The device/inode pairs on this stack mirror the pairs in the
907 active_dir_set hash table. */
908 static struct obstack dev_ino_obstack;
910 /* Push a pair onto the device/inode stack. */
911 #define DEV_INO_PUSH(Dev, Ino) \
914 struct dev_ino *di; \
915 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
916 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
917 di->st_dev = (Dev); \
918 di->st_ino = (Ino); \
922 /* Pop a dev/ino struct off the global dev_ino_obstack
923 and return that struct. */
924 static struct dev_ino
927 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
928 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
929 return *(struct dev_ino *) obstack_next_free (&dev_ino_obstack);
932 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
937 assert (0 <= stat (Name, &sb)); \
938 assert (sb.st_dev == Di.st_dev); \
939 assert (sb.st_ino == Di.st_ino); \
944 /* Write to standard output PREFIX, followed by the quoting style and
945 a space-separated list of the integers stored in OS all on one line. */
948 dired_dump_obstack (const char *prefix, struct obstack *os)
952 n_pos = obstack_object_size (os) / sizeof (dired_pos);
958 pos = (size_t *) obstack_finish (os);
959 fputs (prefix, stdout);
960 for (i = 0; i < n_pos; i++)
961 printf (" %lu", (unsigned long int) pos[i]);
967 dev_ino_hash (void const *x, size_t table_size)
969 struct dev_ino const *p = x;
970 return (uintmax_t) p->st_ino % table_size;
974 dev_ino_compare (void const *x, void const *y)
976 struct dev_ino const *a = x;
977 struct dev_ino const *b = y;
978 return SAME_INODE (*a, *b) ? true : false;
982 dev_ino_free (void *x)
987 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
988 active directories. Return true if there is already a matching
989 entry in the table. */
992 visit_dir (dev_t dev, ino_t ino)
995 struct dev_ino *ent_from_table;
998 ent = xmalloc (sizeof *ent);
1002 /* Attempt to insert this entry into the table. */
1003 ent_from_table = hash_insert (active_dir_set, ent);
1005 if (ent_from_table == NULL)
1007 /* Insertion failed due to lack of memory. */
1011 found_match = (ent_from_table != ent);
1015 /* ent was not inserted, so free it. */
1023 free_pending_ent (struct pending *p)
1031 is_colored (enum indicator_no type)
1033 size_t len = color_indicator[type].len;
1034 char const *s = color_indicator[type].string;
1036 || (len == 1 && strncmp (s, "0", 1) == 0)
1037 || (len == 2 && strncmp (s, "00", 2) == 0));
1041 restore_default_color (void)
1043 put_indicator (&color_indicator[C_LEFT]);
1044 put_indicator (&color_indicator[C_RIGHT]);
1047 /* An ordinary signal was received; arrange for the program to exit. */
1050 sighandler (int sig)
1053 signal (sig, SIG_IGN);
1054 if (! interrupt_signal)
1055 interrupt_signal = sig;
1058 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1061 stophandler (int sig)
1064 signal (sig, stophandler);
1065 if (! interrupt_signal)
1066 stop_signal_count++;
1069 /* Process any pending signals. If signals are caught, this function
1070 should be called periodically. Ideally there should never be an
1071 unbounded amount of time when signals are not being processed.
1072 Signal handling can restore the default colors, so callers must
1073 immediately change colors after invoking this function. */
1076 process_signals (void)
1078 while (interrupt_signal | stop_signal_count)
1085 restore_default_color ();
1088 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1090 /* Reload interrupt_signal and stop_signal_count, in case a new
1091 signal was handled before sigprocmask took effect. */
1092 sig = interrupt_signal;
1093 stops = stop_signal_count;
1095 /* SIGTSTP is special, since the application can receive that signal
1096 more than once. In this case, don't set the signal handler to the
1097 default. Instead, just raise the uncatchable SIGSTOP. */
1100 stop_signal_count = stops - 1;
1104 signal (sig, SIG_DFL);
1106 /* Exit or suspend the program. */
1108 sigprocmask (SIG_SETMASK, &oldset, NULL);
1110 /* If execution reaches here, then the program has been
1111 continued (after being suspended). */
1116 main (int argc, char **argv)
1119 struct pending *thispend;
1122 /* The signals that are trapped, and the number of such signals. */
1123 static int const sig[] =
1125 /* This one is handled specially. */
1128 /* The usual suspects. */
1129 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1146 enum { nsigs = sizeof sig / sizeof sig[0] };
1149 bool caught_sig[nsigs];
1152 initialize_main (&argc, &argv);
1153 program_name = argv[0];
1154 setlocale (LC_ALL, "");
1155 bindtextdomain (PACKAGE, LOCALEDIR);
1156 textdomain (PACKAGE);
1158 initialize_exit_failure (LS_FAILURE);
1159 atexit (close_stdout);
1161 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1162 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1164 exit_status = EXIT_SUCCESS;
1165 print_dir_name = true;
1166 pending_dirs = NULL;
1168 current_time.tv_sec = TYPE_MINIMUM (time_t);
1169 current_time.tv_nsec = -1;
1171 i = decode_switches (argc, argv);
1173 if (print_with_color)
1176 /* Test print_with_color again, because the call to parse_ls_color
1177 may have just reset it -- e.g., if LS_COLORS is invalid. */
1178 if (print_with_color)
1180 /* Avoid following symbolic links when possible. */
1181 if (is_colored (C_ORPHAN)
1182 || (is_colored (C_EXEC) && color_symlink_as_referent)
1183 || (is_colored (C_MISSING) && format == long_format))
1184 check_symlink_color = true;
1186 /* If the standard output is a controlling terminal, watch out
1187 for signals, so that the colors can be restored to the
1188 default state if "ls" is suspended or interrupted. */
1190 if (0 <= tcgetpgrp (STDOUT_FILENO))
1194 struct sigaction act;
1196 sigemptyset (&caught_signals);
1197 for (j = 0; j < nsigs; j++)
1199 sigaction (sig[j], NULL, &act);
1200 if (act.sa_handler != SIG_IGN)
1201 sigaddset (&caught_signals, sig[j]);
1204 act.sa_mask = caught_signals;
1205 act.sa_flags = SA_RESTART;
1207 for (j = 0; j < nsigs; j++)
1208 if (sigismember (&caught_signals, sig[j]))
1210 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1211 sigaction (sig[j], &act, NULL);
1214 for (j = 0; j < nsigs; j++)
1216 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1219 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1220 siginterrupt (sig[j], 0);
1227 if (dereference == DEREF_UNDEFINED)
1228 dereference = ((immediate_dirs
1229 || indicator_style == classify
1230 || format == long_format)
1232 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1234 /* When using -R, initialize a data structure we'll use to
1235 detect any directory cycles. */
1238 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1242 if (active_dir_set == NULL)
1245 obstack_init (&dev_ino_obstack);
1248 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1249 || format == long_format
1251 || print_block_size;
1252 format_needs_type = (! format_needs_stat
1255 || indicator_style != none
1256 || directories_first));
1260 obstack_init (&dired_obstack);
1261 obstack_init (&subdired_obstack);
1265 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1275 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1277 queue_directory (".", NULL, true);
1281 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1287 if (!immediate_dirs)
1288 extract_dirs_from_files (NULL, true);
1289 /* `cwd_n_used' might be zero now. */
1292 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1293 (and not pending_dirs->name) because there may be no markers in the queue
1294 at this point. A marker may be enqueued when extract_dirs_from_files is
1295 called with a non-empty string or via print_dir. */
1298 print_current_files ();
1300 DIRED_PUTCHAR ('\n');
1302 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1303 print_dir_name = false;
1305 while (pending_dirs)
1307 thispend = pending_dirs;
1308 pending_dirs = pending_dirs->next;
1312 if (thispend->name == NULL)
1314 /* thispend->name == NULL means this is a marker entry
1315 indicating we've finished processing the directory.
1316 Use its dev/ino numbers to remove the corresponding
1317 entry from the active_dir_set hash table. */
1318 struct dev_ino di = dev_ino_pop ();
1319 struct dev_ino *found = hash_delete (active_dir_set, &di);
1320 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1322 dev_ino_free (found);
1323 free_pending_ent (thispend);
1328 print_dir (thispend->name, thispend->realname,
1329 thispend->command_line_arg);
1331 free_pending_ent (thispend);
1332 print_dir_name = true;
1335 if (print_with_color)
1340 restore_default_color ();
1343 /* Restore the default signal handling. */
1345 for (j = 0; j < nsigs; j++)
1346 if (sigismember (&caught_signals, sig[j]))
1347 signal (sig[j], SIG_DFL);
1349 for (j = 0; j < nsigs; j++)
1351 signal (sig[j], SIG_DFL);
1354 /* Act on any signals that arrived before the default was restored.
1355 This can process signals out of order, but there doesn't seem to
1356 be an easy way to do them in order, and the order isn't that
1357 important anyway. */
1358 for (j = stop_signal_count; j; j--)
1360 j = interrupt_signal;
1367 /* No need to free these since we're about to exit. */
1368 dired_dump_obstack ("//DIRED//", &dired_obstack);
1369 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1370 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1371 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1376 assert (hash_get_n_entries (active_dir_set) == 0);
1377 hash_free (active_dir_set);
1383 /* Set all the option flags according to the switches specified.
1384 Return the index of the first non-option argument. */
1387 decode_switches (int argc, char **argv)
1389 char *time_style_option = NULL;
1391 /* Record whether there is an option specifying sort type. */
1392 bool sort_type_specified = false;
1394 qmark_funny_chars = false;
1396 /* initialize all switches to default settings */
1401 /* This is for the `dir' program. */
1402 format = many_per_line;
1403 set_quoting_style (NULL, escape_quoting_style);
1406 case LS_LONG_FORMAT:
1407 /* This is for the `vdir' program. */
1408 format = long_format;
1409 set_quoting_style (NULL, escape_quoting_style);
1413 /* This is for the `ls' program. */
1414 if (isatty (STDOUT_FILENO))
1416 format = many_per_line;
1417 /* See description of qmark_funny_chars, above. */
1418 qmark_funny_chars = true;
1422 format = one_per_line;
1423 qmark_funny_chars = false;
1431 time_type = time_mtime;
1432 sort_type = sort_name;
1433 sort_reverse = false;
1434 numeric_ids = false;
1435 print_block_size = false;
1436 indicator_style = none;
1437 print_inode = false;
1438 dereference = DEREF_UNDEFINED;
1440 immediate_dirs = false;
1441 ignore_mode = IGNORE_DEFAULT;
1442 ignore_patterns = NULL;
1443 hide_patterns = NULL;
1444 print_scontext = false;
1446 /* FIXME: put this in a function. */
1448 char const *q_style = getenv ("QUOTING_STYLE");
1451 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1453 set_quoting_style (NULL, quoting_style_vals[i]);
1456 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1457 quotearg (q_style));
1462 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1463 human_options (ls_block_size,
1464 &human_output_opts, &output_block_size);
1465 if (ls_block_size || getenv ("BLOCK_SIZE"))
1466 file_output_block_size = output_block_size;
1471 char const *p = getenv ("COLUMNS");
1474 unsigned long int tmp_ulong;
1475 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1476 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1478 line_length = tmp_ulong;
1483 _("ignoring invalid width in environment variable COLUMNS: %s"),
1493 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1494 && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1495 line_length = ws.ws_col;
1500 char const *p = getenv ("TABSIZE");
1504 unsigned long int tmp_ulong;
1505 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1506 && tmp_ulong <= SIZE_MAX)
1508 tabsize = tmp_ulong;
1513 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1522 int c = getopt_long (argc, argv,
1523 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1531 ignore_mode = IGNORE_MINIMAL;
1535 set_quoting_style (NULL, escape_quoting_style);
1539 time_type = time_ctime;
1543 immediate_dirs = true;
1547 /* Same as enabling -a -U and disabling -l -s. */
1548 ignore_mode = IGNORE_MINIMAL;
1549 sort_type = sort_none;
1550 sort_type_specified = true;
1552 if (format == long_format)
1553 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1554 print_block_size = false; /* disable -s */
1555 print_with_color = false; /* disable --color */
1558 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1559 indicator_style = file_type;
1563 format = long_format;
1564 print_owner = false;
1568 human_output_opts = human_autoscale | human_SI | human_base_1024;
1569 file_output_block_size = output_block_size = 1;
1577 human_output_opts = 0;
1578 file_output_block_size = output_block_size = 1024;
1582 format = long_format;
1586 format = with_commas;
1591 format = long_format;
1594 case 'o': /* Just like -l, but don't display group info. */
1595 format = long_format;
1596 print_group = false;
1600 indicator_style = slash;
1604 qmark_funny_chars = true;
1608 sort_reverse = true;
1612 print_block_size = true;
1616 sort_type = sort_time;
1617 sort_type_specified = true;
1621 time_type = time_atime;
1625 sort_type = sort_version;
1626 sort_type_specified = true;
1631 unsigned long int tmp_ulong;
1632 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1633 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1634 error (LS_FAILURE, 0, _("invalid line width: %s"),
1636 line_length = tmp_ulong;
1641 format = horizontal;
1645 if (ignore_mode == IGNORE_DEFAULT)
1646 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1650 add_ignore_pattern ("*~");
1651 add_ignore_pattern (".*~");
1655 format = many_per_line;
1663 indicator_style = classify;
1666 case 'G': /* inhibit display of group info */
1667 print_group = false;
1671 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1674 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1675 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1679 add_ignore_pattern (optarg);
1683 dereference = DEREF_ALWAYS;
1687 set_quoting_style (NULL, literal_quoting_style);
1691 set_quoting_style (NULL, c_quoting_style);
1699 sort_type = sort_size;
1700 sort_type_specified = true;
1705 unsigned long int tmp_ulong;
1706 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1707 || SIZE_MAX < tmp_ulong)
1708 error (LS_FAILURE, 0, _("invalid tab size: %s"),
1710 tabsize = tmp_ulong;
1715 sort_type = sort_none;
1716 sort_type_specified = true;
1720 sort_type = sort_extension;
1721 sort_type_specified = true;
1725 /* -1 has no effect after -l. */
1726 if (format != long_format)
1727 format = one_per_line;
1731 print_author = true;
1736 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1737 hide->pattern = optarg;
1738 hide->next = hide_patterns;
1739 hide_patterns = hide;
1744 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1745 sort_type_specified = true;
1748 case GROUP_DIRECTORIES_FIRST_OPTION:
1749 directories_first = true;
1753 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1757 format = XARGMATCH ("--format", optarg, format_args, format_types);
1760 case FULL_TIME_OPTION:
1761 format = long_format;
1762 time_style_option = "full-iso";
1769 i = XARGMATCH ("--color", optarg, color_args, color_types);
1771 /* Using --color with no argument is equivalent to using
1775 print_with_color = (i == color_always
1776 || (i == color_if_tty
1777 && isatty (STDOUT_FILENO)));
1779 if (print_with_color)
1781 /* Don't use TAB characters in output. Some terminal
1782 emulators can't handle the combination of tabs and
1783 color codes on the same line. */
1789 case INDICATOR_STYLE_OPTION:
1790 indicator_style = XARGMATCH ("--indicator-style", optarg,
1791 indicator_style_args,
1792 indicator_style_types);
1795 case QUOTING_STYLE_OPTION:
1796 set_quoting_style (NULL,
1797 XARGMATCH ("--quoting-style", optarg,
1799 quoting_style_vals));
1802 case TIME_STYLE_OPTION:
1803 time_style_option = optarg;
1806 case SHOW_CONTROL_CHARS_OPTION:
1807 qmark_funny_chars = false;
1810 case BLOCK_SIZE_OPTION:
1812 enum strtol_error e = human_options (optarg, &human_output_opts,
1813 &output_block_size);
1814 if (e != LONGINT_OK)
1815 xstrtol_fatal (e, oi, 0, long_options, optarg);
1816 file_output_block_size = output_block_size;
1821 human_output_opts = human_autoscale | human_SI;
1822 file_output_block_size = output_block_size = 1;
1826 print_scontext = true;
1829 case_GETOPT_HELP_CHAR;
1831 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1838 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1840 filename_quoting_options = clone_quoting_options (NULL);
1841 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1842 set_char_quoting (filename_quoting_options, ' ', 1);
1843 if (file_type <= indicator_style)
1846 for (p = "*=>@|" + indicator_style - file_type; *p; p++)
1847 set_char_quoting (filename_quoting_options, *p, 1);
1850 dirname_quoting_options = clone_quoting_options (NULL);
1851 set_char_quoting (dirname_quoting_options, ':', 1);
1853 /* --dired is meaningful only with --format=long (-l).
1854 Otherwise, ignore it. FIXME: warn about this?
1855 Alternatively, make --dired imply --format=long? */
1856 if (dired && format != long_format)
1859 /* If -c or -u is specified and not -l (or any other option that implies -l),
1860 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1861 The behavior of ls when using either -c or -u but with neither -l nor -t
1862 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1863 sort by atime (this is the one that's not specified by the POSIX spec),
1864 -lu means show atime and sort by name, -lut means show atime and sort
1867 if ((time_type == time_ctime || time_type == time_atime)
1868 && !sort_type_specified && format != long_format)
1870 sort_type = sort_time;
1873 if (format == long_format)
1875 char *style = time_style_option;
1876 static char const posix_prefix[] = "posix-";
1879 if (! (style = getenv ("TIME_STYLE")))
1882 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1884 if (! hard_locale (LC_TIME))
1886 style += sizeof posix_prefix - 1;
1891 char *p0 = style + 1;
1892 char *p1 = strchr (p0, '\n');
1897 if (strchr (p1 + 1, '\n'))
1898 error (LS_FAILURE, 0, _("invalid time style format %s"),
1902 long_time_format[0] = p0;
1903 long_time_format[1] = p1;
1906 switch (XARGMATCH ("time style", style,
1910 case full_iso_time_style:
1911 long_time_format[0] = long_time_format[1] =
1912 "%Y-%m-%d %H:%M:%S.%N %z";
1915 case long_iso_time_style:
1916 case_long_iso_time_style:
1917 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1920 case iso_time_style:
1921 long_time_format[0] = "%Y-%m-%d ";
1922 long_time_format[1] = "%m-%d %H:%M";
1925 case locale_time_style:
1926 if (hard_locale (LC_TIME))
1928 /* Ensure that the locale has translations for both
1929 formats. If not, fall back on long-iso format. */
1931 for (i = 0; i < 2; i++)
1933 char const *locale_format =
1934 dcgettext (NULL, long_time_format[i], LC_TIME);
1935 if (locale_format == long_time_format[i])
1936 goto case_long_iso_time_style;
1937 long_time_format[i] = locale_format;
1946 /* Parse a string as part of the LS_COLORS variable; this may involve
1947 decoding all kinds of escape characters. If equals_end is set an
1948 unescaped equal sign ends the string, otherwise only a : or \0
1949 does. Set *OUTPUT_COUNT to the number of bytes output. Return
1952 The resulting string is *not* null-terminated, but may contain
1955 Note that both dest and src are char **; on return they point to
1956 the first free byte after the array and the character that ended
1957 the input string, respectively. */
1960 get_funky_string (char **dest, const char **src, bool equals_end,
1961 size_t *output_count)
1963 char num; /* For numerical codes */
1964 size_t count; /* Something to count with */
1966 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1971 p = *src; /* We don't want to double-indirect */
1972 q = *dest; /* the whole darn time. */
1974 count = 0; /* No characters counted in yet. */
1977 state = ST_GND; /* Start in ground state. */
1978 while (state < ST_END)
1982 case ST_GND: /* Ground state (no escapes) */
1987 state = ST_END; /* End of string */
1990 state = ST_BACKSLASH; /* Backslash scape sequence */
1994 state = ST_CARET; /* Caret escape */
2000 state = ST_END; /* End */
2003 /* else fall through */
2011 case ST_BACKSLASH: /* Backslash escaped character */
2022 state = ST_OCTAL; /* Octal sequence */
2027 state = ST_HEX; /* Hex sequence */
2030 case 'a': /* Bell */
2033 case 'b': /* Backspace */
2036 case 'e': /* Escape */
2039 case 'f': /* Form feed */
2042 case 'n': /* Newline */
2045 case 'r': /* Carriage return */
2051 case 'v': /* Vtab */
2054 case '?': /* Delete */
2057 case '_': /* Space */
2060 case '\0': /* End of string */
2061 state = ST_ERROR; /* Error! */
2063 default: /* Escaped character like \ ^ : = */
2067 if (state == ST_BACKSLASH)
2076 case ST_OCTAL: /* Octal sequence */
2077 if (*p < '0' || *p > '7')
2084 num = (num << 3) + (*(p++) - '0');
2087 case ST_HEX: /* Hex sequence */
2100 num = (num << 4) + (*(p++) - '0');
2108 num = (num << 4) + (*(p++) - 'a') + 10;
2116 num = (num << 4) + (*(p++) - 'A') + 10;
2126 case ST_CARET: /* Caret escape */
2127 state = ST_GND; /* Should be the next state... */
2128 if (*p >= '@' && *p <= '~')
2130 *(q++) = *(p++) & 037;
2149 *output_count = count;
2151 return state != ST_ERROR;
2155 parse_ls_color (void)
2157 const char *p; /* Pointer to character being parsed */
2158 char *buf; /* color_buf buffer pointer */
2159 int state; /* State of parser */
2160 int ind_no; /* Indicator number */
2161 char label[3]; /* Indicator label */
2162 struct color_ext_type *ext; /* Extension we are working on */
2164 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2168 strcpy (label, "??");
2170 /* This is an overly conservative estimate, but any possible
2171 LS_COLORS string will *not* generate a color_buf longer than
2172 itself, so it is a safe way of allocating a buffer in
2174 buf = color_buf = xstrdup (p);
2181 case 1: /* First label character */
2189 /* Allocate new extension block and add to head of
2190 linked list (this way a later definition will
2191 override an earlier one, which can be useful for
2192 having terminal-specific defs override global). */
2194 ext = xmalloc (sizeof *ext);
2195 ext->next = color_ext_list;
2196 color_ext_list = ext;
2199 ext->ext.string = buf;
2201 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2206 state = 0; /* Done! */
2209 default: /* Assume it is file type label */
2216 case 2: /* Second label character */
2223 state = -1; /* Error */
2226 case 3: /* Equal sign after indicator label */
2227 state = -1; /* Assume failure... */
2228 if (*(p++) == '=')/* It *should* be... */
2230 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2232 if (STREQ (label, indicator_name[ind_no]))
2234 color_indicator[ind_no].string = buf;
2235 state = (get_funky_string (&buf, &p, false,
2236 &color_indicator[ind_no].len)
2242 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2246 case 4: /* Equal sign after *.ext */
2249 ext->seq.string = buf;
2250 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2261 struct color_ext_type *e;
2262 struct color_ext_type *e2;
2265 _("unparsable value for LS_COLORS environment variable"));
2267 for (e = color_ext_list; e != NULL; /* empty */)
2273 print_with_color = false;
2276 if (color_indicator[C_LINK].len == 6
2277 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2278 color_symlink_as_referent = true;
2281 /* Set the exit status to report a failure. If SERIOUS, it is a
2282 serious failure; otherwise, it is merely a minor problem. */
2285 set_exit_status (bool serious)
2288 exit_status = LS_FAILURE;
2289 else if (exit_status == EXIT_SUCCESS)
2290 exit_status = LS_MINOR_PROBLEM;
2293 /* Assuming a failure is serious if SERIOUS, use the printf-style
2294 MESSAGE to report the failure to access a file named FILE. Assume
2295 errno is set appropriately for the failure. */
2298 file_failure (bool serious, char const *message, char const *file)
2300 error (0, errno, message, quotearg_colon (file));
2301 set_exit_status (serious);
2304 /* Request that the directory named NAME have its contents listed later.
2305 If REALNAME is nonzero, it will be used instead of NAME when the
2306 directory name is printed. This allows symbolic links to directories
2307 to be treated as regular directories but still be listed under their
2308 real names. NAME == NULL is used to insert a marker entry for the
2309 directory named in REALNAME.
2310 If NAME is non-NULL, we use its dev/ino information to save
2311 a call to stat -- when doing a recursive (-R) traversal.
2312 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2315 queue_directory (char const *name, char const *realname, bool command_line_arg)
2317 struct pending *new = xmalloc (sizeof *new);
2318 new->realname = realname ? xstrdup (realname) : NULL;
2319 new->name = name ? xstrdup (name) : NULL;
2320 new->command_line_arg = command_line_arg;
2321 new->next = pending_dirs;
2325 /* Read directory NAME, and list the files in it.
2326 If REALNAME is nonzero, print its name instead of NAME;
2327 this is used for symbolic links to directories.
2328 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2331 print_dir (char const *name, char const *realname, bool command_line_arg)
2334 struct dirent *next;
2335 uintmax_t total_blocks = 0;
2336 static bool first = true;
2339 dirp = opendir (name);
2342 file_failure (command_line_arg, _("cannot open directory %s"), name);
2348 struct stat dir_stat;
2349 int fd = dirfd (dirp);
2351 /* If dirfd failed, endure the overhead of using stat. */
2353 ? fstat (fd, &dir_stat)
2354 : stat (name, &dir_stat)) < 0)
2356 file_failure (command_line_arg,
2357 _("cannot determine device and inode of %s"), name);
2362 /* If we've already visited this dev/inode pair, warn that
2363 we've found a loop, and do not process this directory. */
2364 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2366 error (0, 0, _("%s: not listing already-listed directory"),
2367 quotearg_colon (name));
2372 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2375 /* Read the directory entries, and insert the subfiles into the `cwd_file'
2382 /* Set errno to zero so we can distinguish between a readdir failure
2383 and when readdir simply finds that there are no more entries. */
2385 next = readdir (dirp);
2388 if (! file_ignored (next->d_name))
2390 enum filetype type = unknown;
2392 #if HAVE_STRUCT_DIRENT_D_TYPE
2393 switch (next->d_type)
2395 case DT_BLK: type = blockdev; break;
2396 case DT_CHR: type = chardev; break;
2397 case DT_DIR: type = directory; break;
2398 case DT_FIFO: type = fifo; break;
2399 case DT_LNK: type = symbolic_link; break;
2400 case DT_REG: type = normal; break;
2401 case DT_SOCK: type = sock; break;
2403 case DT_WHT: type = whiteout; break;
2407 total_blocks += gobble_file (next->d_name, type, D_INO (next),
2411 else if (errno != 0)
2413 file_failure (command_line_arg, _("reading directory %s"), name);
2414 if (errno != EOVERFLOW)
2421 if (closedir (dirp) != 0)
2423 file_failure (command_line_arg, _("closing directory %s"), name);
2424 /* Don't return; print whatever we got. */
2427 /* Sort the directory contents. */
2430 /* If any member files are subdirectories, perhaps they should have their
2431 contents listed rather than being mentioned here as files. */
2434 extract_dirs_from_files (name, command_line_arg);
2436 if (recursive | print_dir_name)
2439 DIRED_PUTCHAR ('\n');
2442 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2443 dired_pos += quote_name (stdout, realname ? realname : name,
2444 dirname_quoting_options, NULL);
2445 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2446 DIRED_FPUTS_LITERAL (":\n", stdout);
2449 if (format == long_format || print_block_size)
2452 char buf[LONGEST_HUMAN_READABLE + 1];
2456 DIRED_FPUTS (p, stdout, strlen (p));
2457 DIRED_PUTCHAR (' ');
2458 p = human_readable (total_blocks, buf, human_output_opts,
2459 ST_NBLOCKSIZE, output_block_size);
2460 DIRED_FPUTS (p, stdout, strlen (p));
2461 DIRED_PUTCHAR ('\n');
2465 print_current_files ();
2468 /* Add `pattern' to the list of patterns for which files that match are
2472 add_ignore_pattern (const char *pattern)
2474 struct ignore_pattern *ignore;
2476 ignore = xmalloc (sizeof *ignore);
2477 ignore->pattern = pattern;
2478 /* Add it to the head of the linked list. */
2479 ignore->next = ignore_patterns;
2480 ignore_patterns = ignore;
2483 /* Return true if one of the PATTERNS matches FILE. */
2486 patterns_match (struct ignore_pattern const *patterns, char const *file)
2488 struct ignore_pattern const *p;
2489 for (p = patterns; p; p = p->next)
2490 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2495 /* Return true if FILE should be ignored. */
2498 file_ignored (char const *name)
2500 return ((ignore_mode != IGNORE_MINIMAL
2502 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2503 || (ignore_mode == IGNORE_DEFAULT
2504 && patterns_match (hide_patterns, name))
2505 || patterns_match (ignore_patterns, name));
2508 /* POSIX requires that a file size be printed without a sign, even
2509 when negative. Assume the typical case where negative sizes are
2510 actually positive values that have wrapped around. */
2513 unsigned_file_size (off_t size)
2515 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2518 /* Enter and remove entries in the table `cwd_file'. */
2520 /* Empty the table of files. */
2527 for (i = 0; i < cwd_n_used; i++)
2529 struct fileinfo *f = sorted_file[i];
2532 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
2533 freecon (f->scontext);
2537 any_has_acl = false;
2538 inode_number_width = 0;
2539 block_size_width = 0;
2545 major_device_number_width = 0;
2546 minor_device_number_width = 0;
2547 file_size_width = 0;
2550 /* Add a file to the current table of files.
2551 Verify that the file exists, and print an error message if it does not.
2552 Return the number of blocks that the file occupies. */
2555 gobble_file (char const *name, enum filetype type, ino_t inode,
2556 bool command_line_arg, char const *dirname)
2558 uintmax_t blocks = 0;
2561 /* An inode value prior to gobble_file necessarily came from readdir,
2562 which is not used for command line arguments. */
2563 assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2565 if (cwd_n_used == cwd_n_alloc)
2567 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
2571 f = &cwd_file[cwd_n_used];
2572 memset (f, '\0', sizeof *f);
2573 f->stat.st_ino = inode;
2576 if (command_line_arg
2577 || format_needs_stat
2578 /* When coloring a directory (we may know the type from
2579 direct.d_type), we have to stat it in order to indicate
2580 sticky and/or other-writable attributes. */
2581 || (type == directory && print_with_color)
2582 /* When dereferencing symlinks, the inode and type must come from
2583 stat, but readdir provides the inode and type of lstat. */
2584 || ((print_inode || format_needs_type)
2585 && (type == symbolic_link || type == unknown)
2586 && (dereference == DEREF_ALWAYS
2587 || (command_line_arg && dereference != DEREF_NEVER)
2588 || color_symlink_as_referent || check_symlink_color))
2589 /* Command line dereferences are already taken care of by the above
2590 assertion that the inode number is not yet known. */
2591 || (print_inode && inode == NOT_AN_INODE_NUMBER)
2592 || (format_needs_type
2593 && (type == unknown || command_line_arg
2594 /* --indicator-style=classify (aka -F)
2595 requires that we stat each regular file
2596 to see if it's executable. */
2597 || (type == normal && (indicator_style == classify
2598 /* This is so that --color ends up
2599 highlighting files with the executable
2600 bit set even when options like -F are
2602 || (print_with_color
2603 && is_colored (C_EXEC))
2607 /* Absolute name of this file. */
2608 char *absolute_name;
2612 if (name[0] == '/' || dirname[0] == 0)
2613 absolute_name = (char *) name;
2616 absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2617 attach (absolute_name, dirname, name);
2620 switch (dereference)
2623 err = stat (absolute_name, &f->stat);
2627 case DEREF_COMMAND_LINE_ARGUMENTS:
2628 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2629 if (command_line_arg)
2632 err = stat (absolute_name, &f->stat);
2635 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2638 need_lstat = (err < 0
2640 : ! S_ISDIR (f->stat.st_mode));
2644 /* stat failed because of ENOENT, maybe indicating a dangling
2645 symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
2646 directory, and --dereference-command-line-symlink-to-dir is
2647 in effect. Fall through so that we call lstat instead. */
2650 default: /* DEREF_NEVER */
2651 err = lstat (absolute_name, &f->stat);
2658 /* Failure to stat a command line argument leads to
2659 an exit status of 2. For other files, stat failure
2660 provokes an exit status of 1. */
2661 file_failure (command_line_arg,
2662 _("cannot access %s"), absolute_name);
2663 if (command_line_arg)
2666 f->name = xstrdup (name);
2674 if (format == long_format || print_scontext)
2676 bool have_acl = false;
2677 int attr_len = (do_deref
2678 ? getfilecon (absolute_name, &f->scontext)
2679 : lgetfilecon (absolute_name, &f->scontext));
2680 err = (attr_len < 0);
2682 /* Contrary to its documented API, getfilecon may return 0,
2683 yet set f->scontext to NULL (on at least Debian's libselinux1
2684 2.0.15-2+b1), so work around that bug.
2685 FIXME: remove this work-around in 2011, or whenever affected
2686 versions of libselinux are long gone. */
2690 f->scontext = xstrdup ("unlabeled");
2694 have_acl = ! STREQ ("unlabeled", f->scontext);
2697 f->scontext = UNKNOWN_SECURITY_CONTEXT;
2699 /* When requesting security context information, don't make
2700 ls fail just because the file (even a command line argument)
2701 isn't on the right type of file system. I.e., a getfilecon
2702 failure isn't in the same class as a stat failure. */
2703 if (errno == ENOTSUP || errno == ENODATA)
2707 if (err == 0 && ! have_acl && format == long_format)
2709 int n = file_has_acl (absolute_name, &f->stat);
2714 f->have_acl = have_acl;
2715 any_has_acl |= have_acl;
2718 error (0, errno, "%s", quotearg_colon (absolute_name));
2721 if (S_ISLNK (f->stat.st_mode)
2722 && (format == long_format || check_symlink_color))
2725 struct stat linkstats;
2727 get_link_name (absolute_name, f, command_line_arg);
2728 linkname = make_link_name (absolute_name, f->linkname);
2730 /* Avoid following symbolic links when possible, ie, when
2731 they won't be traced and when no indicator is needed. */
2733 && (file_type <= indicator_style || check_symlink_color)
2734 && stat (linkname, &linkstats) == 0)
2738 /* Symbolic links to directories that are mentioned on the
2739 command line are automatically traced if not being
2741 if (!command_line_arg || format == long_format
2742 || !S_ISDIR (linkstats.st_mode))
2744 /* Get the linked-to file's mode for the filetype indicator
2745 in long listings. */
2746 f->linkmode = linkstats.st_mode;
2752 /* When not distinguishing types of symlinks, pretend we know that
2753 it is stat'able, so that it will be colored as a regular symlink,
2754 and not as an orphan. */
2755 if (S_ISLNK (f->stat.st_mode) && !check_symlink_color)
2758 if (S_ISLNK (f->stat.st_mode))
2759 f->filetype = symbolic_link;
2760 else if (S_ISDIR (f->stat.st_mode))
2762 if (command_line_arg & !immediate_dirs)
2763 f->filetype = arg_directory;
2765 f->filetype = directory;
2768 f->filetype = normal;
2770 blocks = ST_NBLOCKS (f->stat);
2771 if (format == long_format || print_block_size)
2773 char buf[LONGEST_HUMAN_READABLE + 1];
2774 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
2775 ST_NBLOCKSIZE, output_block_size),
2777 if (block_size_width < len)
2778 block_size_width = len;
2781 if (format == long_format)
2785 int len = format_user_width (f->stat.st_uid);
2786 if (owner_width < len)
2792 int len = format_group_width (f->stat.st_gid);
2793 if (group_width < len)
2799 int len = format_user_width (f->stat.st_author);
2800 if (author_width < len)
2807 int len = strlen (f->scontext);
2808 if (scontext_width < len)
2809 scontext_width = len;
2812 if (format == long_format)
2814 char b[INT_BUFSIZE_BOUND (uintmax_t)];
2815 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
2816 if (nlink_width < b_len)
2817 nlink_width = b_len;
2819 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2821 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2822 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2823 if (major_device_number_width < len)
2824 major_device_number_width = len;
2825 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2826 if (minor_device_number_width < len)
2827 minor_device_number_width = len;
2828 len = major_device_number_width + 2 + minor_device_number_width;
2829 if (file_size_width < len)
2830 file_size_width = len;
2834 char buf[LONGEST_HUMAN_READABLE + 1];
2835 uintmax_t size = unsigned_file_size (f->stat.st_size);
2836 int len = mbswidth (human_readable (size, buf, human_output_opts,
2837 1, file_output_block_size),
2839 if (file_size_width < len)
2840 file_size_width = len;
2847 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2848 int len = strlen (umaxtostr (f->stat.st_ino, buf));
2849 if (inode_number_width < len)
2850 inode_number_width = len;
2853 f->name = xstrdup (name);
2859 /* Return true if F refers to a directory. */
2861 is_directory (const struct fileinfo *f)
2863 return f->filetype == directory || f->filetype == arg_directory;
2866 /* Put the name of the file that FILENAME is a symbolic link to
2867 into the LINKNAME field of `f'. COMMAND_LINE_ARG indicates whether
2868 FILENAME is a command-line argument. */
2871 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
2873 f->linkname = areadlink_with_size (filename, f->stat.st_size);
2874 if (f->linkname == NULL)
2875 file_failure (command_line_arg, _("cannot read symbolic link %s"),
2879 /* If `linkname' is a relative name and `name' contains one or more
2880 leading directories, return `linkname' with those directories
2881 prepended; otherwise, return a copy of `linkname'.
2882 If `linkname' is zero, return zero. */
2885 make_link_name (char const *name, char const *linkname)
2893 if (*linkname == '/')
2894 return xstrdup (linkname);
2896 /* The link is to a relative name. Prepend any leading directory
2897 in `name' to the link name. */
2898 linkbuf = strrchr (name, '/');
2900 return xstrdup (linkname);
2902 bufsiz = linkbuf - name + 1;
2903 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2904 strncpy (linkbuf, name, bufsiz);
2905 strcpy (linkbuf + bufsiz, linkname);
2909 /* Return true if the last component of NAME is `.' or `..'
2910 This is so we don't try to recurse on `././././. ...' */
2913 basename_is_dot_or_dotdot (const char *name)
2915 char const *base = last_component (name);
2916 return dot_or_dotdot (base);
2919 /* Remove any entries from CWD_FILE that are for directories,
2920 and queue them to be listed as directories instead.
2921 DIRNAME is the prefix to prepend to each dirname
2922 to make it correct relative to ls's working dir;
2923 if it is null, no prefix is needed and "." and ".." should not be ignored.
2924 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
2925 This is desirable when processing directories recursively. */
2928 extract_dirs_from_files (char const *dirname, bool command_line_arg)
2932 bool ignore_dot_and_dot_dot = (dirname != NULL);
2934 if (dirname && LOOP_DETECT)
2936 /* Insert a marker entry first. When we dequeue this marker entry,
2937 we'll know that DIRNAME has been processed and may be removed
2938 from the set of active directories. */
2939 queue_directory (NULL, dirname, false);
2942 /* Queue the directories last one first, because queueing reverses the
2944 for (i = cwd_n_used; i-- != 0; )
2946 struct fileinfo *f = sorted_file[i];
2948 if (is_directory (f)
2949 && (! ignore_dot_and_dot_dot
2950 || ! basename_is_dot_or_dotdot (f->name)))
2952 if (!dirname || f->name[0] == '/')
2953 queue_directory (f->name, f->linkname, command_line_arg);
2956 char *name = file_name_concat (dirname, f->name, NULL);
2957 queue_directory (name, f->linkname, command_line_arg);
2960 if (f->filetype == arg_directory)
2965 /* Now delete the directories from the table, compacting all the remaining
2968 for (i = 0, j = 0; i < cwd_n_used; i++)
2970 struct fileinfo *f = sorted_file[i];
2972 j += (f->filetype != arg_directory);
2977 /* Use strcoll to compare strings in this locale. If an error occurs,
2978 report an error and longjmp to failed_strcoll. */
2980 static jmp_buf failed_strcoll;
2983 xstrcoll (char const *a, char const *b)
2987 diff = strcoll (a, b);
2990 error (0, errno, _("cannot compare file names %s and %s"),
2991 quote_n (0, a), quote_n (1, b));
2992 set_exit_status (false);
2993 longjmp (failed_strcoll, 1);
2998 /* Comparison routines for sorting the files. */
3000 typedef void const *V;
3001 typedef int (*qsortFunc)(V a, V b);
3003 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
3004 The do { ... } while(0) makes it possible to use the macro more like
3005 a statement, without violating C89 rules: */
3006 #define DIRFIRST_CHECK(a, b) \
3009 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
3010 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
3011 if (a_is_dir && !b_is_dir) \
3012 return -1; /* a goes before b */ \
3013 if (!a_is_dir && b_is_dir) \
3014 return 1; /* b goes before a */ \
3018 /* Define the 8 different sort function variants required for each sortkey.
3019 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3020 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3021 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3022 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3023 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3024 /* direct, non-dirfirst versions */ \
3025 static int xstrcoll_##key_name (V a, V b) \
3026 { return key_cmp_func (a, b, xstrcoll); } \
3027 static int strcmp_##key_name (V a, V b) \
3028 { return key_cmp_func (a, b, strcmp); } \
3030 /* reverse, non-dirfirst versions */ \
3031 static int rev_xstrcoll_##key_name (V a, V b) \
3032 { return key_cmp_func (b, a, xstrcoll); } \
3033 static int rev_strcmp_##key_name (V a, V b) \
3034 { return key_cmp_func (b, a, strcmp); } \
3036 /* direct, dirfirst versions */ \
3037 static int xstrcoll_df_##key_name (V a, V b) \
3038 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
3039 static int strcmp_df_##key_name (V a, V b) \
3040 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
3042 /* reverse, dirfirst versions */ \
3043 static int rev_xstrcoll_df_##key_name (V a, V b) \
3044 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
3045 static int rev_strcmp_df_##key_name (V a, V b) \
3046 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
3049 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3050 int (*cmp) (char const *, char const *))
3052 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3053 get_stat_ctime (&a->stat));
3054 return diff ? diff : cmp (a->name, b->name);
3058 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3059 int (*cmp) (char const *, char const *))
3061 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3062 get_stat_mtime (&a->stat));
3063 return diff ? diff : cmp (a->name, b->name);
3067 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3068 int (*cmp) (char const *, char const *))
3070 int diff = timespec_cmp (get_stat_atime (&b->stat),
3071 get_stat_atime (&a->stat));
3072 return diff ? diff : cmp (a->name, b->name);
3076 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3077 int (*cmp) (char const *, char const *))
3079 int diff = longdiff (b->stat.st_size, a->stat.st_size);
3080 return diff ? diff : cmp (a->name, b->name);
3084 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3085 int (*cmp) (char const *, char const *))
3087 return cmp (a->name, b->name);
3090 /* Compare file extensions. Files with no extension are `smallest'.
3091 If extensions are the same, compare by filenames instead. */
3094 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3095 int (*cmp) (char const *, char const *))
3097 char const *base1 = strrchr (a->name, '.');
3098 char const *base2 = strrchr (b->name, '.');
3099 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3100 return diff ? diff : cmp (a->name, b->name);
3103 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3104 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3105 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3106 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3107 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3108 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3110 /* Compare file versions.
3111 Unlike all other compare functions above, cmp_version depends only
3112 on strverscmp, which does not fail (even for locale reasons), and does not
3113 need a secondary sort key.
3114 All the other sort options, in fact, need xstrcoll and strcmp variants,
3115 because they all use a string comparison (either as the primary or secondary
3116 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3117 locale reasons. Last, strverscmp is ALWAYS available in coreutils,
3118 thanks to the gnulib library. */
3120 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3122 return strverscmp (a->name, b->name);
3125 static int xstrcoll_version (V a, V b)
3126 { return cmp_version (a, b); }
3127 static int rev_xstrcoll_version (V a, V b)
3128 { return cmp_version (b, a); }
3129 static int xstrcoll_df_version (V a, V b)
3130 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3131 static int rev_xstrcoll_df_version (V a, V b)
3132 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3135 /* We have 2^3 different variants for each sortkey function
3136 (for 3 independent sort modes).
3137 The function pointers stored in this array must be dereferenced as:
3139 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3141 Note that the order in which sortkeys are listed in the function pointer
3142 array below is defined by the order of the elements in the time_type and
3145 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3148 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3149 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3152 { strcmp_##key_name, strcmp_df_##key_name }, \
3153 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3157 static qsortFunc sort_functions[][2][2][2] =
3159 LIST_SORTFUNCTION_VARIANTS (name),
3160 LIST_SORTFUNCTION_VARIANTS (extension),
3161 LIST_SORTFUNCTION_VARIANTS (size),
3165 { xstrcoll_version, xstrcoll_df_version },
3166 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3169 /* We use NULL for the strcmp variants of version comparison
3170 since as explained in cmp_version definition, version comparison
3171 does not rely on xstrcoll, so it will never longjmp, and never
3172 need to try the strcmp fallback. */
3179 /* last are time sort functions */
3180 LIST_SORTFUNCTION_VARIANTS (mtime),
3181 LIST_SORTFUNCTION_VARIANTS (ctime),
3182 LIST_SORTFUNCTION_VARIANTS (atime)
3185 /* The number of sortkeys is calculated as
3186 the number of elements in the sort_type enum (i.e. sort_numtypes) +
3187 the number of elements in the time_type enum (i.e. time_numtypes) - 1
3188 This is because when sort_type==sort_time, we have up to
3189 time_numtypes possible sortkeys.
3191 This line verifies at compile-time that the array of sort functions has been
3192 initialized for all possible sortkeys. */
3193 verify (ARRAY_CARDINALITY (sort_functions)
3194 == sort_numtypes + time_numtypes - 1 );
3196 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
3199 initialize_ordering_vector (void)
3202 for (i = 0; i < cwd_n_used; i++)
3203 sorted_file[i] = &cwd_file[i];
3206 /* Sort the files now in the table. */
3213 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
3216 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
3217 sorted_file_alloc = 3 * cwd_n_used;
3220 initialize_ordering_vector ();
3222 if (sort_type == sort_none)
3225 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3226 ignore strcoll failures, as a failing strcoll might be a
3227 comparison function that is not a total order, and if we ignored
3228 the failure this might cause qsort to dump core. */
3230 if (! setjmp (failed_strcoll))
3231 use_strcmp = false; /* strcoll() succeeded */
3235 assert (sort_type != sort_version);
3236 initialize_ordering_vector ();
3239 /* When sort_type == sort_time, use time_type as subindex. */
3240 mpsort ((void const **) sorted_file, cwd_n_used,
3241 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
3242 [use_strcmp][sort_reverse]
3243 [directories_first]);
3246 /* List all the files now in the table. */
3249 print_current_files (void)
3256 for (i = 0; i < cwd_n_used; i++)
3258 print_file_name_and_frills (sorted_file[i]);
3264 print_many_per_line ();
3268 print_horizontal ();
3272 print_with_commas ();
3276 for (i = 0; i < cwd_n_used; i++)
3278 print_long_format (sorted_file[i]);
3279 DIRED_PUTCHAR ('\n');
3285 /* Return the expected number of columns in a long-format time stamp,
3286 or zero if it cannot be calculated. */
3289 long_time_expected_width (void)
3291 static int width = -1;
3296 struct tm const *tm = localtime (&epoch);
3297 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3299 /* In case you're wondering if localtime can fail with an input time_t
3300 value of 0, let's just say it's very unlikely, but not inconceivable.
3301 The TZ environment variable would have to specify a time zone that
3302 is 2**31-1900 years or more ahead of UTC. This could happen only on
3303 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3304 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3305 their implementations limit the offset to 167:59 and 24:00, resp. */
3309 nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3311 width = mbsnwidth (buf, len, 0);
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 */
3420 struct timespec when_timespec;
3421 struct tm *when_local;
3423 /* Compute the mode string, except remove the trailing space if no
3424 file in this directory has an ACL or SELinux security context. */
3426 filemodestring (&f->stat, modebuf);
3429 modebuf[0] = filetype_letter[f->filetype];
3430 memset (modebuf + 1, '?', 10);
3435 else if (f->have_acl)
3441 when_timespec = get_stat_ctime (&f->stat);
3444 when_timespec = get_stat_mtime (&f->stat);
3447 when_timespec = get_stat_atime (&f->stat);
3457 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3458 sprintf (p, "%*s ", inode_number_width,
3459 (f->stat.st_ino == NOT_AN_INODE_NUMBER
3461 : umaxtostr (f->stat.st_ino, hbuf)));
3462 /* Increment by strlen (p) here, rather than by inode_number_width + 1.
3463 The latter is wrong when inode_number_width is zero. */
3467 if (print_block_size)
3469 char hbuf[LONGEST_HUMAN_READABLE + 1];
3470 char const *blocks =
3473 : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3474 ST_NBLOCKSIZE, output_block_size));
3476 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3478 while ((*p++ = *blocks++))
3483 /* The last byte of the mode string is the POSIX
3484 "optional alternate access method flag". */
3486 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3487 sprintf (p, "%s %*s ", modebuf, nlink_width,
3488 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
3490 /* Increment by strlen (p) here, rather than by, e.g.,
3491 sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
3492 The latter is wrong when nlink_width is zero. */
3497 if (print_owner | print_group | print_author | print_scontext)
3499 DIRED_FPUTS (buf, stdout, p - buf);
3502 format_user (f->stat.st_uid, owner_width, f->stat_ok);
3505 format_group (f->stat.st_gid, group_width, f->stat_ok);
3508 format_user (f->stat.st_author, author_width, f->stat_ok);
3511 format_user_or_group (f->scontext, 0, scontext_width);
3517 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
3519 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3520 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3521 int blanks_width = (file_size_width
3522 - (major_device_number_width + 2
3523 + minor_device_number_width));
3524 sprintf (p, "%*s, %*s ",
3525 major_device_number_width + MAX (0, blanks_width),
3526 umaxtostr (major (f->stat.st_rdev), majorbuf),
3527 minor_device_number_width,
3528 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3529 p += file_size_width + 1;
3533 char hbuf[LONGEST_HUMAN_READABLE + 1];
3537 : human_readable (unsigned_file_size (f->stat.st_size),
3538 hbuf, human_output_opts, 1, file_output_block_size));
3540 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3542 while ((*p++ = *size++))
3547 when_local = localtime (&when_timespec.tv_sec);
3551 if (f->stat_ok && when_local)
3553 struct timespec six_months_ago;
3557 /* If the file appears to be in the future, update the current
3558 time, in case the file happens to have been modified since
3559 the last time we checked the clock. */
3560 if (timespec_cmp (current_time, when_timespec) < 0)
3562 /* Note that gettime may call gettimeofday which, on some non-
3563 compliant systems, clobbers the buffer used for localtime's result.
3564 But it's ok here, because we use a gettimeofday wrapper that
3565 saves and restores the buffer around the gettimeofday call. */
3566 gettime (¤t_time);
3569 /* Consider a time to be recent if it is within the past six
3570 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3571 31556952 seconds on the average. Write this value as an
3572 integer constant to avoid floating point hassles. */
3573 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
3574 six_months_ago.tv_nsec = current_time.tv_nsec;
3576 recent = (timespec_cmp (six_months_ago, when_timespec) < 0
3577 && (timespec_cmp (when_timespec, current_time) < 0));
3578 fmt = long_time_format[recent];
3580 /* We assume here that all time zones are offset from UTC by a
3581 whole number of seconds. */
3582 s = nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3583 when_local, 0, when_timespec.tv_nsec);
3591 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3596 /* The time cannot be converted using the desired format, so
3597 print it as a huge integer number of seconds. */
3598 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3599 sprintf (p, "%*s ", long_time_expected_width (),
3602 : (TYPE_SIGNED (time_t)
3603 ? imaxtostr (when_timespec.tv_sec, hbuf)
3604 : umaxtostr (when_timespec.tv_sec, hbuf))));
3605 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
3609 DIRED_FPUTS (buf, stdout, p - buf);
3610 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3611 f->stat_ok, f->filetype, &dired_obstack);
3613 if (f->filetype == symbolic_link)
3617 DIRED_FPUTS_LITERAL (" -> ", stdout);
3618 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3619 f->stat_ok, f->filetype, NULL);
3620 if (indicator_style != none)
3621 print_type_indicator (true, f->linkmode, unknown);
3624 else if (indicator_style != none)
3625 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3628 /* Output to OUT a quoted representation of the file name NAME,
3629 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3630 Store the number of screen columns occupied by NAME's quoted
3631 representation into WIDTH, if non-NULL. Return the number of bytes
3635 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3638 char smallbuf[BUFSIZ];
3639 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3641 size_t displayed_width IF_LINT (= 0);
3643 if (len < sizeof smallbuf)
3647 buf = alloca (len + 1);
3648 quotearg_buffer (buf, len + 1, name, -1, options);
3651 if (qmark_funny_chars)
3656 char const *p = buf;
3657 char const *plimit = buf + len;
3659 displayed_width = 0;
3664 case ' ': case '!': case '"': case '#': case '%':
3665 case '&': case '\'': case '(': case ')': case '*':
3666 case '+': case ',': case '-': case '.': case '/':
3667 case '0': case '1': case '2': case '3': case '4':
3668 case '5': case '6': case '7': case '8': case '9':
3669 case ':': case ';': case '<': case '=': case '>':
3671 case 'A': case 'B': case 'C': case 'D': case 'E':
3672 case 'F': case 'G': case 'H': case 'I': case 'J':
3673 case 'K': case 'L': case 'M': case 'N': case 'O':
3674 case 'P': case 'Q': case 'R': case 'S': case 'T':
3675 case 'U': case 'V': case 'W': case 'X': case 'Y':
3677 case '[': case '\\': case ']': case '^': case '_':
3678 case 'a': case 'b': case 'c': case 'd': case 'e':
3679 case 'f': case 'g': case 'h': case 'i': case 'j':
3680 case 'k': case 'l': case 'm': case 'n': case 'o':
3681 case 'p': case 'q': case 'r': case 's': case 't':
3682 case 'u': case 'v': case 'w': case 'x': case 'y':
3683 case 'z': case '{': case '|': case '}': case '~':
3684 /* These characters are printable ASCII characters. */
3686 displayed_width += 1;
3689 /* If we have a multibyte sequence, copy it until we
3690 reach its end, replacing each non-printable multibyte
3691 character with a single question mark. */
3693 mbstate_t mbstate = { 0, };
3700 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3702 if (bytes == (size_t) -1)
3704 /* An invalid multibyte sequence was
3705 encountered. Skip one input byte, and
3706 put a question mark. */
3709 displayed_width += 1;
3713 if (bytes == (size_t) -2)
3715 /* An incomplete multibyte character
3716 at the end. Replace it entirely with
3720 displayed_width += 1;
3725 /* A null wide character was encountered. */
3731 /* A printable multibyte character.
3733 for (; bytes > 0; --bytes)
3735 displayed_width += w;
3739 /* An unprintable multibyte character.
3740 Replace it entirely with a question
3744 displayed_width += 1;
3747 while (! mbsinit (&mbstate));
3752 /* The buffer may have shrunk. */
3759 char const *plimit = buf + len;
3763 if (! isprint (to_uchar (*p)))
3767 displayed_width = len;
3770 else if (width != NULL)
3774 displayed_width = mbsnwidth (buf, len, 0);
3778 char const *p = buf;
3779 char const *plimit = buf + len;
3781 displayed_width = 0;
3784 if (isprint (to_uchar (*p)))
3792 fwrite (buf, 1, len, out);
3794 *width = displayed_width;
3799 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3800 bool stat_ok, enum filetype type,
3801 struct obstack *stack)
3803 bool used_color_this_time
3805 && print_color_indicator (p, mode, linkok, stat_ok, type));
3808 PUSH_CURRENT_DIRED_POS (stack);
3810 dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3813 PUSH_CURRENT_DIRED_POS (stack);
3815 if (used_color_this_time)
3818 prep_non_filename_text ();
3823 prep_non_filename_text (void)
3825 if (color_indicator[C_END].string != NULL)
3826 put_indicator (&color_indicator[C_END]);
3829 put_indicator (&color_indicator[C_LEFT]);
3830 put_indicator (&color_indicator[C_RESET]);
3831 put_indicator (&color_indicator[C_RIGHT]);
3835 /* Print the file name of `f' with appropriate quoting.
3836 Also print file size, inode number, and filetype indicator character,
3837 as requested by switches. */
3840 print_file_name_and_frills (const struct fileinfo *f)
3842 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3845 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
3846 umaxtostr (f->stat.st_ino, buf));
3848 if (print_block_size)
3849 printf ("%*s ", format == with_commas ? 0 : block_size_width,
3850 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3851 ST_NBLOCKSIZE, output_block_size));
3854 printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
3856 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3857 f->stat_ok, f->filetype, NULL);
3859 if (indicator_style != none)
3860 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3863 /* Given these arguments describing a file, return the single-byte
3864 type indicator, or 0. */
3866 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3870 if (stat_ok ? S_ISREG (mode) : type == normal)
3872 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
3879 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
3881 else if (indicator_style == slash)
3883 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
3885 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
3887 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
3889 else if (stat_ok && S_ISDOOR (mode))
3898 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
3900 char c = get_type_indicator (stat_ok, mode, type);
3905 /* Returns whether any color sequence was printed. */
3907 print_color_indicator (const char *name, mode_t mode, int linkok,
3908 bool stat_ok, enum filetype filetype)
3911 struct color_ext_type *ext; /* Color extension */
3912 size_t len; /* Length of name */
3914 /* Is this a nonexistent file? If so, linkok == -1. */
3916 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3920 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
3921 type = filetype_indicator[filetype];
3928 if ((mode & S_ISUID) != 0)
3930 else if ((mode & S_ISGID) != 0)
3932 else if ((mode & S_IXUGO) != 0)
3935 else if (S_ISDIR (mode))
3937 if ((mode & S_ISVTX) && (mode & S_IWOTH))
3938 type = C_STICKY_OTHER_WRITABLE;
3939 else if ((mode & S_IWOTH) != 0)
3940 type = C_OTHER_WRITABLE;
3941 else if ((mode & S_ISVTX) != 0)
3946 else if (S_ISLNK (mode))
3947 type = ((!linkok && color_indicator[C_ORPHAN].string)
3948 ? C_ORPHAN : C_LINK);
3949 else if (S_ISFIFO (mode))
3951 else if (S_ISSOCK (mode))
3953 else if (S_ISBLK (mode))
3955 else if (S_ISCHR (mode))
3957 else if (S_ISDOOR (mode))
3961 /* Classify a file of some other type as C_ORPHAN. */
3966 /* Check the file's suffix only if still classified as C_FILE. */
3970 /* Test if NAME has a recognized suffix. */
3972 len = strlen (name);
3973 name += len; /* Pointer to final \0. */
3974 for (ext = color_ext_list; ext != NULL; ext = ext->next)
3976 if (ext->ext.len <= len
3977 && strncmp (name - ext->ext.len, ext->ext.string,
3984 const struct bin_str *const s
3985 = ext ? &(ext->seq) : &color_indicator[type];
3986 if (s->string != NULL)
3988 put_indicator (&color_indicator[C_LEFT]);
3990 put_indicator (&color_indicator[C_RIGHT]);
3998 /* Output a color indicator (which may contain nulls). */
4000 put_indicator (const struct bin_str *ind)
4005 prep_non_filename_text ();
4008 fwrite (ind->string, ind->len, 1, stdout);
4012 length_of_file_name_and_frills (const struct fileinfo *f)
4016 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4019 len += 1 + (format == with_commas
4020 ? strlen (umaxtostr (f->stat.st_ino, buf))
4021 : inode_number_width);
4023 if (print_block_size)
4024 len += 1 + (format == with_commas
4025 ? strlen (human_readable (ST_NBLOCKS (f->stat), buf,
4026 human_output_opts, ST_NBLOCKSIZE,
4028 : block_size_width);
4031 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
4033 quote_name (NULL, f->name, filename_quoting_options, &name_width);
4036 if (indicator_style != none)
4038 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4046 print_many_per_line (void)
4048 size_t row; /* Current row. */
4049 size_t cols = calculate_columns (true);
4050 struct column_info const *line_fmt = &column_info[cols - 1];
4052 /* Calculate the number of rows that will be in each column except possibly
4053 for a short column on the right. */
4054 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
4056 for (row = 0; row < rows; row++)
4059 size_t filesno = row;
4062 /* Print the next row. */
4065 struct fileinfo const *f = sorted_file[filesno];
4066 size_t name_length = length_of_file_name_and_frills (f);
4067 size_t max_name_length = line_fmt->col_arr[col++];
4068 print_file_name_and_frills (f);
4071 if (filesno >= cwd_n_used)
4074 indent (pos + name_length, pos + max_name_length);
4075 pos += max_name_length;
4082 print_horizontal (void)
4086 size_t cols = calculate_columns (false);
4087 struct column_info const *line_fmt = &column_info[cols - 1];
4088 struct fileinfo const *f = sorted_file[0];
4089 size_t name_length = length_of_file_name_and_frills (f);
4090 size_t max_name_length = line_fmt->col_arr[0];
4092 /* Print first entry. */
4093 print_file_name_and_frills (f);
4096 for (filesno = 1; filesno < cwd_n_used; ++filesno)
4098 size_t col = filesno % cols;
4107 indent (pos + name_length, pos + max_name_length);
4108 pos += max_name_length;
4111 f = sorted_file[filesno];
4112 print_file_name_and_frills (f);
4114 name_length = length_of_file_name_and_frills (f);
4115 max_name_length = line_fmt->col_arr[col];
4121 print_with_commas (void)
4126 for (filesno = 0; filesno < cwd_n_used; filesno++)
4128 struct fileinfo const *f = sorted_file[filesno];
4129 size_t len = length_of_file_name_and_frills (f);
4135 if (pos + len + 2 < line_length)
4147 putchar (separator);
4150 print_file_name_and_frills (f);
4156 /* Assuming cursor is at position FROM, indent up to position TO.
4157 Use a TAB character instead of two or more spaces whenever possible. */
4160 indent (size_t from, size_t to)
4164 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4167 from += tabsize - from % tabsize;
4177 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
4178 /* FIXME: maybe remove this function someday. See about using a
4179 non-malloc'ing version of file_name_concat. */
4182 attach (char *dest, const char *dirname, const char *name)
4184 const char *dirnamep = dirname;
4186 /* Copy dirname if it is not ".". */
4187 if (dirname[0] != '.' || dirname[1] != 0)
4190 *dest++ = *dirnamep++;
4191 /* Add '/' if `dirname' doesn't already end with it. */
4192 if (dirnamep > dirname && dirnamep[-1] != '/')
4200 /* Allocate enough column info suitable for the current number of
4201 files and display columns, and initialize the info to represent the
4202 narrowest possible columns. */
4205 init_column_info (void)
4208 size_t max_cols = MIN (max_idx, cwd_n_used);
4210 /* Currently allocated columns in column_info. */
4211 static size_t column_info_alloc;
4213 if (column_info_alloc < max_cols)
4215 size_t new_column_info_alloc;
4218 if (max_cols < max_idx / 2)
4220 /* The number of columns is far less than the display width
4221 allows. Grow the allocation, but only so that it's
4222 double the current requirements. If the display is
4223 extremely wide, this avoids allocating a lot of memory
4224 that is never needed. */
4225 column_info = xnrealloc (column_info, max_cols,
4226 2 * sizeof *column_info);
4227 new_column_info_alloc = 2 * max_cols;
4231 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4232 new_column_info_alloc = max_idx;
4235 /* Allocate the new size_t objects by computing the triangle
4236 formula n * (n + 1) / 2, except that we don't need to
4237 allocate the part of the triangle that we've already
4238 allocated. Check for address arithmetic overflow. */
4240 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4241 size_t s = column_info_alloc + 1 + new_column_info_alloc;
4242 size_t t = s * column_info_growth;
4243 if (s < new_column_info_alloc || t / column_info_growth != s)
4245 p = xnmalloc (t / 2, sizeof *p);
4248 /* Grow the triangle by parceling out the cells just allocated. */
4249 for (i = column_info_alloc; i < new_column_info_alloc; i++)
4251 column_info[i].col_arr = p;
4255 column_info_alloc = new_column_info_alloc;
4258 for (i = 0; i < max_cols; ++i)
4262 column_info[i].valid_len = true;
4263 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4264 for (j = 0; j <= i; ++j)
4265 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4269 /* Calculate the number of columns needed to represent the current set
4270 of files in the current display width. */
4273 calculate_columns (bool by_columns)
4275 size_t filesno; /* Index into cwd_file. */
4276 size_t cols; /* Number of files across. */
4278 /* Normally the maximum number of columns is determined by the
4279 screen width. But if few files are available this might limit it
4281 size_t max_cols = MIN (max_idx, cwd_n_used);
4283 init_column_info ();
4285 /* Compute the maximum number of possible columns. */
4286 for (filesno = 0; filesno < cwd_n_used; ++filesno)
4288 struct fileinfo const *f = sorted_file[filesno];
4289 size_t name_length = length_of_file_name_and_frills (f);
4292 for (i = 0; i < max_cols; ++i)
4294 if (column_info[i].valid_len)
4296 size_t idx = (by_columns
4297 ? filesno / ((cwd_n_used + i) / (i + 1))
4298 : filesno % (i + 1));
4299 size_t real_length = name_length + (idx == i ? 0 : 2);
4301 if (column_info[i].col_arr[idx] < real_length)
4303 column_info[i].line_len += (real_length
4304 - column_info[i].col_arr[idx]);
4305 column_info[i].col_arr[idx] = real_length;
4306 column_info[i].valid_len = (column_info[i].line_len
4313 /* Find maximum allowed columns. */
4314 for (cols = max_cols; 1 < cols; --cols)
4316 if (column_info[cols - 1].valid_len)
4326 if (status != EXIT_SUCCESS)
4327 fprintf (stderr, _("Try `%s --help' for more information.\n"),
4331 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4333 List information about the FILEs (the current directory by default).\n\
4334 Sort entries alphabetically if none of -cftuvSUX nor --sort.\n\
4338 Mandatory arguments to long options are mandatory for short options too.\n\
4341 -a, --all do not ignore entries starting with .\n\
4342 -A, --almost-all do not list implied . and ..\n\
4343 --author with -l, print the author of each file\n\
4344 -b, --escape print octal escapes for nongraphic characters\n\
4347 --block-size=SIZE use SIZE-byte blocks\n\
4348 -B, --ignore-backups do not list implied entries ending with ~\n\
4349 -c with -lt: sort by, and show, ctime (time of last\n\
4350 modification of file status information)\n\
4351 with -l: show ctime and sort by name\n\
4352 otherwise: sort by ctime\n\
4355 -C list entries by columns\n\
4356 --color[=WHEN] control whether color is used to distinguish file\n\
4357 types. WHEN may be `never', `always', or `auto'\n\
4358 -d, --directory list directory entries instead of contents,\n\
4359 and do not dereference symbolic links\n\
4360 -D, --dired generate output designed for Emacs' dired mode\n\
4363 -f do not sort, enable -aU, disable -ls --color\n\
4364 -F, --classify append indicator (one of */=>@|) to entries\n\
4365 --file-type likewise, except do not append `*'\n\
4366 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
4367 single-column -1, verbose -l, vertical -C\n\
4368 --full-time like -l --time-style=full-iso\n\
4371 -g like -l, but do not list owner\n\
4374 --group-directories-first\n\
4375 group directories before files.\n\
4376 augment with a --sort option, but any\n\
4377 use of --sort=none (-U) disables grouping\n\
4380 -G, --no-group in a long listing, don't print group names\n\
4381 -h, --human-readable with -l, print sizes in human readable format\n\
4382 (e.g., 1K 234M 2G)\n\
4383 --si likewise, but use powers of 1000 not 1024\n\
4386 -H, --dereference-command-line\n\
4387 follow symbolic links listed on the command line\n\
4388 --dereference-command-line-symlink-to-dir\n\
4389 follow each command line symbolic link\n\
4390 that points to a directory\n\
4391 --hide=PATTERN do not list implied entries matching shell PATTERN\n\
4392 (overridden by -a or -A)\n\
4395 --indicator-style=WORD append indicator with style WORD to entry names:\n\
4396 none (default), slash (-p),\n\
4397 file-type (--file-type), classify (-F)\n\
4398 -i, --inode print the index number of each file\n\
4399 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
4400 -k like --block-size=1K\n\
4403 -l use a long listing format\n\
4404 -L, --dereference when showing file information for a symbolic\n\
4405 link, show information for the file the link\n\
4406 references rather than for the link itself\n\
4407 -m fill width with a comma separated list of entries\n\
4410 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
4411 -N, --literal print raw entry names (don't treat e.g. control\n\
4412 characters specially)\n\
4413 -o like -l, but do not list group information\n\
4414 -p, --indicator-style=slash\n\
4415 append / indicator to directories\n\
4418 -q, --hide-control-chars print ? instead of non graphic characters\n\
4419 --show-control-chars show non graphic characters as-is (default\n\
4420 unless program is `ls' and output is a terminal)\n\
4421 -Q, --quote-name enclose entry names in double quotes\n\
4422 --quoting-style=WORD use quoting style WORD for entry names:\n\
4423 literal, locale, shell, shell-always, c, escape\n\
4426 -r, --reverse reverse order while sorting\n\
4427 -R, --recursive list subdirectories recursively\n\
4428 -s, --size print the size of each file, in blocks\n\
4431 -S sort by file size\n\
4432 --sort=WORD sort by WORD instead of name: none -U,\n\
4433 extension -X, size -S, time -t, version -v\n\
4434 --time=WORD with -l, show time as WORD instead of modification\n\
4435 time: atime -u, access -u, use -u, ctime -c,\n\
4436 or status -c; use specified time as sort key\n\
4440 --time-style=STYLE with -l, show times using style STYLE:\n\
4441 full-iso, long-iso, iso, locale, +FORMAT.\n\
4442 FORMAT is interpreted like `date'; if FORMAT is\n\
4443 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4444 non-recent files and FORMAT2 to recent files;\n\
4445 if STYLE is prefixed with `posix-', STYLE\n\
4446 takes effect only outside the POSIX locale\n\
4449 -t sort by modification time\n\
4450 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4453 -u with -lt: sort by, and show, access time\n\
4454 with -l: show access time and sort by name\n\
4455 otherwise: sort by access time\n\
4456 -U do not sort; list entries in directory order\n\
4457 -v sort by version\n\
4460 -w, --width=COLS assume screen width instead of current value\n\
4461 -x list entries by lines instead of by columns\n\
4462 -X sort alphabetically by entry extension\n\
4463 -Z, --context print any SELinux security context of each file\n\
4464 -1 list one file per line\n\
4466 fputs (HELP_OPTION_DESCRIPTION, stdout);
4467 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4469 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4470 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4474 By default, color is not used to distinguish types of files. That is\n\
4475 equivalent to using --color=none. Using the --color option without the\n\
4476 optional WHEN argument is equivalent to using --color=always. With\n\
4477 --color=auto, color codes are output only if standard output is connected\n\
4478 to a terminal (tty). The environment variable LS_COLORS can influence the\n\
4479 colors, and can be set easily by the dircolors command.\n\
4483 Exit status is 0 if OK, 1 if minor problems, 2 if serious trouble.\n\
4485 emit_bug_reporting_address ();