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