.
[coreutils.git] / src / ls.c
blob00bb1fa9fbd92f47f09c7a4808694273be2a97da
1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-2003 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 2, or (at your option)
7 any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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.
28 If ls_mode is LS_LS,
29 the output format depends on whether the output
30 device is a terminal.
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>. */
39 #include <config.h>
40 #include <sys/types.h>
42 #if HAVE_TERMIOS_H
43 # include <termios.h>
44 #endif
46 #ifdef GWINSZ_IN_SYS_IOCTL
47 # include <sys/ioctl.h>
48 #endif
50 #ifdef WINSIZE_IN_PTEM
51 # include <sys/stream.h>
52 # include <sys/ptem.h>
53 #endif
55 #include <stdio.h>
56 #include <assert.h>
57 #include <setjmp.h>
58 #include <grp.h>
59 #include <pwd.h>
60 #include <getopt.h>
61 #include <signal.h>
63 /* Get mbstate_t, mbrtowc(), mbsinit(), wcwidth(). */
64 #if HAVE_WCHAR_H
65 # include <wchar.h>
66 #endif
68 /* Get iswprint(). */
69 #if HAVE_WCTYPE_H
70 # include <wctype.h>
71 #endif
72 #if !defined iswprint && !HAVE_ISWPRINT
73 # define iswprint(wc) 1
74 #endif
76 #ifndef HAVE_DECL_WCWIDTH
77 "this configure-time declaration test was not run"
78 #endif
79 #if !HAVE_DECL_WCWIDTH
80 int wcwidth ();
81 #endif
83 /* If wcwidth() doesn't exist, assume all printable characters have
84 width 1. */
85 #ifndef wcwidth
86 # if !HAVE_WCWIDTH
87 # define wcwidth(wc) ((wc) == 0 ? 0 : iswprint (wc) ? 1 : -1)
88 # endif
89 #endif
91 #include "system.h"
92 #include <fnmatch.h>
94 #include "acl.h"
95 #include "argmatch.h"
96 #include "dev-ino.h"
97 #include "dirname.h"
98 #include "dirfd.h"
99 #include "error.h"
100 #include "full-write.h"
101 #include "hard-locale.h"
102 #include "hash.h"
103 #include "human.h"
104 #include "filemode.h"
105 #include "inttostr.h"
106 #include "ls.h"
107 #include "mbswidth.h"
108 #include "obstack.h"
109 #include "path-concat.h"
110 #include "quote.h"
111 #include "quotearg.h"
112 #include "same.h"
113 #include "strftime.h"
114 #include "strverscmp.h"
115 #include "xstrtol.h"
116 #include "xreadlink.h"
118 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
119 : (ls_mode == LS_MULTI_COL \
120 ? "dir" : "vdir"))
122 #define AUTHORS "Richard Stallman", "David MacKenzie"
124 #define obstack_chunk_alloc malloc
125 #define obstack_chunk_free free
127 /* Return an int indicating the result of comparing two integers.
128 Subtracting doesn't always work, due to overflow. */
129 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
131 /* Arrange to make lstat calls go through the wrapper function
132 on systems with an lstat function that does not dereference symlinks
133 that are specified with a trailing slash. */
134 #if ! LSTAT_FOLLOWS_SLASHED_SYMLINK
135 int rpl_lstat (const char *, struct stat *);
136 # undef lstat
137 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
138 #endif
140 #if HAVE_STRUCT_DIRENT_D_TYPE && defined DTTOIF
141 # define DT_INIT(Val) = Val
142 #else
143 # define DT_INIT(Val) /* empty */
144 #endif
146 #ifdef ST_MTIM_NSEC
147 # define TIMESPEC_NS(timespec) ((timespec).ST_MTIM_NSEC)
148 #else
149 # define TIMESPEC_NS(timespec) 0
150 #endif
152 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
153 # define st_author st_uid
154 #endif
156 /* Cray/Unicos DMF: use the file's migrated, not real, status */
157 #if HAVE_ST_DM_MODE
158 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_dm_mode)
159 #else
160 # define ST_DM_MODE(Stat_buf) ((Stat_buf).st_mode)
161 #endif
163 enum filetype
165 unknown DT_INIT (DT_UNKNOWN),
166 fifo DT_INIT (DT_FIFO),
167 chardev DT_INIT (DT_CHR),
168 directory DT_INIT (DT_DIR),
169 blockdev DT_INIT (DT_BLK),
170 normal DT_INIT (DT_REG),
171 symbolic_link DT_INIT (DT_LNK),
172 sock DT_INIT (DT_SOCK),
173 arg_directory DT_INIT (2 * (DT_UNKNOWN | DT_FIFO | DT_CHR | DT_DIR | DT_BLK
174 | DT_REG | DT_LNK | DT_SOCK))
177 struct fileinfo
179 /* The file name. */
180 char *name;
182 struct stat stat;
184 /* For symbolic link, name of the file linked to, otherwise zero. */
185 char *linkname;
187 /* For symbolic link and long listing, st_mode of file linked to, otherwise
188 zero. */
189 mode_t linkmode;
191 /* For symbolic link and color printing, 1 if linked-to file
192 exists, otherwise 0. */
193 int linkok;
195 enum filetype filetype;
197 #if HAVE_ACL
198 /* For long listings, true if the file has an access control list. */
199 bool have_acl;
200 #endif
203 #if HAVE_ACL
204 # define FILE_HAS_ACL(F) ((F)->have_acl)
205 #else
206 # define FILE_HAS_ACL(F) 0
207 #endif
209 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
211 /* Null is a valid character in a color indicator (think about Epson
212 printers, for example) so we have to use a length/buffer string
213 type. */
215 struct bin_str
217 size_t len; /* Number of bytes */
218 const char *string; /* Pointer to the same */
221 #ifndef STDC_HEADERS
222 time_t time ();
223 #endif
225 char *getgroup ();
226 char *getuser ();
228 static size_t quote_name (FILE *out, const char *name,
229 struct quoting_options const *options,
230 size_t *width);
231 static char *make_link_path (const char *path, const char *linkname);
232 static int decode_switches (int argc, char **argv);
233 static int file_interesting (const struct dirent *next);
234 static uintmax_t gobble_file (const char *name, enum filetype type,
235 int explicit_arg, const char *dirname);
236 static void print_color_indicator (const char *name, mode_t mode, int linkok);
237 static void put_indicator (const struct bin_str *ind);
238 static int put_indicator_direct (const struct bin_str *ind);
239 static void add_ignore_pattern (const char *pattern);
240 static void attach (char *dest, const char *dirname, const char *name);
241 static void clear_files (void);
242 static void extract_dirs_from_files (const char *dirname,
243 int ignore_dot_and_dot_dot);
244 static void get_link_name (const char *filename, struct fileinfo *f);
245 static void indent (size_t from, size_t to);
246 static size_t calculate_columns (bool by_columns);
247 static void print_current_files (void);
248 static void print_dir (const char *name, const char *realname);
249 static void print_file_name_and_frills (const struct fileinfo *f);
250 static void print_horizontal (void);
251 static int format_user_width (uid_t u);
252 static int format_group_width (gid_t g);
253 static void print_long_format (const struct fileinfo *f);
254 static void print_many_per_line (void);
255 static void print_name_with_quoting (const char *p, mode_t mode,
256 int linkok,
257 struct obstack *stack);
258 static void prep_non_filename_text (void);
259 static void print_type_indicator (mode_t mode);
260 static void print_with_commas (void);
261 static void queue_directory (const char *name, const char *realname);
262 static void sort_files (void);
263 static void parse_ls_color (void);
264 void usage (int status);
266 /* The name the program was run with, stripped of any leading path. */
267 char *program_name;
269 /* Initial size of hash table.
270 Most hierarchies are likely to be shallower than this. */
271 #define INITIAL_TABLE_SIZE 30
273 /* The set of `active' directories, from the current command-line argument
274 to the level in the hierarchy at which files are being listed.
275 A directory is represented by its device and inode numbers (struct dev_ino).
276 A directory is added to this set when ls begins listing it or its
277 entries, and it is removed from the set just after ls has finished
278 processing it. This set is used solely to detect loops, e.g., with
279 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
280 static Hash_table *active_dir_set;
282 #define LOOP_DETECT (!!active_dir_set)
284 /* The table of files in the current directory:
286 `files' points to a vector of `struct fileinfo', one per file.
287 `nfiles' is the number of elements space has been allocated for.
288 `files_index' is the number actually in use. */
290 /* Address of block containing the files that are described. */
291 static struct fileinfo *files; /* FIXME: rename this to e.g. cwd_file */
293 /* Length of block that `files' points to, measured in files. */
294 static size_t nfiles; /* FIXME: rename this to e.g. cwd_n_alloc */
296 /* Index of first unused in `files'. */
297 static size_t files_index; /* FIXME: rename this to e.g. cwd_n_used */
299 /* When nonzero, in a color listing, color each symlink name according to the
300 type of file it points to. Otherwise, color them according to the `ln'
301 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
302 regardless. This is set when `ln=target' appears in LS_COLORS. */
304 static int color_symlink_as_referent;
306 /* mode of appropriate file for colorization */
307 #define FILE_OR_LINK_MODE(File) \
308 ((color_symlink_as_referent && (File)->linkok) \
309 ? (File)->linkmode : (File)->stat.st_mode)
312 /* Record of one pending directory waiting to be listed. */
314 struct pending
316 char *name;
317 /* If the directory is actually the file pointed to by a symbolic link we
318 were told to list, `realname' will contain the name of the symbolic
319 link, otherwise zero. */
320 char *realname;
321 struct pending *next;
324 static struct pending *pending_dirs;
326 /* Current time in seconds and nanoseconds since 1970, updated as
327 needed when deciding whether a file is recent. */
329 static time_t current_time = TYPE_MINIMUM (time_t);
330 static int current_time_ns = -1;
332 /* The number of bytes to use for columns containing inode numbers,
333 block sizes, link counts, owners, groups, authors, major device
334 numbers, minor device numbers, and file sizes, respectively. */
336 static int inode_number_width;
337 static int block_size_width;
338 static int nlink_width;
339 static int owner_width;
340 static int group_width;
341 static int author_width;
342 static int major_device_number_width;
343 static int minor_device_number_width;
344 static int file_size_width;
346 /* Option flags */
348 /* long_format for lots of info, one per line.
349 one_per_line for just names, one per line.
350 many_per_line for just names, many per line, sorted vertically.
351 horizontal for just names, many per line, sorted horizontally.
352 with_commas for just names, many per line, separated by commas.
354 -l (and other options that imply -l), -1, -C, -x and -m control
355 this parameter. */
357 enum format
359 long_format, /* -l and other options that imply -l */
360 one_per_line, /* -1 */
361 many_per_line, /* -C */
362 horizontal, /* -x */
363 with_commas /* -m */
366 static enum format format;
368 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
369 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
370 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
371 enum time_style
373 full_iso_time_style, /* --time-style=full-iso */
374 long_iso_time_style, /* --time-style=long-iso */
375 iso_time_style, /* --time-style=iso */
376 locale_time_style /* --time-style=locale */
379 static char const *const time_style_args[] =
381 "full-iso", "long-iso", "iso", "locale", 0
384 static enum time_style const time_style_types[] =
386 full_iso_time_style, long_iso_time_style, iso_time_style,
387 locale_time_style, 0
390 /* Type of time to print or sort by. Controlled by -c and -u. */
392 enum time_type
394 time_mtime, /* default */
395 time_ctime, /* -c */
396 time_atime /* -u */
399 static enum time_type time_type;
401 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v. */
403 enum sort_type
405 sort_none, /* -U */
406 sort_name, /* default */
407 sort_extension, /* -X */
408 sort_time, /* -t */
409 sort_size, /* -S */
410 sort_version /* -v */
413 static enum sort_type sort_type;
415 /* Direction of sort.
416 0 means highest first if numeric,
417 lowest first if alphabetic;
418 these are the defaults.
419 1 means the opposite order in each case. -r */
421 static int sort_reverse;
423 /* Nonzero means to display owner information. -g turns this off. */
425 static int print_owner = 1;
427 /* Nonzero means to display author information. */
429 static bool print_author;
431 /* Nonzero means to display group information. -G and -o turn this off. */
433 static int print_group = 1;
435 /* Nonzero means print the user and group id's as numbers rather
436 than as names. -n */
438 static int numeric_ids;
440 /* Nonzero means mention the size in blocks of each file. -s */
442 static int print_block_size;
444 /* Human-readable options for output. */
445 static int human_output_opts;
447 /* The units to use when printing sizes other than file sizes. */
448 static uintmax_t output_block_size;
450 /* Likewise, but for file sizes. */
451 static uintmax_t file_output_block_size = 1;
453 /* Precede each line of long output (per file) with a string like `m,n:'
454 where M is the number of characters after the `:' and before the
455 filename and N is the length of the filename. Using this format,
456 Emacs' dired mode starts up twice as fast, and can handle all
457 strange characters in file names. */
458 static int dired;
460 /* `none' means don't mention the type of files.
461 `classify' means mention file types and mark executables.
462 `file_type' means mention only file types.
464 Controlled by -F, -p, and --indicator-style. */
466 enum indicator_style
468 none, /* --indicator-style=none */
469 classify, /* -F, --indicator-style=classify */
470 file_type /* -p, --indicator-style=file-type */
473 static enum indicator_style indicator_style;
475 /* Names of indicator styles. */
476 static char const *const indicator_style_args[] =
478 "none", "classify", "file-type", 0
481 static enum indicator_style const indicator_style_types[]=
483 none, classify, file_type
486 /* Nonzero means use colors to mark types. Also define the different
487 colors as well as the stuff for the LS_COLORS environment variable.
488 The LS_COLORS variable is now in a termcap-like format. */
490 static int print_with_color;
492 enum color_type
494 color_never, /* 0: default or --color=never */
495 color_always, /* 1: --color=always */
496 color_if_tty /* 2: --color=tty */
499 enum Dereference_symlink
501 DEREF_UNDEFINED = 1,
502 DEREF_NEVER,
503 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
504 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
505 DEREF_ALWAYS /* -L */
508 enum indicator_no
510 C_LEFT, C_RIGHT, C_END, C_NORM, C_FILE, C_DIR, C_LINK, C_FIFO, C_SOCK,
511 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR
514 static const char *const indicator_name[]=
516 "lc", "rc", "ec", "no", "fi", "di", "ln", "pi", "so",
517 "bd", "cd", "mi", "or", "ex", "do", NULL
520 struct color_ext_type
522 struct bin_str ext; /* The extension we're looking for */
523 struct bin_str seq; /* The sequence to output when we do */
524 struct color_ext_type *next; /* Next in list */
527 static struct bin_str color_indicator[] =
529 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
530 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
531 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
532 { LEN_STR_PAIR ("0") }, /* no: Normal */
533 { LEN_STR_PAIR ("0") }, /* fi: File: default */
534 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
535 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
536 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
537 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
538 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
539 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
540 { 0, NULL }, /* mi: Missing file: undefined */
541 { 0, NULL }, /* or: Orphanned symlink: undefined */
542 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
543 { LEN_STR_PAIR ("01;35") } /* do: Door: bright magenta */
546 /* FIXME: comment */
547 static struct color_ext_type *color_ext_list = NULL;
549 /* Buffer for color sequences */
550 static char *color_buf;
552 /* Nonzero means to check for orphaned symbolic link, for displaying
553 colors. */
555 static int check_symlink_color;
557 /* Nonzero means mention the inode number of each file. -i */
559 static int print_inode;
561 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
562 other options that imply -l), and -L. */
564 static enum Dereference_symlink dereference;
566 /* Nonzero means when a directory is found, display info on its
567 contents. -R */
569 static int recursive;
571 /* Nonzero means when an argument is a directory name, display info
572 on it itself. -d */
574 static int immediate_dirs;
576 /* Nonzero means don't omit files whose names start with `.'. -A */
578 static int all_files;
580 /* Nonzero means don't omit files `.' and `..'
581 This flag implies `all_files'. -a */
583 static int really_all_files;
585 /* A linked list of shell-style globbing patterns. If a non-argument
586 file name matches any of these patterns, it is omitted.
587 Controlled by -I. Multiple -I options accumulate.
588 The -B option adds `*~' and `.*~' to this list. */
590 struct ignore_pattern
592 const char *pattern;
593 struct ignore_pattern *next;
596 static struct ignore_pattern *ignore_patterns;
598 /* Nonzero means output nongraphic chars in file names as `?'.
599 (-q, --hide-control-chars)
600 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
601 independent. The algorithm is: first, obey the quoting style to get a
602 string representing the file name; then, if qmark_funny_chars is set,
603 replace all nonprintable chars in that string with `?'. It's necessary
604 to replace nonprintable chars even in quoted strings, because we don't
605 want to mess up the terminal if control chars get sent to it, and some
606 quoting methods pass through control chars as-is. */
607 static int qmark_funny_chars;
609 /* Quoting options for file and dir name output. */
611 static struct quoting_options *filename_quoting_options;
612 static struct quoting_options *dirname_quoting_options;
614 /* The number of chars per hardware tab stop. Setting this to zero
615 inhibits the use of TAB characters for separating columns. -T */
616 static size_t tabsize;
618 /* Nonzero means we are listing the working directory because no
619 non-option arguments were given. */
621 static int dir_defaulted;
623 /* Nonzero means print each directory name before listing it. */
625 static int print_dir_name;
627 /* The line length to use for breaking lines in many-per-line format.
628 Can be set with -w. */
630 static size_t line_length;
632 /* If nonzero, the file listing format requires that stat be called on
633 each file. */
635 static int format_needs_stat;
637 /* Similar to `format_needs_stat', but set if only the file type is
638 needed. */
640 static int format_needs_type;
642 /* strftime formats for non-recent and recent files, respectively, in
643 -l output. */
645 static char const *long_time_format[2] =
647 /* strftime format for non-recent files (older than 6 months), in
648 -l output when --time-style=locale is specified. This should
649 contain the year, month and day (at least), in an order that is
650 understood by people in your locale's territory.
651 Please try to keep the number of used screen columns small,
652 because many people work in windows with only 80 columns. But
653 make this as wide as the other string below, for recent files. */
654 N_("%b %e %Y"),
655 /* strftime format for recent files (younger than 6 months), in
656 -l output when --time-style=locale is specified. This should
657 contain the month, day and time (at least), in an order that is
658 understood by people in your locale's territory.
659 Please try to keep the number of used screen columns small,
660 because many people work in windows with only 80 columns. But
661 make this as wide as the other string above, for non-recent files. */
662 N_("%b %e %H:%M")
665 /* The exit status to use if we don't get any fatal errors. */
667 static int exit_status;
669 /* For long options that have no equivalent short option, use a
670 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
671 enum
673 AUTHOR_OPTION = CHAR_MAX + 1,
674 BLOCK_SIZE_OPTION,
675 COLOR_OPTION,
676 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
677 FORMAT_OPTION,
678 FULL_TIME_OPTION,
679 INDICATOR_STYLE_OPTION,
680 QUOTING_STYLE_OPTION,
681 SHOW_CONTROL_CHARS_OPTION,
682 SI_OPTION,
683 SORT_OPTION,
684 TIME_OPTION,
685 TIME_STYLE_OPTION
688 static struct option const long_options[] =
690 {"all", no_argument, 0, 'a'},
691 {"escape", no_argument, 0, 'b'},
692 {"directory", no_argument, 0, 'd'},
693 {"dired", no_argument, 0, 'D'},
694 {"full-time", no_argument, 0, FULL_TIME_OPTION},
695 {"human-readable", no_argument, 0, 'h'},
696 {"inode", no_argument, 0, 'i'},
697 {"kilobytes", no_argument, 0, 'k'}, /* long form is obsolescent */
698 {"numeric-uid-gid", no_argument, 0, 'n'},
699 {"no-group", no_argument, 0, 'G'},
700 {"hide-control-chars", no_argument, 0, 'q'},
701 {"reverse", no_argument, 0, 'r'},
702 {"size", no_argument, 0, 's'},
703 {"width", required_argument, 0, 'w'},
704 {"almost-all", no_argument, 0, 'A'},
705 {"ignore-backups", no_argument, 0, 'B'},
706 {"classify", no_argument, 0, 'F'},
707 {"file-type", no_argument, 0, 'p'},
708 {"si", no_argument, 0, SI_OPTION},
709 {"dereference-command-line", no_argument, 0, 'H'},
710 {"dereference-command-line-symlink-to-dir", no_argument, 0,
711 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
712 {"ignore", required_argument, 0, 'I'},
713 {"indicator-style", required_argument, 0, INDICATOR_STYLE_OPTION},
714 {"dereference", no_argument, 0, 'L'},
715 {"literal", no_argument, 0, 'N'},
716 {"quote-name", no_argument, 0, 'Q'},
717 {"quoting-style", required_argument, 0, QUOTING_STYLE_OPTION},
718 {"recursive", no_argument, 0, 'R'},
719 {"format", required_argument, 0, FORMAT_OPTION},
720 {"show-control-chars", no_argument, 0, SHOW_CONTROL_CHARS_OPTION},
721 {"sort", required_argument, 0, SORT_OPTION},
722 {"tabsize", required_argument, 0, 'T'},
723 {"time", required_argument, 0, TIME_OPTION},
724 {"time-style", required_argument, 0, TIME_STYLE_OPTION},
725 {"color", optional_argument, 0, COLOR_OPTION},
726 {"block-size", required_argument, 0, BLOCK_SIZE_OPTION},
727 {"author", no_argument, 0, AUTHOR_OPTION},
728 {GETOPT_HELP_OPTION_DECL},
729 {GETOPT_VERSION_OPTION_DECL},
730 {NULL, 0, NULL, 0}
733 static char const *const format_args[] =
735 "verbose", "long", "commas", "horizontal", "across",
736 "vertical", "single-column", 0
739 static enum format const format_types[] =
741 long_format, long_format, with_commas, horizontal, horizontal,
742 many_per_line, one_per_line
745 static char const *const sort_args[] =
747 "none", "time", "size", "extension", "version", 0
750 static enum sort_type const sort_types[] =
752 sort_none, sort_time, sort_size, sort_extension, sort_version
755 static char const *const time_args[] =
757 "atime", "access", "use", "ctime", "status", 0
760 static enum time_type const time_types[] =
762 time_atime, time_atime, time_atime, time_ctime, time_ctime
765 static char const *const color_args[] =
767 /* force and none are for compatibility with another color-ls version */
768 "always", "yes", "force",
769 "never", "no", "none",
770 "auto", "tty", "if-tty", 0
773 static enum color_type const color_types[] =
775 color_always, color_always, color_always,
776 color_never, color_never, color_never,
777 color_if_tty, color_if_tty, color_if_tty
780 /* Information about filling a column. */
781 struct column_info
783 bool valid_len;
784 size_t line_len;
785 size_t *col_arr;
788 /* Array with information about column filledness. */
789 static struct column_info *column_info;
791 /* Maximum number of columns ever possible for this display. */
792 static size_t max_idx;
794 /* The minimum width of a colum is 3: 1 character for the name and 2
795 for the separating white space. */
796 #define MIN_COLUMN_WIDTH 3
799 /* This zero-based index is used solely with the --dired option.
800 When that option is in effect, this counter is incremented for each
801 character of output generated by this program so that the beginning
802 and ending indices (in that output) of every file name can be recorded
803 and later output themselves. */
804 static size_t dired_pos;
806 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
808 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
809 #define DIRED_FPUTS(s, stream, s_len) \
810 do {fputs ((s), (stream)); dired_pos += s_len;} while (0)
812 /* Like DIRED_FPUTS, but for use when S is a literal string. */
813 #define DIRED_FPUTS_LITERAL(s, stream) \
814 do {fputs ((s), (stream)); dired_pos += sizeof((s)) - 1;} while (0)
816 #define DIRED_INDENT() \
817 do \
819 if (dired) \
820 DIRED_FPUTS_LITERAL (" ", stdout); \
822 while (0)
824 /* With --dired, store pairs of beginning and ending indices of filenames. */
825 static struct obstack dired_obstack;
827 /* With --dired, store pairs of beginning and ending indices of any
828 directory names that appear as headers (just before `total' line)
829 for lists of directory entries. Such directory names are seen when
830 listing hierarchies using -R and when a directory is listed with at
831 least one other command line argument. */
832 static struct obstack subdired_obstack;
834 /* Save the current index on the specified obstack, OBS. */
835 #define PUSH_CURRENT_DIRED_POS(obs) \
836 do \
838 if (dired) \
839 obstack_grow ((obs), &dired_pos, sizeof (dired_pos)); \
841 while (0)
843 /* With -R, this stack is used to help detect directory cycles.
844 The device/inode pairs on this stack mirror the pairs in the
845 active_dir_set hash table. */
846 static struct obstack dev_ino_obstack;
848 /* Push a pair onto the device/inode stack. */
849 #define DEV_INO_PUSH(Dev, Ino) \
850 do \
852 struct dev_ino *di; \
853 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
854 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
855 di->st_dev = (Dev); \
856 di->st_ino = (Ino); \
858 while (0)
860 /* Pop a dev/ino struct off the global dev_ino_obstack
861 and return that struct. */
862 static struct dev_ino
863 dev_ino_pop (void)
865 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
866 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
867 return *(struct dev_ino*) obstack_next_free (&dev_ino_obstack);
870 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
871 do \
873 struct stat sb; \
874 assert (Name); \
875 assert (0 <= stat (Name, &sb)); \
876 assert (sb.st_dev == Di.st_dev); \
877 assert (sb.st_ino == Di.st_ino); \
879 while (0)
882 /* Write to standard output PREFIX, followed by the quoting style and
883 a space-separated list of the integers stored in OS all on one line. */
885 static void
886 dired_dump_obstack (const char *prefix, struct obstack *os)
888 size_t n_pos;
890 n_pos = obstack_object_size (os) / sizeof (dired_pos);
891 if (n_pos > 0)
893 size_t i;
894 size_t *pos;
896 pos = (size_t *) obstack_finish (os);
897 fputs (prefix, stdout);
898 for (i = 0; i < n_pos; i++)
899 printf (" %lu", (unsigned long int) pos[i]);
900 putchar ('\n');
904 static size_t
905 dev_ino_hash (void const *x, size_t table_size)
907 struct dev_ino const *p = x;
908 return (uintmax_t) p->st_ino % table_size;
911 static bool
912 dev_ino_compare (void const *x, void const *y)
914 struct dev_ino const *a = x;
915 struct dev_ino const *b = y;
916 return SAME_INODE (*a, *b) ? true : false;
919 static void
920 dev_ino_free (void *x)
922 free (x);
925 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
926 active directories. Return nonzero if there is already a matching
927 entry in the table. Otherwise, return zero. */
929 static int
930 visit_dir (dev_t dev, ino_t ino)
932 struct dev_ino *ent;
933 struct dev_ino *ent_from_table;
934 int found_match;
936 ent = xmalloc (sizeof *ent);
937 ent->st_ino = ino;
938 ent->st_dev = dev;
940 /* Attempt to insert this entry into the table. */
941 ent_from_table = hash_insert (active_dir_set, ent);
943 if (ent_from_table == NULL)
945 /* Insertion failed due to lack of memory. */
946 xalloc_die ();
949 found_match = (ent_from_table != ent);
951 if (found_match)
953 /* ent was not inserted, so free it. */
954 free (ent);
957 return found_match;
960 static void
961 free_pending_ent (struct pending *p)
963 if (p->name)
964 free (p->name);
965 if (p->realname)
966 free (p->realname);
967 free (p);
970 static void
971 restore_default_color (void)
973 if (put_indicator_direct (&color_indicator[C_LEFT]) == 0)
974 put_indicator_direct (&color_indicator[C_RIGHT]);
977 /* Upon interrupt, suspend, hangup, etc. ensure that the
978 terminal text color is restored to the default. */
979 static void
980 sighandler (int sig)
982 #ifndef SA_NOCLDSTOP
983 signal (sig, SIG_IGN);
984 #endif
986 restore_default_color ();
988 /* SIGTSTP is special, since the application can receive that signal more
989 than once. In this case, don't set the signal handler to the default.
990 Instead, just raise the uncatchable SIGSTOP. */
991 if (sig == SIGTSTP)
993 sig = SIGSTOP;
995 else
997 #ifdef SA_NOCLDSTOP
998 struct sigaction sigact;
1000 sigact.sa_handler = SIG_DFL;
1001 sigemptyset (&sigact.sa_mask);
1002 sigact.sa_flags = 0;
1003 sigaction (sig, &sigact, NULL);
1004 #else
1005 signal (sig, SIG_DFL);
1006 #endif
1009 raise (sig);
1013 main (int argc, char **argv)
1015 register int i;
1016 register struct pending *thispend;
1017 unsigned int n_files;
1019 initialize_main (&argc, &argv);
1020 program_name = argv[0];
1021 setlocale (LC_ALL, "");
1022 bindtextdomain (PACKAGE, LOCALEDIR);
1023 textdomain (PACKAGE);
1025 atexit (close_stdout);
1027 #define N_ENTRIES(Array) (sizeof Array / sizeof *(Array))
1028 assert (N_ENTRIES (color_indicator) + 1 == N_ENTRIES (indicator_name));
1030 exit_status = 0;
1031 dir_defaulted = 1;
1032 print_dir_name = 1;
1033 pending_dirs = 0;
1035 i = decode_switches (argc, argv);
1037 if (print_with_color)
1038 parse_ls_color ();
1040 /* Test print_with_color again, because the call to parse_ls_color
1041 may have just reset it -- e.g., if LS_COLORS is invalid. */
1042 if (print_with_color)
1044 prep_non_filename_text ();
1045 /* Avoid following symbolic links when possible. */
1046 if (color_indicator[C_ORPHAN].string != NULL
1047 || (color_indicator[C_MISSING].string != NULL
1048 && format == long_format))
1049 check_symlink_color = 1;
1052 unsigned int j;
1053 static int const sigs[] = { SIGHUP, SIGINT, SIGPIPE,
1054 SIGQUIT, SIGTERM, SIGTSTP };
1055 unsigned int nsigs = sizeof sigs / sizeof *sigs;
1056 #ifdef SA_NOCLDSTOP
1057 struct sigaction oldact, newact;
1058 sigset_t caught_signals;
1060 sigemptyset (&caught_signals);
1061 for (j = 0; j < nsigs; j++)
1062 sigaddset (&caught_signals, sigs[j]);
1063 newact.sa_handler = sighandler;
1064 newact.sa_mask = caught_signals;
1065 newact.sa_flags = 0;
1066 #endif
1068 for (j = 0; j < nsigs; j++)
1070 int sig = sigs[j];
1071 #ifdef SA_NOCLDSTOP
1072 sigaction (sig, NULL, &oldact);
1073 if (oldact.sa_handler != SIG_IGN)
1074 sigaction (sig, &newact, NULL);
1075 #else
1076 if (signal (sig, SIG_IGN) != SIG_IGN)
1077 signal (sig, sighandler);
1078 #endif
1083 if (dereference == DEREF_UNDEFINED)
1084 dereference = ((immediate_dirs
1085 || indicator_style == classify
1086 || format == long_format)
1087 ? DEREF_NEVER
1088 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1090 /* When using -R, initialize a data structure we'll use to
1091 detect any directory cycles. */
1092 if (recursive)
1094 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1095 dev_ino_hash,
1096 dev_ino_compare,
1097 dev_ino_free);
1098 if (active_dir_set == NULL)
1099 xalloc_die ();
1101 obstack_init (&dev_ino_obstack);
1104 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1105 || format == long_format
1106 || dereference == DEREF_ALWAYS
1107 || print_block_size || print_inode;
1108 format_needs_type = (format_needs_stat == 0
1109 && (recursive || print_with_color
1110 || indicator_style != none));
1112 if (dired)
1114 obstack_init (&dired_obstack);
1115 obstack_init (&subdired_obstack);
1118 nfiles = 100;
1119 files = xnmalloc (nfiles, sizeof *files);
1120 files_index = 0;
1122 clear_files ();
1124 n_files = argc - i;
1125 if (0 < n_files)
1126 dir_defaulted = 0;
1128 for (; i < argc; i++)
1130 gobble_file (argv[i], unknown, 1, "");
1133 if (dir_defaulted)
1135 if (immediate_dirs)
1136 gobble_file (".", directory, 1, "");
1137 else
1138 queue_directory (".", 0);
1141 if (files_index)
1143 sort_files ();
1144 if (!immediate_dirs)
1145 extract_dirs_from_files ("", 0);
1146 /* `files_index' might be zero now. */
1149 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1150 (and not pending_dirs->name) because there may be no markers in the queue
1151 at this point. A marker may be enqueued when extract_dirs_from_files is
1152 called with a non-empty string or via print_dir. */
1153 if (files_index)
1155 print_current_files ();
1156 if (pending_dirs)
1157 DIRED_PUTCHAR ('\n');
1159 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1160 print_dir_name = 0;
1162 while (pending_dirs)
1164 thispend = pending_dirs;
1165 pending_dirs = pending_dirs->next;
1167 if (LOOP_DETECT)
1169 if (thispend->name == NULL)
1171 /* thispend->name == NULL means this is a marker entry
1172 indicating we've finished processing the directory.
1173 Use its dev/ino numbers to remove the corresponding
1174 entry from the active_dir_set hash table. */
1175 struct dev_ino di = dev_ino_pop ();
1176 struct dev_ino *found = hash_delete (active_dir_set, &di);
1177 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1178 assert (found);
1179 dev_ino_free (found);
1180 free_pending_ent (thispend);
1181 continue;
1185 print_dir (thispend->name, thispend->realname);
1187 free_pending_ent (thispend);
1188 print_dir_name = 1;
1191 if (dired)
1193 /* No need to free these since we're about to exit. */
1194 dired_dump_obstack ("//DIRED//", &dired_obstack);
1195 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1196 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1197 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1200 /* Restore default color before exiting */
1201 if (print_with_color)
1203 put_indicator (&color_indicator[C_LEFT]);
1204 put_indicator (&color_indicator[C_RIGHT]);
1207 if (LOOP_DETECT)
1209 assert (hash_get_n_entries (active_dir_set) == 0);
1210 hash_free (active_dir_set);
1213 exit (exit_status);
1216 /* Set all the option flags according to the switches specified.
1217 Return the index of the first non-option argument. */
1219 static int
1220 decode_switches (int argc, char **argv)
1222 int c;
1223 char *time_style_option = 0;
1225 /* Record whether there is an option specifying sort type. */
1226 int sort_type_specified = 0;
1228 qmark_funny_chars = 0;
1230 /* initialize all switches to default settings */
1232 switch (ls_mode)
1234 case LS_MULTI_COL:
1235 /* This is for the `dir' program. */
1236 format = many_per_line;
1237 set_quoting_style (NULL, escape_quoting_style);
1238 break;
1240 case LS_LONG_FORMAT:
1241 /* This is for the `vdir' program. */
1242 format = long_format;
1243 set_quoting_style (NULL, escape_quoting_style);
1244 break;
1246 case LS_LS:
1247 /* This is for the `ls' program. */
1248 if (isatty (STDOUT_FILENO))
1250 format = many_per_line;
1251 /* See description of qmark_funny_chars, above. */
1252 qmark_funny_chars = 1;
1254 else
1256 format = one_per_line;
1257 qmark_funny_chars = 0;
1259 break;
1261 default:
1262 abort ();
1265 time_type = time_mtime;
1266 sort_type = sort_name;
1267 sort_reverse = 0;
1268 numeric_ids = 0;
1269 print_block_size = 0;
1270 indicator_style = none;
1271 print_inode = 0;
1272 dereference = DEREF_UNDEFINED;
1273 recursive = 0;
1274 immediate_dirs = 0;
1275 all_files = 0;
1276 really_all_files = 0;
1277 ignore_patterns = 0;
1279 /* FIXME: put this in a function. */
1281 char const *q_style = getenv ("QUOTING_STYLE");
1282 if (q_style)
1284 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1285 if (0 <= i)
1286 set_quoting_style (NULL, quoting_style_vals[i]);
1287 else
1288 error (0, 0,
1289 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1290 quotearg (q_style));
1295 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1296 human_output_opts = human_options (ls_block_size, false,
1297 &output_block_size);
1298 if (ls_block_size || getenv ("BLOCK_SIZE"))
1299 file_output_block_size = output_block_size;
1302 line_length = 80;
1304 char const *p = getenv ("COLUMNS");
1305 if (p && *p)
1307 unsigned long int tmp_ulong;
1308 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1309 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1311 line_length = tmp_ulong;
1313 else
1315 error (0, 0,
1316 _("ignoring invalid width in environment variable COLUMNS: %s"),
1317 quotearg (p));
1322 #ifdef TIOCGWINSZ
1324 struct winsize ws;
1326 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1327 && 0 < ws.ws_col /* && ws.ws_col <= SIZE_MAX */ )
1328 line_length = ws.ws_col;
1330 #endif
1332 /* Using the TABSIZE environment variable is not POSIX-approved.
1333 Ignore it when POSIXLY_CORRECT is set. */
1335 char const *p;
1336 tabsize = 8;
1337 if (!getenv ("POSIXLY_CORRECT") && (p = getenv ("TABSIZE")))
1339 unsigned long int tmp_ulong;
1340 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1341 && tmp_ulong <= SIZE_MAX)
1343 tabsize = tmp_ulong;
1345 else
1347 error (0, 0,
1348 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1349 quotearg (p));
1354 while ((c = getopt_long (argc, argv,
1355 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UX1",
1356 long_options, NULL)) != -1)
1358 switch (c)
1360 case 0:
1361 break;
1363 case 'a':
1364 all_files = 1;
1365 really_all_files = 1;
1366 break;
1368 case 'b':
1369 set_quoting_style (NULL, escape_quoting_style);
1370 break;
1372 case 'c':
1373 time_type = time_ctime;
1374 break;
1376 case 'd':
1377 immediate_dirs = 1;
1378 break;
1380 case 'f':
1381 /* Same as enabling -a -U and disabling -l -s. */
1382 all_files = 1;
1383 really_all_files = 1;
1384 sort_type = sort_none;
1385 sort_type_specified = 1;
1386 /* disable -l */
1387 if (format == long_format)
1388 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1389 print_block_size = 0; /* disable -s */
1390 print_with_color = 0; /* disable --color */
1391 break;
1393 case 'g':
1394 format = long_format;
1395 print_owner = 0;
1396 break;
1398 case 'h':
1399 human_output_opts = human_autoscale | human_SI | human_base_1024;
1400 file_output_block_size = output_block_size = 1;
1401 break;
1403 case 'i':
1404 print_inode = 1;
1405 break;
1407 case 'k':
1408 human_output_opts = 0;
1409 file_output_block_size = output_block_size = 1024;
1410 break;
1412 case 'l':
1413 format = long_format;
1414 break;
1416 case 'm':
1417 format = with_commas;
1418 break;
1420 case 'n':
1421 numeric_ids = 1;
1422 format = long_format;
1423 break;
1425 case 'o': /* Just like -l, but don't display group info. */
1426 format = long_format;
1427 print_group = 0;
1428 break;
1430 case 'p':
1431 indicator_style = file_type;
1432 break;
1434 case 'q':
1435 qmark_funny_chars = 1;
1436 break;
1438 case 'r':
1439 sort_reverse = 1;
1440 break;
1442 case 's':
1443 print_block_size = 1;
1444 break;
1446 case 't':
1447 sort_type = sort_time;
1448 sort_type_specified = 1;
1449 break;
1451 case 'u':
1452 time_type = time_atime;
1453 break;
1455 case 'v':
1456 sort_type = sort_version;
1457 sort_type_specified = 1;
1458 break;
1460 case 'w':
1462 unsigned long int tmp_ulong;
1463 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1464 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1465 error (EXIT_FAILURE, 0, _("invalid line width: %s"),
1466 quotearg (optarg));
1467 line_length = tmp_ulong;
1468 break;
1471 case 'x':
1472 format = horizontal;
1473 break;
1475 case 'A':
1476 really_all_files = 0;
1477 all_files = 1;
1478 break;
1480 case 'B':
1481 add_ignore_pattern ("*~");
1482 add_ignore_pattern (".*~");
1483 break;
1485 case 'C':
1486 format = many_per_line;
1487 break;
1489 case 'D':
1490 dired = 1;
1491 break;
1493 case 'F':
1494 indicator_style = classify;
1495 break;
1497 case 'G': /* inhibit display of group info */
1498 print_group = 0;
1499 break;
1501 case 'H':
1502 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1503 break;
1505 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1506 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1507 break;
1509 case 'I':
1510 add_ignore_pattern (optarg);
1511 break;
1513 case 'L':
1514 dereference = DEREF_ALWAYS;
1515 break;
1517 case 'N':
1518 set_quoting_style (NULL, literal_quoting_style);
1519 break;
1521 case 'Q':
1522 set_quoting_style (NULL, c_quoting_style);
1523 break;
1525 case 'R':
1526 recursive = 1;
1527 break;
1529 case 'S':
1530 sort_type = sort_size;
1531 sort_type_specified = 1;
1532 break;
1534 case 'T':
1536 unsigned long int tmp_ulong;
1537 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1538 || SIZE_MAX < tmp_ulong)
1539 error (EXIT_FAILURE, 0, _("invalid tab size: %s"),
1540 quotearg (optarg));
1541 tabsize = tmp_ulong;
1542 break;
1545 case 'U':
1546 sort_type = sort_none;
1547 sort_type_specified = 1;
1548 break;
1550 case 'X':
1551 sort_type = sort_extension;
1552 sort_type_specified = 1;
1553 break;
1555 case '1':
1556 /* -1 has no effect after -l. */
1557 if (format != long_format)
1558 format = one_per_line;
1559 break;
1561 case AUTHOR_OPTION:
1562 print_author = true;
1563 break;
1565 case SORT_OPTION:
1566 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1567 sort_type_specified = 1;
1568 break;
1570 case TIME_OPTION:
1571 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1572 break;
1574 case FORMAT_OPTION:
1575 format = XARGMATCH ("--format", optarg, format_args, format_types);
1576 break;
1578 case FULL_TIME_OPTION:
1579 format = long_format;
1580 time_style_option = "full-iso";
1581 break;
1583 case COLOR_OPTION:
1585 int i;
1586 if (optarg)
1587 i = XARGMATCH ("--color", optarg, color_args, color_types);
1588 else
1589 /* Using --color with no argument is equivalent to using
1590 --color=always. */
1591 i = color_always;
1593 print_with_color = (i == color_always
1594 || (i == color_if_tty
1595 && isatty (STDOUT_FILENO)));
1597 if (print_with_color)
1599 /* Don't use TAB characters in output. Some terminal
1600 emulators can't handle the combination of tabs and
1601 color codes on the same line. */
1602 tabsize = 0;
1604 break;
1607 case INDICATOR_STYLE_OPTION:
1608 indicator_style = XARGMATCH ("--indicator-style", optarg,
1609 indicator_style_args,
1610 indicator_style_types);
1611 break;
1613 case QUOTING_STYLE_OPTION:
1614 set_quoting_style (NULL,
1615 XARGMATCH ("--quoting-style", optarg,
1616 quoting_style_args,
1617 quoting_style_vals));
1618 break;
1620 case TIME_STYLE_OPTION:
1621 time_style_option = optarg;
1622 break;
1624 case SHOW_CONTROL_CHARS_OPTION:
1625 qmark_funny_chars = 0;
1626 break;
1628 case BLOCK_SIZE_OPTION:
1629 human_output_opts = human_options (optarg, true, &output_block_size);
1630 file_output_block_size = output_block_size;
1631 break;
1633 case SI_OPTION:
1634 human_output_opts = human_autoscale | human_SI;
1635 file_output_block_size = output_block_size = 1;
1636 break;
1638 case_GETOPT_HELP_CHAR;
1640 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1642 default:
1643 usage (EXIT_FAILURE);
1647 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1649 filename_quoting_options = clone_quoting_options (NULL);
1650 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1651 set_char_quoting (filename_quoting_options, ' ', 1);
1652 if (indicator_style != none)
1654 char const *p;
1655 for (p = "*=@|" + (int) indicator_style - 1; *p; p++)
1656 set_char_quoting (filename_quoting_options, *p, 1);
1659 dirname_quoting_options = clone_quoting_options (NULL);
1660 set_char_quoting (dirname_quoting_options, ':', 1);
1662 /* --dired is meaningful only with --format=long (-l).
1663 Otherwise, ignore it. FIXME: warn about this?
1664 Alternatively, make --dired imply --format=long? */
1665 if (dired && format != long_format)
1666 dired = 0;
1668 /* If -c or -u is specified and not -l (or any other option that implies -l),
1669 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1670 The behavior of ls when using either -c or -u but with neither -l nor -t
1671 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1672 sort by atime (this is the one that's not specified by the POSIX spec),
1673 -lu means show atime and sort by name, -lut means show atime and sort
1674 by atime. */
1676 if ((time_type == time_ctime || time_type == time_atime)
1677 && !sort_type_specified && format != long_format)
1679 sort_type = sort_time;
1682 if (format == long_format)
1684 char *style = time_style_option;
1685 static char const posix_prefix[] = "posix-";
1687 if (! style)
1688 if (! (style = getenv ("TIME_STYLE")))
1689 style = "posix-long-iso";
1691 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1693 if (! hard_locale (LC_TIME))
1694 return optind;
1695 style += sizeof posix_prefix - 1;
1698 if (*style == '+')
1700 char *p0 = style + 1;
1701 char *p1 = strchr (p0, '\n');
1702 if (! p1)
1703 p1 = p0;
1704 else
1706 if (strchr (p1 + 1, '\n'))
1707 error (EXIT_FAILURE, 0, _("invalid time style format %s"),
1708 quote (p0));
1709 *p1++ = '\0';
1711 long_time_format[0] = p0;
1712 long_time_format[1] = p1;
1714 else
1715 switch (XARGMATCH ("time style", style,
1716 time_style_args,
1717 time_style_types))
1719 case full_iso_time_style:
1720 long_time_format[0] = long_time_format[1] =
1721 "%Y-%m-%d %H:%M:%S.%N %z";
1722 break;
1724 case long_iso_time_style:
1725 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1726 break;
1728 case iso_time_style:
1729 long_time_format[0] = "%Y-%m-%d ";
1730 long_time_format[1] = "%m-%d %H:%M";
1731 break;
1733 case locale_time_style:
1734 if (hard_locale (LC_TIME))
1736 unsigned int i;
1737 for (i = 0; i < 2; i++)
1738 long_time_format[i] =
1739 dcgettext (NULL, long_time_format[i], LC_TIME);
1744 return optind;
1747 /* Parse a string as part of the LS_COLORS variable; this may involve
1748 decoding all kinds of escape characters. If equals_end is set an
1749 unescaped equal sign ends the string, otherwise only a : or \0
1750 does. Set *OUTPUT_COUNT to the number of bytes output. Return
1751 true if successful.
1753 The resulting string is *not* null-terminated, but may contain
1754 embedded nulls.
1756 Note that both dest and src are char **; on return they point to
1757 the first free byte after the array and the character that ended
1758 the input string, respectively. */
1760 static bool
1761 get_funky_string (char **dest, const char **src, bool equals_end,
1762 size_t *output_count)
1764 int num; /* For numerical codes */
1765 size_t count; /* Something to count with */
1766 enum {
1767 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
1768 } state;
1769 const char *p;
1770 char *q;
1772 p = *src; /* We don't want to double-indirect */
1773 q = *dest; /* the whole darn time. */
1775 count = 0; /* No characters counted in yet. */
1776 num = 0;
1778 state = ST_GND; /* Start in ground state. */
1779 while (state < ST_END)
1781 switch (state)
1783 case ST_GND: /* Ground state (no escapes) */
1784 switch (*p)
1786 case ':':
1787 case '\0':
1788 state = ST_END; /* End of string */
1789 break;
1790 case '\\':
1791 state = ST_BACKSLASH; /* Backslash scape sequence */
1792 ++p;
1793 break;
1794 case '^':
1795 state = ST_CARET; /* Caret escape */
1796 ++p;
1797 break;
1798 case '=':
1799 if (equals_end)
1801 state = ST_END; /* End */
1802 break;
1804 /* else fall through */
1805 default:
1806 *(q++) = *(p++);
1807 ++count;
1808 break;
1810 break;
1812 case ST_BACKSLASH: /* Backslash escaped character */
1813 switch (*p)
1815 case '0':
1816 case '1':
1817 case '2':
1818 case '3':
1819 case '4':
1820 case '5':
1821 case '6':
1822 case '7':
1823 state = ST_OCTAL; /* Octal sequence */
1824 num = *p - '0';
1825 break;
1826 case 'x':
1827 case 'X':
1828 state = ST_HEX; /* Hex sequence */
1829 num = 0;
1830 break;
1831 case 'a': /* Bell */
1832 num = 7; /* Not all C compilers know what \a means */
1833 break;
1834 case 'b': /* Backspace */
1835 num = '\b';
1836 break;
1837 case 'e': /* Escape */
1838 num = 27;
1839 break;
1840 case 'f': /* Form feed */
1841 num = '\f';
1842 break;
1843 case 'n': /* Newline */
1844 num = '\n';
1845 break;
1846 case 'r': /* Carriage return */
1847 num = '\r';
1848 break;
1849 case 't': /* Tab */
1850 num = '\t';
1851 break;
1852 case 'v': /* Vtab */
1853 num = '\v';
1854 break;
1855 case '?': /* Delete */
1856 num = 127;
1857 break;
1858 case '_': /* Space */
1859 num = ' ';
1860 break;
1861 case '\0': /* End of string */
1862 state = ST_ERROR; /* Error! */
1863 break;
1864 default: /* Escaped character like \ ^ : = */
1865 num = *p;
1866 break;
1868 if (state == ST_BACKSLASH)
1870 *(q++) = num;
1871 ++count;
1872 state = ST_GND;
1874 ++p;
1875 break;
1877 case ST_OCTAL: /* Octal sequence */
1878 if (*p < '0' || *p > '7')
1880 *(q++) = num;
1881 ++count;
1882 state = ST_GND;
1884 else
1885 num = (num << 3) + (*(p++) - '0');
1886 break;
1888 case ST_HEX: /* Hex sequence */
1889 switch (*p)
1891 case '0':
1892 case '1':
1893 case '2':
1894 case '3':
1895 case '4':
1896 case '5':
1897 case '6':
1898 case '7':
1899 case '8':
1900 case '9':
1901 num = (num << 4) + (*(p++) - '0');
1902 break;
1903 case 'a':
1904 case 'b':
1905 case 'c':
1906 case 'd':
1907 case 'e':
1908 case 'f':
1909 num = (num << 4) + (*(p++) - 'a') + 10;
1910 break;
1911 case 'A':
1912 case 'B':
1913 case 'C':
1914 case 'D':
1915 case 'E':
1916 case 'F':
1917 num = (num << 4) + (*(p++) - 'A') + 10;
1918 break;
1919 default:
1920 *(q++) = num;
1921 ++count;
1922 state = ST_GND;
1923 break;
1925 break;
1927 case ST_CARET: /* Caret escape */
1928 state = ST_GND; /* Should be the next state... */
1929 if (*p >= '@' && *p <= '~')
1931 *(q++) = *(p++) & 037;
1932 ++count;
1934 else if (*p == '?')
1936 *(q++) = 127;
1937 ++count;
1939 else
1940 state = ST_ERROR;
1941 break;
1943 default:
1944 abort ();
1948 *dest = q;
1949 *src = p;
1950 *output_count = count;
1952 return state != ST_ERROR;
1955 static void
1956 parse_ls_color (void)
1958 const char *p; /* Pointer to character being parsed */
1959 char *buf; /* color_buf buffer pointer */
1960 int state; /* State of parser */
1961 int ind_no; /* Indicator number */
1962 char label[3]; /* Indicator label */
1963 struct color_ext_type *ext; /* Extension we are working on */
1965 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
1966 return;
1968 ext = NULL;
1969 strcpy (label, "??");
1971 /* This is an overly conservative estimate, but any possible
1972 LS_COLORS string will *not* generate a color_buf longer than
1973 itself, so it is a safe way of allocating a buffer in
1974 advance. */
1975 buf = color_buf = xstrdup (p);
1977 state = 1;
1978 while (state > 0)
1980 switch (state)
1982 case 1: /* First label character */
1983 switch (*p)
1985 case ':':
1986 ++p;
1987 break;
1989 case '*':
1990 /* Allocate new extension block and add to head of
1991 linked list (this way a later definition will
1992 override an earlier one, which can be useful for
1993 having terminal-specific defs override global). */
1995 ext = xmalloc (sizeof *ext);
1996 ext->next = color_ext_list;
1997 color_ext_list = ext;
1999 ++p;
2000 ext->ext.string = buf;
2002 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2003 ? 4 : -1);
2004 break;
2006 case '\0':
2007 state = 0; /* Done! */
2008 break;
2010 default: /* Assume it is file type label */
2011 label[0] = *(p++);
2012 state = 2;
2013 break;
2015 break;
2017 case 2: /* Second label character */
2018 if (*p)
2020 label[1] = *(p++);
2021 state = 3;
2023 else
2024 state = -1; /* Error */
2025 break;
2027 case 3: /* Equal sign after indicator label */
2028 state = -1; /* Assume failure... */
2029 if (*(p++) == '=')/* It *should* be... */
2031 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2033 if (STREQ (label, indicator_name[ind_no]))
2035 color_indicator[ind_no].string = buf;
2036 state = (get_funky_string (&buf, &p, false,
2037 &color_indicator[ind_no].len)
2038 ? 1 : -1);
2039 break;
2042 if (state == -1)
2043 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2045 break;
2047 case 4: /* Equal sign after *.ext */
2048 if (*(p++) == '=')
2050 ext->seq.string = buf;
2051 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2052 ? 1 : -1);
2054 else
2055 state = -1;
2056 break;
2060 if (state < 0)
2062 struct color_ext_type *e;
2063 struct color_ext_type *e2;
2065 error (0, 0,
2066 _("unparsable value for LS_COLORS environment variable"));
2067 free (color_buf);
2068 for (e = color_ext_list; e != NULL; /* empty */)
2070 e2 = e;
2071 e = e->next;
2072 free (e2);
2074 print_with_color = 0;
2077 if (color_indicator[C_LINK].len == 6
2078 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2079 color_symlink_as_referent = 1;
2082 /* Request that the directory named NAME have its contents listed later.
2083 If REALNAME is nonzero, it will be used instead of NAME when the
2084 directory name is printed. This allows symbolic links to directories
2085 to be treated as regular directories but still be listed under their
2086 real names. NAME == NULL is used to insert a marker entry for the
2087 directory named in REALNAME.
2088 If F is non-NULL, we use its dev/ino information to save
2089 a call to stat -- when doing a recursive (-R) traversal. */
2091 static void
2092 queue_directory (const char *name, const char *realname)
2094 struct pending *new;
2096 new = xmalloc (sizeof *new);
2097 new->realname = realname ? xstrdup (realname) : NULL;
2098 new->name = name ? xstrdup (name) : NULL;
2099 new->next = pending_dirs;
2100 pending_dirs = new;
2103 /* Read directory `name', and list the files in it.
2104 If `realname' is nonzero, print its name instead of `name';
2105 this is used for symbolic links to directories. */
2107 static void
2108 print_dir (const char *name, const char *realname)
2110 register DIR *dirp;
2111 register struct dirent *next;
2112 register uintmax_t total_blocks = 0;
2113 static int first = 1;
2115 errno = 0;
2116 dirp = opendir (name);
2117 if (!dirp)
2119 error (0, errno, "%s", quotearg_colon (name));
2120 exit_status = 1;
2121 return;
2124 if (LOOP_DETECT)
2126 struct stat dir_stat;
2127 int fd = dirfd (dirp);
2129 /* If dirfd failed, endure the overhead of using stat. */
2130 if ((0 <= fd
2131 ? fstat (fd, &dir_stat)
2132 : stat (name, &dir_stat)) < 0)
2134 error (0, errno, _("cannot determine device and inode of %s"),
2135 quotearg_colon (name));
2136 exit_status = 1;
2137 return;
2140 /* If we've already visited this dev/inode pair, warn that
2141 we've found a loop, and do not process this directory. */
2142 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2144 error (0, 0, _("not listing already-listed directory: %s"),
2145 quotearg_colon (name));
2146 return;
2149 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2152 /* Read the directory entries, and insert the subfiles into the `files'
2153 table. */
2155 clear_files ();
2157 while (1)
2159 /* Set errno to zero so we can distinguish between a readdir failure
2160 and when readdir simply finds that there are no more entries. */
2161 errno = 0;
2162 if ((next = readdir (dirp)) == NULL)
2164 if (errno)
2166 /* Save/restore errno across closedir call. */
2167 int e = errno;
2168 closedir (dirp);
2169 errno = e;
2171 /* Arrange to give a diagnostic after exiting this loop. */
2172 dirp = NULL;
2174 break;
2177 if (file_interesting (next))
2179 enum filetype type = unknown;
2181 #if HAVE_STRUCT_DIRENT_D_TYPE
2182 if (next->d_type == DT_BLK
2183 || next->d_type == DT_CHR
2184 || next->d_type == DT_DIR
2185 || next->d_type == DT_FIFO
2186 || next->d_type == DT_LNK
2187 || next->d_type == DT_REG
2188 || next->d_type == DT_SOCK)
2189 type = next->d_type;
2190 #endif
2191 total_blocks += gobble_file (next->d_name, type, 0, name);
2195 if (dirp == NULL || CLOSEDIR (dirp))
2197 error (0, errno, _("reading directory %s"), quotearg_colon (name));
2198 exit_status = 1;
2199 /* Don't return; print whatever we got. */
2202 /* Sort the directory contents. */
2203 sort_files ();
2205 /* If any member files are subdirectories, perhaps they should have their
2206 contents listed rather than being mentioned here as files. */
2208 if (recursive)
2209 extract_dirs_from_files (name, 1);
2211 if (recursive || print_dir_name)
2213 if (!first)
2214 DIRED_PUTCHAR ('\n');
2215 first = 0;
2216 DIRED_INDENT ();
2217 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2218 dired_pos += quote_name (stdout, realname ? realname : name,
2219 dirname_quoting_options, NULL);
2220 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2221 DIRED_FPUTS_LITERAL (":\n", stdout);
2224 if (format == long_format || print_block_size)
2226 const char *p;
2227 char buf[LONGEST_HUMAN_READABLE + 1];
2229 DIRED_INDENT ();
2230 p = _("total");
2231 DIRED_FPUTS (p, stdout, strlen (p));
2232 DIRED_PUTCHAR (' ');
2233 p = human_readable (total_blocks, buf, human_output_opts,
2234 ST_NBLOCKSIZE, output_block_size);
2235 DIRED_FPUTS (p, stdout, strlen (p));
2236 DIRED_PUTCHAR ('\n');
2239 if (files_index)
2240 print_current_files ();
2243 /* Add `pattern' to the list of patterns for which files that match are
2244 not listed. */
2246 static void
2247 add_ignore_pattern (const char *pattern)
2249 register struct ignore_pattern *ignore;
2251 ignore = xmalloc (sizeof *ignore);
2252 ignore->pattern = pattern;
2253 /* Add it to the head of the linked list. */
2254 ignore->next = ignore_patterns;
2255 ignore_patterns = ignore;
2258 /* Return nonzero if the file in `next' should be listed. */
2260 static int
2261 file_interesting (const struct dirent *next)
2263 register struct ignore_pattern *ignore;
2265 for (ignore = ignore_patterns; ignore; ignore = ignore->next)
2266 if (fnmatch (ignore->pattern, next->d_name, FNM_PERIOD) == 0)
2267 return 0;
2269 if (really_all_files
2270 || next->d_name[0] != '.'
2271 || (all_files
2272 && next->d_name[1] != '\0'
2273 && (next->d_name[1] != '.' || next->d_name[2] != '\0')))
2274 return 1;
2276 return 0;
2279 /* POSIX requires that a file size be printed without a sign, even
2280 when negative. Assume the typical case where negative sizes are
2281 actually positive values that have wrapped around. */
2283 static uintmax_t
2284 unsigned_file_size (off_t size)
2286 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2289 /* Enter and remove entries in the table `files'. */
2291 /* Empty the table of files. */
2293 static void
2294 clear_files (void)
2296 register size_t i;
2298 for (i = 0; i < files_index; i++)
2300 free (files[i].name);
2301 if (files[i].linkname)
2302 free (files[i].linkname);
2305 files_index = 0;
2306 inode_number_width = 0;
2307 block_size_width = 0;
2308 nlink_width = 0;
2309 owner_width = 0;
2310 group_width = 0;
2311 author_width = 0;
2312 major_device_number_width = 0;
2313 minor_device_number_width = 0;
2314 file_size_width = 0;
2317 /* Add a file to the current table of files.
2318 Verify that the file exists, and print an error message if it does not.
2319 Return the number of blocks that the file occupies. */
2321 static uintmax_t
2322 gobble_file (const char *name, enum filetype type, int explicit_arg,
2323 const char *dirname)
2325 register uintmax_t blocks;
2326 register char *path;
2327 register struct fileinfo *f;
2329 if (files_index == nfiles)
2331 files = xnrealloc (files, nfiles, 2 * sizeof *files);
2332 nfiles *= 2;
2335 f = &files[files_index];
2336 f->linkname = 0;
2337 f->linkmode = 0;
2338 f->linkok = 0;
2340 if (explicit_arg
2341 || format_needs_stat
2342 || (format_needs_type
2343 && (type == unknown
2345 /* FIXME: remove this disjunct.
2346 I don't think we care about symlinks here, but for now
2347 this won't make a big performance difference. */
2348 || type == symbolic_link
2350 /* --indicator-style=classify (aka -F)
2351 requires that we stat each regular file
2352 to see if it's executable. */
2353 || (type == normal && (indicator_style == classify
2354 /* This is so that --color ends up
2355 highlighting files with the executable
2356 bit set even when options like -F are
2357 not specified. */
2358 || print_with_color)))))
2361 /* `path' is the absolute pathname of this file. */
2362 int err;
2364 if (name[0] == '/' || dirname[0] == 0)
2365 path = (char *) name;
2366 else
2368 path = alloca (strlen (name) + strlen (dirname) + 2);
2369 attach (path, dirname, name);
2372 switch (dereference)
2374 case DEREF_ALWAYS:
2375 err = stat (path, &f->stat);
2376 break;
2378 case DEREF_COMMAND_LINE_ARGUMENTS:
2379 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2380 if (explicit_arg)
2382 int need_lstat;
2383 err = stat (path, &f->stat);
2385 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2386 break;
2388 need_lstat = (err < 0
2389 ? errno == ENOENT
2390 : ! S_ISDIR (f->stat.st_mode));
2391 if (!need_lstat)
2392 break;
2394 /* stat failed because of ENOENT, maybe indicating a dangling
2395 symlink. Or stat succeeded, PATH does not refer to a
2396 directory, and --dereference-command-line-symlink-to-dir is
2397 in effect. Fall through so that we call lstat instead. */
2400 default: /* DEREF_NEVER */
2401 err = lstat (path, &f->stat);
2402 break;
2405 if (err < 0)
2407 error (0, errno, "%s", quotearg_colon (path));
2408 exit_status = 1;
2409 return 0;
2412 #if HAVE_ACL
2413 if (format == long_format)
2415 int n = file_has_acl (path, &f->stat);
2416 f->have_acl = (0 < n);
2417 if (n < 0)
2418 error (0, errno, "%s", quotearg_colon (path));
2420 #endif
2422 if (S_ISLNK (f->stat.st_mode)
2423 && (format == long_format || check_symlink_color))
2425 char *linkpath;
2426 struct stat linkstats;
2428 get_link_name (path, f);
2429 linkpath = make_link_path (path, f->linkname);
2431 /* Avoid following symbolic links when possible, ie, when
2432 they won't be traced and when no indicator is needed. */
2433 if (linkpath
2434 && (indicator_style != none || check_symlink_color)
2435 && stat (linkpath, &linkstats) == 0)
2437 f->linkok = 1;
2439 /* Symbolic links to directories that are mentioned on the
2440 command line are automatically traced if not being
2441 listed as files. */
2442 if (!explicit_arg || format == long_format
2443 || !S_ISDIR (linkstats.st_mode))
2445 /* Get the linked-to file's mode for the filetype indicator
2446 in long listings. */
2447 f->linkmode = linkstats.st_mode;
2448 f->linkok = 1;
2451 if (linkpath)
2452 free (linkpath);
2455 if (S_ISLNK (f->stat.st_mode))
2456 f->filetype = symbolic_link;
2457 else if (S_ISDIR (f->stat.st_mode))
2459 if (explicit_arg && !immediate_dirs)
2460 f->filetype = arg_directory;
2461 else
2462 f->filetype = directory;
2464 else
2465 f->filetype = normal;
2468 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2469 int len = strlen (umaxtostr (f->stat.st_ino, buf));
2470 if (inode_number_width < len)
2471 inode_number_width = len;
2474 blocks = ST_NBLOCKS (f->stat);
2476 char buf[LONGEST_HUMAN_READABLE + 1];
2477 int len = strlen (human_readable (blocks, buf, human_output_opts,
2478 ST_NBLOCKSIZE, output_block_size));
2479 if (block_size_width < len)
2480 block_size_width = len;
2483 if (print_owner)
2485 int len = format_user_width (f->stat.st_uid);
2486 if (owner_width < len)
2487 owner_width = len;
2490 if (print_group)
2492 int len = format_group_width (f->stat.st_gid);
2493 if (group_width < len)
2494 group_width = len;
2497 if (print_author)
2499 int len = format_user_width (f->stat.st_uid);
2500 if (author_width < len)
2501 author_width = len;
2505 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2506 int len = strlen (umaxtostr (f->stat.st_nlink, buf));
2507 if (nlink_width < len)
2508 nlink_width = len;
2511 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2513 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2514 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2515 if (major_device_number_width < len)
2516 major_device_number_width = len;
2517 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2518 if (minor_device_number_width < len)
2519 minor_device_number_width = len;
2520 len = major_device_number_width + 2 + minor_device_number_width;
2521 if (file_size_width < len)
2522 file_size_width = len;
2524 else
2526 char buf[LONGEST_HUMAN_READABLE + 1];
2527 uintmax_t size = unsigned_file_size (f->stat.st_size);
2528 int len = strlen (human_readable (size, buf, human_output_opts,
2529 1, file_output_block_size));
2530 if (file_size_width < len)
2531 file_size_width = len;
2534 else
2536 f->filetype = type;
2537 #if HAVE_STRUCT_DIRENT_D_TYPE
2538 f->stat.st_mode = DTTOIF (type);
2539 #endif
2540 blocks = 0;
2543 f->name = xstrdup (name);
2544 files_index++;
2546 return blocks;
2549 #ifdef S_ISLNK
2551 /* Put the name of the file that `filename' is a symbolic link to
2552 into the `linkname' field of `f'. */
2554 static void
2555 get_link_name (const char *filename, struct fileinfo *f)
2557 f->linkname = xreadlink (filename);
2558 if (f->linkname == NULL)
2560 error (0, errno, _("cannot read symbolic link %s"),
2561 quotearg_colon (filename));
2562 exit_status = 1;
2566 /* If `linkname' is a relative path and `path' contains one or more
2567 leading directories, return `linkname' with those directories
2568 prepended; otherwise, return a copy of `linkname'.
2569 If `linkname' is zero, return zero. */
2571 static char *
2572 make_link_path (const char *path, const char *linkname)
2574 char *linkbuf;
2575 size_t bufsiz;
2577 if (linkname == 0)
2578 return 0;
2580 if (*linkname == '/')
2581 return xstrdup (linkname);
2583 /* The link is to a relative path. Prepend any leading path
2584 in `path' to the link name. */
2585 linkbuf = strrchr (path, '/');
2586 if (linkbuf == 0)
2587 return xstrdup (linkname);
2589 bufsiz = linkbuf - path + 1;
2590 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
2591 strncpy (linkbuf, path, bufsiz);
2592 strcpy (linkbuf + bufsiz, linkname);
2593 return linkbuf;
2595 #endif
2597 /* Return nonzero if base_name (NAME) ends in `.' or `..'
2598 This is so we don't try to recurse on `././././. ...' */
2600 static int
2601 basename_is_dot_or_dotdot (const char *name)
2603 char const *base = base_name (name);
2604 return DOT_OR_DOTDOT (base);
2607 /* Remove any entries from `files' that are for directories,
2608 and queue them to be listed as directories instead.
2609 `dirname' is the prefix to prepend to each dirname
2610 to make it correct relative to ls's working dir.
2611 If IGNORE_DOT_AND_DOT_DOT is nonzero don't treat `.' and `..' as dirs.
2612 This is desirable when processing directories recursively. */
2614 static void
2615 extract_dirs_from_files (const char *dirname, int ignore_dot_and_dot_dot)
2617 register size_t i;
2618 register size_t j;
2620 if (*dirname && LOOP_DETECT)
2622 /* Insert a marker entry first. When we dequeue this marker entry,
2623 we'll know that DIRNAME has been processed and may be removed
2624 from the set of active directories. */
2625 queue_directory (NULL, dirname);
2628 /* Queue the directories last one first, because queueing reverses the
2629 order. */
2630 for (i = files_index; i-- != 0; )
2631 if ((files[i].filetype == directory || files[i].filetype == arg_directory)
2632 && (!ignore_dot_and_dot_dot
2633 || !basename_is_dot_or_dotdot (files[i].name)))
2635 if (files[i].name[0] == '/' || dirname[0] == 0)
2637 queue_directory (files[i].name, files[i].linkname);
2639 else
2641 char *path = path_concat (dirname, files[i].name, NULL);
2642 queue_directory (path, files[i].linkname);
2643 free (path);
2645 if (files[i].filetype == arg_directory)
2646 free (files[i].name);
2649 /* Now delete the directories from the table, compacting all the remaining
2650 entries. */
2652 for (i = 0, j = 0; i < files_index; i++)
2654 if (files[i].filetype != arg_directory)
2656 if (j < i)
2657 files[j] = files[i];
2658 ++j;
2661 files_index = j;
2664 /* Use strcoll to compare strings in this locale. If an error occurs,
2665 report an error and longjmp to failed_strcoll. */
2667 static jmp_buf failed_strcoll;
2669 static int
2670 xstrcoll (char const *a, char const *b)
2672 int diff;
2673 errno = 0;
2674 diff = strcoll (a, b);
2675 if (errno)
2677 error (0, errno, _("cannot compare file names %s and %s"),
2678 quote_n (0, a), quote_n (1, b));
2679 exit_status = 1;
2680 longjmp (failed_strcoll, 1);
2682 return diff;
2685 /* Comparison routines for sorting the files. */
2687 typedef void const *V;
2689 static inline int
2690 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
2691 int (*cmp) (char const *, char const *))
2693 int diff = CTIME_CMP (b->stat, a->stat);
2694 return diff ? diff : cmp (a->name, b->name);
2696 static int compare_ctime (V a, V b) { return cmp_ctime (a, b, xstrcoll); }
2697 static int compstr_ctime (V a, V b) { return cmp_ctime (a, b, strcmp); }
2698 static int rev_cmp_ctime (V a, V b) { return compare_ctime (b, a); }
2699 static int rev_str_ctime (V a, V b) { return compstr_ctime (b, a); }
2701 static inline int
2702 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
2703 int (*cmp) (char const *, char const *))
2705 int diff = MTIME_CMP (b->stat, a->stat);
2706 return diff ? diff : cmp (a->name, b->name);
2708 static int compare_mtime (V a, V b) { return cmp_mtime (a, b, xstrcoll); }
2709 static int compstr_mtime (V a, V b) { return cmp_mtime (a, b, strcmp); }
2710 static int rev_cmp_mtime (V a, V b) { return compare_mtime (b, a); }
2711 static int rev_str_mtime (V a, V b) { return compstr_mtime (b, a); }
2713 static inline int
2714 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
2715 int (*cmp) (char const *, char const *))
2717 int diff = ATIME_CMP (b->stat, a->stat);
2718 return diff ? diff : cmp (a->name, b->name);
2720 static int compare_atime (V a, V b) { return cmp_atime (a, b, xstrcoll); }
2721 static int compstr_atime (V a, V b) { return cmp_atime (a, b, strcmp); }
2722 static int rev_cmp_atime (V a, V b) { return compare_atime (b, a); }
2723 static int rev_str_atime (V a, V b) { return compstr_atime (b, a); }
2725 static inline int
2726 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
2727 int (*cmp) (char const *, char const *))
2729 int diff = longdiff (b->stat.st_size, a->stat.st_size);
2730 return diff ? diff : cmp (a->name, b->name);
2732 static int compare_size (V a, V b) { return cmp_size (a, b, xstrcoll); }
2733 static int compstr_size (V a, V b) { return cmp_size (a, b, strcmp); }
2734 static int rev_cmp_size (V a, V b) { return compare_size (b, a); }
2735 static int rev_str_size (V a, V b) { return compstr_size (b, a); }
2737 static inline int
2738 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
2740 return strverscmp (a->name, b->name);
2742 static int compare_version (V a, V b) { return cmp_version (a, b); }
2743 static int rev_cmp_version (V a, V b) { return compare_version (b, a); }
2745 static inline int
2746 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
2747 int (*cmp) (char const *, char const *))
2749 return cmp (a->name, b->name);
2751 static int compare_name (V a, V b) { return cmp_name (a, b, xstrcoll); }
2752 static int compstr_name (V a, V b) { return cmp_name (a, b, strcmp); }
2753 static int rev_cmp_name (V a, V b) { return compare_name (b, a); }
2754 static int rev_str_name (V a, V b) { return compstr_name (b, a); }
2756 /* Compare file extensions. Files with no extension are `smallest'.
2757 If extensions are the same, compare by filenames instead. */
2759 static inline int
2760 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
2761 int (*cmp) (char const *, char const *))
2763 char const *base1 = strrchr (a->name, '.');
2764 char const *base2 = strrchr (b->name, '.');
2765 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
2766 return diff ? diff : cmp (a->name, b->name);
2768 static int compare_extension (V a, V b) { return cmp_extension (a, b, xstrcoll); }
2769 static int compstr_extension (V a, V b) { return cmp_extension (a, b, strcmp); }
2770 static int rev_cmp_extension (V a, V b) { return compare_extension (b, a); }
2771 static int rev_str_extension (V a, V b) { return compstr_extension (b, a); }
2773 /* Sort the files now in the table. */
2775 static void
2776 sort_files (void)
2778 /* `func' must be `volatile', so it can't be
2779 clobbered by a `longjmp' into this function. */
2780 int (* volatile func) (V, V);
2782 switch (sort_type)
2784 case sort_none:
2785 return;
2786 case sort_time:
2787 switch (time_type)
2789 case time_ctime:
2790 func = sort_reverse ? rev_cmp_ctime : compare_ctime;
2791 break;
2792 case time_mtime:
2793 func = sort_reverse ? rev_cmp_mtime : compare_mtime;
2794 break;
2795 case time_atime:
2796 func = sort_reverse ? rev_cmp_atime : compare_atime;
2797 break;
2798 default:
2799 abort ();
2801 break;
2802 case sort_name:
2803 func = sort_reverse ? rev_cmp_name : compare_name;
2804 break;
2805 case sort_extension:
2806 func = sort_reverse ? rev_cmp_extension : compare_extension;
2807 break;
2808 case sort_size:
2809 func = sort_reverse ? rev_cmp_size : compare_size;
2810 break;
2811 case sort_version:
2812 func = sort_reverse ? rev_cmp_version : compare_version;
2813 break;
2814 default:
2815 abort ();
2818 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
2819 ignore strcoll failures, as a failing strcoll might be a
2820 comparison function that is not a total order, and if we ignored
2821 the failure this might cause qsort to dump core. */
2823 if (setjmp (failed_strcoll))
2825 switch (sort_type)
2827 case sort_time:
2828 switch (time_type)
2830 case time_ctime:
2831 func = sort_reverse ? rev_str_ctime : compstr_ctime;
2832 break;
2833 case time_mtime:
2834 func = sort_reverse ? rev_str_mtime : compstr_mtime;
2835 break;
2836 case time_atime:
2837 func = sort_reverse ? rev_str_atime : compstr_atime;
2838 break;
2839 default:
2840 abort ();
2842 break;
2843 case sort_name:
2844 func = sort_reverse ? rev_str_name : compstr_name;
2845 break;
2846 case sort_extension:
2847 func = sort_reverse ? rev_str_extension : compstr_extension;
2848 break;
2849 case sort_size:
2850 func = sort_reverse ? rev_str_size : compstr_size;
2851 break;
2852 default:
2853 abort ();
2857 qsort (files, files_index, sizeof (struct fileinfo), func);
2860 /* List all the files now in the table. */
2862 static void
2863 print_current_files (void)
2865 register size_t i;
2867 switch (format)
2869 case one_per_line:
2870 for (i = 0; i < files_index; i++)
2872 print_file_name_and_frills (files + i);
2873 putchar ('\n');
2875 break;
2877 case many_per_line:
2878 print_many_per_line ();
2879 break;
2881 case horizontal:
2882 print_horizontal ();
2883 break;
2885 case with_commas:
2886 print_with_commas ();
2887 break;
2889 case long_format:
2890 for (i = 0; i < files_index; i++)
2892 print_long_format (files + i);
2893 DIRED_PUTCHAR ('\n');
2895 break;
2899 /* Return the expected number of columns in a long-format time stamp,
2900 or zero if it cannot be calculated. */
2902 static int
2903 long_time_expected_width (void)
2905 static int width = -1;
2907 if (width < 0)
2909 time_t epoch = 0;
2910 struct tm const *tm = localtime (&epoch);
2911 char const *fmt = long_time_format[0];
2912 char initbuf[100];
2913 char *buf = initbuf;
2914 size_t bufsize = sizeof initbuf;
2915 size_t len;
2917 for (;;)
2919 *buf = '\1';
2920 len = nstrftime (buf, bufsize, fmt, tm, 0, 0);
2921 if (len || ! *buf)
2922 break;
2923 buf = alloca (bufsize *= 2);
2926 width = mbsnwidth (buf, len, 0);
2927 if (width < 0)
2928 width = 0;
2931 return width;
2934 /* Get the current time. */
2936 static void
2937 get_current_time (void)
2939 #if HAVE_CLOCK_GETTIME && defined CLOCK_REALTIME
2941 struct timespec timespec;
2942 if (clock_gettime (CLOCK_REALTIME, &timespec) == 0)
2944 current_time = timespec.tv_sec;
2945 current_time_ns = timespec.tv_nsec;
2946 return;
2949 #endif
2951 /* The clock does not have nanosecond resolution, so get the maximum
2952 possible value for the current time that is consistent with the
2953 reported clock. That way, files are not considered to be in the
2954 future merely because their time stamps have higher resolution
2955 than the clock resolution. */
2957 #if HAVE_GETTIMEOFDAY
2959 struct timeval timeval;
2960 if (gettimeofday (&timeval, NULL) == 0)
2962 current_time = timeval.tv_sec;
2963 current_time_ns = timeval.tv_usec * 1000 + 999;
2964 return;
2967 #endif
2969 current_time = time (NULL);
2970 current_time_ns = 999999999;
2973 /* Print the name or id of the user with id U, using a print width of
2974 WIDTH. */
2976 static void
2977 format_user (uid_t u, int width)
2979 char const *name = (numeric_ids ? NULL : getuser (u));
2980 if (name)
2981 printf ("%-*s ", width, name);
2982 else
2983 printf ("%*lu ", width, (unsigned long int) u);
2984 dired_pos += width;
2985 dired_pos++;
2988 /* Likewise, for groups. */
2990 static void
2991 format_group (gid_t g, int width)
2993 char const *name = (numeric_ids ? NULL : getgroup (g));
2994 if (name)
2995 printf ("%-*s ", width, name);
2996 else
2997 printf ("%*lu ", width, (unsigned long int) g);
2998 dired_pos += width;
2999 dired_pos++;
3002 /* Return the number of bytes that format_user will print. */
3004 static int
3005 format_user_width (uid_t u)
3007 char const *name = (numeric_ids ? NULL : getuser (u));
3008 char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3009 size_t len;
3011 if (! name)
3013 sprintf (buf, "%lu", (unsigned long int) u);
3014 name = buf;
3017 len = strlen (name);
3018 if (INT_MAX < len)
3019 error (EXIT_FAILURE, 0, _("User name too long"));
3020 return len;
3023 /* Likewise, for groups. */
3025 static int
3026 format_group_width (gid_t g)
3028 char const *name = (numeric_ids ? NULL : getgroup (g));
3029 char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3030 size_t len;
3032 if (! name)
3034 sprintf (buf, "%lu", (unsigned long int) g);
3035 name = buf;
3038 len = strlen (name);
3039 if (INT_MAX < len)
3040 error (EXIT_FAILURE, 0, _("Group name too long"));
3041 return len;
3045 /* Print information about F in long format. */
3047 static void
3048 print_long_format (const struct fileinfo *f)
3050 char modebuf[12];
3051 char init_bigbuf
3052 [LONGEST_HUMAN_READABLE + 1 /* inode */
3053 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
3054 + sizeof (modebuf) - 1 + 1 /* mode string */
3055 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3056 + LONGEST_HUMAN_READABLE + 2 /* major device number */
3057 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
3058 + 35 + 1 /* usual length of time/date -- may be longer; see below */
3060 char *buf = init_bigbuf;
3061 size_t bufsize = sizeof (init_bigbuf);
3062 size_t s;
3063 char *p;
3064 time_t when;
3065 int when_ns IF_LINT (= 0);
3066 struct tm *when_local;
3068 /* Compute mode string. On most systems, it's based on st_mode.
3069 On systems with migration (via the stat.st_dm_mode field), use
3070 the file's migrated status. */
3071 mode_string (ST_DM_MODE (f->stat), modebuf);
3073 modebuf[10] = (FILE_HAS_ACL (f) ? '+' : ' ');
3074 modebuf[11] = '\0';
3076 switch (time_type)
3078 case time_ctime:
3079 when = f->stat.st_ctime;
3080 when_ns = TIMESPEC_NS (f->stat.st_ctim);
3081 break;
3082 case time_mtime:
3083 when = f->stat.st_mtime;
3084 when_ns = TIMESPEC_NS (f->stat.st_mtim);
3085 break;
3086 case time_atime:
3087 when = f->stat.st_atime;
3088 when_ns = TIMESPEC_NS (f->stat.st_atim);
3089 break;
3092 p = buf;
3094 if (print_inode)
3096 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3097 sprintf (p, "%*s ", inode_number_width,
3098 umaxtostr (f->stat.st_ino, hbuf));
3099 p += inode_number_width + 1;
3102 if (print_block_size)
3104 char hbuf[LONGEST_HUMAN_READABLE + 1];
3105 sprintf (p, "%*s ", block_size_width,
3106 human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3107 ST_NBLOCKSIZE, output_block_size));
3108 p += block_size_width + 1;
3111 /* The last byte of the mode string is the POSIX
3112 "optional alternate access method flag". */
3114 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3115 sprintf (p, "%s %*s ", modebuf, nlink_width,
3116 umaxtostr (f->stat.st_nlink, hbuf));
3118 p += sizeof modebuf + nlink_width + 1;
3120 DIRED_INDENT ();
3122 if (print_owner | print_group | print_author)
3124 DIRED_FPUTS (buf, stdout, p - buf);
3126 if (print_owner)
3127 format_user (f->stat.st_uid, owner_width);
3129 if (print_group)
3130 format_group (f->stat.st_gid, group_width);
3132 if (print_author)
3133 format_user (f->stat.st_author, author_width);
3135 p = buf;
3138 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
3140 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3141 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3142 int blanks_width = (file_size_width
3143 - (major_device_number_width + 2
3144 + minor_device_number_width));
3145 sprintf (p, "%*s, %*s ",
3146 major_device_number_width + MAX (0, blanks_width),
3147 umaxtostr (major (f->stat.st_rdev), majorbuf),
3148 minor_device_number_width,
3149 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3151 else
3153 char hbuf[LONGEST_HUMAN_READABLE + 1];
3154 uintmax_t size = unsigned_file_size (f->stat.st_size);
3155 sprintf (p, "%*s ", file_size_width,
3156 human_readable (size, hbuf, human_output_opts,
3157 1, file_output_block_size));
3160 p += file_size_width + 1;
3162 if ((when_local = localtime (&when)))
3164 time_t six_months_ago;
3165 int recent;
3166 char const *fmt;
3168 /* If the file appears to be in the future, update the current
3169 time, in case the file happens to have been modified since
3170 the last time we checked the clock. */
3171 if (current_time < when
3172 || (current_time == when && current_time_ns < when_ns))
3174 /* Note that get_current_time calls gettimeofday which, on some non-
3175 compliant systems, clobbers the buffer used for localtime's result.
3176 But it's ok here, because we use a gettimeofday wrapper that
3177 saves and restores the buffer around the gettimeofday call. */
3178 get_current_time ();
3181 /* Consider a time to be recent if it is within the past six
3182 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3183 31556952 seconds on the average. Write this value as an
3184 integer constant to avoid floating point hassles. */
3185 six_months_ago = current_time - 31556952 / 2;
3186 recent = (six_months_ago <= when
3187 && (when < current_time
3188 || (when == current_time && when_ns <= current_time_ns)));
3189 fmt = long_time_format[recent];
3191 for (;;)
3193 char *newbuf;
3194 *p = '\1';
3195 s = nstrftime (p, buf + bufsize - p - 1, fmt,
3196 when_local, 0, when_ns);
3197 if (s || ! *p)
3198 break;
3199 newbuf = alloca (bufsize *= 2);
3200 memcpy (newbuf, buf, p - buf);
3201 p = newbuf + (p - buf);
3202 buf = newbuf;
3205 p += s;
3206 *p++ = ' ';
3208 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3209 *p = '\0';
3211 else
3213 /* The time cannot be represented as a local time;
3214 print it as a huge integer number of seconds. */
3215 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3216 sprintf (p, "%*s ", long_time_expected_width (),
3217 (TYPE_SIGNED (time_t)
3218 ? imaxtostr (when, hbuf)
3219 : umaxtostr (when, hbuf)));
3220 p += strlen (p);
3223 DIRED_FPUTS (buf, stdout, p - buf);
3224 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3225 &dired_obstack);
3227 if (f->filetype == symbolic_link)
3229 if (f->linkname)
3231 DIRED_FPUTS_LITERAL (" -> ", stdout);
3232 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3233 NULL);
3234 if (indicator_style != none)
3235 print_type_indicator (f->linkmode);
3238 else if (indicator_style != none)
3239 print_type_indicator (f->stat.st_mode);
3242 /* Output to OUT a quoted representation of the file name NAME,
3243 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3244 Store the number of screen columns occupied by NAME's quoted
3245 representation into WIDTH, if non-NULL. Return the number of bytes
3246 produced. */
3248 static size_t
3249 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3250 size_t *width)
3252 char smallbuf[BUFSIZ];
3253 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3254 char *buf;
3255 size_t displayed_width IF_LINT (= 0);
3257 if (len < sizeof smallbuf)
3258 buf = smallbuf;
3259 else
3261 buf = alloca (len + 1);
3262 quotearg_buffer (buf, len + 1, name, -1, options);
3265 if (qmark_funny_chars)
3267 #if HAVE_MBRTOWC
3268 if (MB_CUR_MAX > 1)
3270 char const *p = buf;
3271 char const *plimit = buf + len;
3272 char *q = buf;
3273 displayed_width = 0;
3275 while (p < plimit)
3276 switch (*p)
3278 case ' ': case '!': case '"': case '#': case '%':
3279 case '&': case '\'': case '(': case ')': case '*':
3280 case '+': case ',': case '-': case '.': case '/':
3281 case '0': case '1': case '2': case '3': case '4':
3282 case '5': case '6': case '7': case '8': case '9':
3283 case ':': case ';': case '<': case '=': case '>':
3284 case '?':
3285 case 'A': case 'B': case 'C': case 'D': case 'E':
3286 case 'F': case 'G': case 'H': case 'I': case 'J':
3287 case 'K': case 'L': case 'M': case 'N': case 'O':
3288 case 'P': case 'Q': case 'R': case 'S': case 'T':
3289 case 'U': case 'V': case 'W': case 'X': case 'Y':
3290 case 'Z':
3291 case '[': case '\\': case ']': case '^': case '_':
3292 case 'a': case 'b': case 'c': case 'd': case 'e':
3293 case 'f': case 'g': case 'h': case 'i': case 'j':
3294 case 'k': case 'l': case 'm': case 'n': case 'o':
3295 case 'p': case 'q': case 'r': case 's': case 't':
3296 case 'u': case 'v': case 'w': case 'x': case 'y':
3297 case 'z': case '{': case '|': case '}': case '~':
3298 /* These characters are printable ASCII characters. */
3299 *q++ = *p++;
3300 displayed_width += 1;
3301 break;
3302 default:
3303 /* If we have a multibyte sequence, copy it until we
3304 reach its end, replacing each non-printable multibyte
3305 character with a single question mark. */
3307 mbstate_t mbstate;
3308 memset (&mbstate, 0, sizeof mbstate);
3311 wchar_t wc;
3312 size_t bytes;
3313 int w;
3315 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3317 if (bytes == (size_t) -1)
3319 /* An invalid multibyte sequence was
3320 encountered. Skip one input byte, and
3321 put a question mark. */
3322 p++;
3323 *q++ = '?';
3324 displayed_width += 1;
3325 break;
3328 if (bytes == (size_t) -2)
3330 /* An incomplete multibyte character
3331 at the end. Replace it entirely with
3332 a question mark. */
3333 p = plimit;
3334 *q++ = '?';
3335 displayed_width += 1;
3336 break;
3339 if (bytes == 0)
3340 /* A null wide character was encountered. */
3341 bytes = 1;
3343 w = wcwidth (wc);
3344 if (w >= 0)
3346 /* A printable multibyte character.
3347 Keep it. */
3348 for (; bytes > 0; --bytes)
3349 *q++ = *p++;
3350 displayed_width += w;
3352 else
3354 /* An unprintable multibyte character.
3355 Replace it entirely with a question
3356 mark. */
3357 p += bytes;
3358 *q++ = '?';
3359 displayed_width += 1;
3362 while (! mbsinit (&mbstate));
3364 break;
3367 /* The buffer may have shrunk. */
3368 len = q - buf;
3370 else
3371 #endif
3373 char *p = buf;
3374 char const *plimit = buf + len;
3376 while (p < plimit)
3378 if (! ISPRINT ((unsigned char) *p))
3379 *p = '?';
3380 p++;
3382 displayed_width = len;
3385 else if (width != NULL)
3387 #if HAVE_MBRTOWC
3388 if (MB_CUR_MAX > 1)
3389 displayed_width = mbsnwidth (buf, len, 0);
3390 else
3391 #endif
3393 char const *p = buf;
3394 char const *plimit = buf + len;
3396 displayed_width = 0;
3397 while (p < plimit)
3399 if (ISPRINT ((unsigned char) *p))
3400 displayed_width++;
3401 p++;
3406 if (out != NULL)
3407 fwrite (buf, 1, len, out);
3408 if (width != NULL)
3409 *width = displayed_width;
3410 return len;
3413 static void
3414 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3415 struct obstack *stack)
3417 if (print_with_color)
3418 print_color_indicator (p, mode, linkok);
3420 if (stack)
3421 PUSH_CURRENT_DIRED_POS (stack);
3423 dired_pos += quote_name (stdout, p, filename_quoting_options, NULL);
3425 if (stack)
3426 PUSH_CURRENT_DIRED_POS (stack);
3428 if (print_with_color)
3429 prep_non_filename_text ();
3432 static void
3433 prep_non_filename_text (void)
3435 if (color_indicator[C_END].string != NULL)
3436 put_indicator (&color_indicator[C_END]);
3437 else
3439 put_indicator (&color_indicator[C_LEFT]);
3440 put_indicator (&color_indicator[C_NORM]);
3441 put_indicator (&color_indicator[C_RIGHT]);
3445 /* Print the file name of `f' with appropriate quoting.
3446 Also print file size, inode number, and filetype indicator character,
3447 as requested by switches. */
3449 static void
3450 print_file_name_and_frills (const struct fileinfo *f)
3452 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3454 if (print_inode)
3455 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
3456 umaxtostr (f->stat.st_ino, buf));
3458 if (print_block_size)
3459 printf ("%*s ", format == with_commas ? 0 : block_size_width,
3460 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3461 ST_NBLOCKSIZE, output_block_size));
3463 print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok, NULL);
3465 if (indicator_style != none)
3466 print_type_indicator (f->stat.st_mode);
3469 static void
3470 print_type_indicator (mode_t mode)
3472 int c;
3474 if (S_ISREG (mode))
3476 if (indicator_style == classify && (mode & S_IXUGO))
3477 c ='*';
3478 else
3479 c = 0;
3481 else
3483 if (S_ISDIR (mode))
3484 c = '/';
3485 else if (S_ISLNK (mode))
3486 c = '@';
3487 else if (S_ISFIFO (mode))
3488 c = '|';
3489 else if (S_ISSOCK (mode))
3490 c = '=';
3491 else if (S_ISDOOR (mode))
3492 c = '>';
3493 else
3494 c = 0;
3497 if (c)
3498 DIRED_PUTCHAR (c);
3501 static void
3502 print_color_indicator (const char *name, mode_t mode, int linkok)
3504 int type = C_FILE;
3505 struct color_ext_type *ext; /* Color extension */
3506 size_t len; /* Length of name */
3508 /* Is this a nonexistent file? If so, linkok == -1. */
3510 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
3512 ext = NULL;
3513 type = C_MISSING;
3515 else
3517 if (S_ISDIR (mode))
3518 type = C_DIR;
3519 else if (S_ISLNK (mode))
3520 type = ((!linkok && color_indicator[C_ORPHAN].string)
3521 ? C_ORPHAN : C_LINK);
3522 else if (S_ISFIFO (mode))
3523 type = C_FIFO;
3524 else if (S_ISSOCK (mode))
3525 type = C_SOCK;
3526 else if (S_ISBLK (mode))
3527 type = C_BLK;
3528 else if (S_ISCHR (mode))
3529 type = C_CHR;
3530 else if (S_ISDOOR (mode))
3531 type = C_DOOR;
3533 if (type == C_FILE && (mode & S_IXUGO) != 0)
3534 type = C_EXEC;
3536 /* Check the file's suffix only if still classified as C_FILE. */
3537 ext = NULL;
3538 if (type == C_FILE)
3540 /* Test if NAME has a recognized suffix. */
3542 len = strlen (name);
3543 name += len; /* Pointer to final \0. */
3544 for (ext = color_ext_list; ext != NULL; ext = ext->next)
3546 if (ext->ext.len <= len
3547 && strncmp (name - ext->ext.len, ext->ext.string,
3548 ext->ext.len) == 0)
3549 break;
3554 put_indicator (&color_indicator[C_LEFT]);
3555 put_indicator (ext ? &(ext->seq) : &color_indicator[type]);
3556 put_indicator (&color_indicator[C_RIGHT]);
3559 /* Output a color indicator (which may contain nulls). */
3560 static void
3561 put_indicator (const struct bin_str *ind)
3563 register size_t i;
3564 register const char *p;
3566 p = ind->string;
3568 for (i = ind->len; i != 0; --i)
3569 putchar (*(p++));
3572 /* Output a color indicator, but don't use stdio, for use from signal handlers.
3573 Return zero if the write is successful or if the string length is zero.
3574 Return nonzero if the write fails. */
3575 static int
3576 put_indicator_direct (const struct bin_str *ind)
3578 size_t len;
3579 if (ind->len == 0)
3580 return 0;
3582 len = ind->len;
3583 return (full_write (STDOUT_FILENO, ind->string, len) != len);
3586 static size_t
3587 length_of_file_name_and_frills (const struct fileinfo *f)
3589 register size_t len = 0;
3590 size_t name_width;
3591 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3593 if (print_inode)
3594 len += 1 + (format == with_commas
3595 ? strlen (umaxtostr (f->stat.st_ino, buf))
3596 : inode_number_width);
3598 if (print_block_size)
3599 len += 1 + (format == with_commas
3600 ? strlen (human_readable (ST_NBLOCKS (f->stat), buf,
3601 human_output_opts, ST_NBLOCKSIZE,
3602 output_block_size))
3603 : block_size_width);
3605 quote_name (NULL, f->name, filename_quoting_options, &name_width);
3606 len += name_width;
3608 if (indicator_style != none)
3610 mode_t filetype = f->stat.st_mode;
3612 if (S_ISREG (filetype))
3614 if (indicator_style == classify
3615 && (f->stat.st_mode & S_IXUGO))
3616 len += 1;
3618 else if (S_ISDIR (filetype)
3619 || S_ISLNK (filetype)
3620 || S_ISFIFO (filetype)
3621 || S_ISSOCK (filetype)
3622 || S_ISDOOR (filetype)
3624 len += 1;
3627 return len;
3630 static void
3631 print_many_per_line (void)
3633 size_t row; /* Current row. */
3634 size_t cols = calculate_columns (true);
3635 struct column_info const *line_fmt = &column_info[cols - 1];
3637 /* Calculate the number of rows that will be in each column except possibly
3638 for a short column on the right. */
3639 size_t rows = files_index / cols + (files_index % cols != 0);
3641 for (row = 0; row < rows; row++)
3643 size_t col = 0;
3644 size_t filesno = row;
3645 size_t pos = 0;
3647 /* Print the next row. */
3648 while (1)
3650 size_t name_length = length_of_file_name_and_frills (files + filesno);
3651 size_t max_name_length = line_fmt->col_arr[col++];
3652 print_file_name_and_frills (files + filesno);
3654 filesno += rows;
3655 if (filesno >= files_index)
3656 break;
3658 indent (pos + name_length, pos + max_name_length);
3659 pos += max_name_length;
3661 putchar ('\n');
3665 static void
3666 print_horizontal (void)
3668 size_t filesno;
3669 size_t pos = 0;
3670 size_t cols = calculate_columns (false);
3671 struct column_info const *line_fmt = &column_info[cols - 1];
3672 size_t name_length = length_of_file_name_and_frills (files);
3673 size_t max_name_length = line_fmt->col_arr[0];
3675 /* Print first entry. */
3676 print_file_name_and_frills (files);
3678 /* Now the rest. */
3679 for (filesno = 1; filesno < files_index; ++filesno)
3681 size_t col = filesno % cols;
3683 if (col == 0)
3685 putchar ('\n');
3686 pos = 0;
3688 else
3690 indent (pos + name_length, pos + max_name_length);
3691 pos += max_name_length;
3694 print_file_name_and_frills (files + filesno);
3696 name_length = length_of_file_name_and_frills (files + filesno);
3697 max_name_length = line_fmt->col_arr[col];
3699 putchar ('\n');
3702 static void
3703 print_with_commas (void)
3705 size_t filesno;
3706 size_t pos = 0;
3708 for (filesno = 0; filesno < files_index; filesno++)
3710 size_t len = length_of_file_name_and_frills (files + filesno);
3712 if (filesno != 0)
3714 char separator;
3716 if (pos + len + 2 < line_length)
3718 pos += 2;
3719 separator = ' ';
3721 else
3723 pos = 0;
3724 separator = '\n';
3727 putchar (',');
3728 putchar (separator);
3731 print_file_name_and_frills (files + filesno);
3732 pos += len;
3734 putchar ('\n');
3737 /* Assuming cursor is at position FROM, indent up to position TO.
3738 Use a TAB character instead of two or more spaces whenever possible. */
3740 static void
3741 indent (size_t from, size_t to)
3743 while (from < to)
3745 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
3747 putchar ('\t');
3748 from += tabsize - from % tabsize;
3750 else
3752 putchar (' ');
3753 from++;
3758 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
3759 /* FIXME: maybe remove this function someday. See about using a
3760 non-malloc'ing version of path_concat. */
3762 static void
3763 attach (char *dest, const char *dirname, const char *name)
3765 const char *dirnamep = dirname;
3767 /* Copy dirname if it is not ".". */
3768 if (dirname[0] != '.' || dirname[1] != 0)
3770 while (*dirnamep)
3771 *dest++ = *dirnamep++;
3772 /* Add '/' if `dirname' doesn't already end with it. */
3773 if (dirnamep > dirname && dirnamep[-1] != '/')
3774 *dest++ = '/';
3776 while (*name)
3777 *dest++ = *name++;
3778 *dest = 0;
3781 /* Allocate enough column info suitable for the current number of
3782 files and display columns, and initialize the info to represent the
3783 narrowest possible columns. */
3785 static void
3786 init_column_info (void)
3788 size_t i;
3789 size_t max_cols = MIN (max_idx, files_index);
3791 /* Currently allocated columns in column_info. */
3792 static size_t column_info_alloc;
3794 if (column_info_alloc < max_cols)
3796 size_t new_column_info_alloc;
3797 size_t *p;
3799 if (max_cols < max_idx / 2)
3801 /* The number of columns is far less than the display width
3802 allows. Grow the allocation, but only so that it's
3803 double the current requirements. If the display is
3804 extremely wide, this avoids allocating a lot of memory
3805 that is never needed. */
3806 column_info = xnrealloc (column_info, max_cols,
3807 2 * sizeof *column_info);
3808 new_column_info_alloc = 2 * max_cols;
3810 else
3812 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
3813 new_column_info_alloc = max_idx;
3816 /* Allocate the new size_t objects by computing the triangle
3817 formula n * (n + 1) / 2, except that we don't need to
3818 allocate the part of the triangle that we've already
3819 allocated. Check for address arithmetic overflow. */
3821 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
3822 size_t s = column_info_alloc + 1 + new_column_info_alloc;
3823 size_t t = s * column_info_growth;
3824 if (s < new_column_info_alloc || t / column_info_growth != s)
3825 xalloc_die ();
3826 p = xnmalloc (t / 2, sizeof *p);
3829 /* Grow the triangle by parceling out the cells just allocated. */
3830 for (i = column_info_alloc; i < new_column_info_alloc; i++)
3832 column_info[i].col_arr = p;
3833 p += i + 1;
3836 column_info_alloc = new_column_info_alloc;
3839 for (i = 0; i < max_cols; ++i)
3841 size_t j;
3843 column_info[i].valid_len = true;
3844 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
3845 for (j = 0; j <= i; ++j)
3846 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
3850 /* Calculate the number of columns needed to represent the current set
3851 of files in the current display width. */
3853 static size_t
3854 calculate_columns (bool by_columns)
3856 size_t filesno; /* Index into files. */
3857 size_t cols; /* Number of files across. */
3859 /* Normally the maximum number of columns is determined by the
3860 screen width. But if few files are available this might limit it
3861 as well. */
3862 size_t max_cols = MIN (max_idx, files_index);
3864 init_column_info ();
3866 /* Compute the maximum number of possible columns. */
3867 for (filesno = 0; filesno < files_index; ++filesno)
3869 size_t name_length = length_of_file_name_and_frills (files + filesno);
3870 size_t i;
3872 for (i = 0; i < max_cols; ++i)
3874 if (column_info[i].valid_len)
3876 size_t idx = (by_columns
3877 ? filesno / ((files_index + i) / (i + 1))
3878 : filesno % (i + 1));
3879 size_t real_length = name_length + (idx == i ? 0 : 2);
3881 if (column_info[i].col_arr[idx] < real_length)
3883 column_info[i].line_len += (real_length
3884 - column_info[i].col_arr[idx]);
3885 column_info[i].col_arr[idx] = real_length;
3886 column_info[i].valid_len = (column_info[i].line_len
3887 < line_length);
3893 /* Find maximum allowed columns. */
3894 for (cols = max_cols; 1 < cols; --cols)
3896 if (column_info[cols - 1].valid_len)
3897 break;
3900 return cols;
3903 void
3904 usage (int status)
3906 if (status != 0)
3907 fprintf (stderr, _("Try `%s --help' for more information.\n"),
3908 program_name);
3909 else
3911 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
3912 fputs (_("\
3913 List information about the FILEs (the current directory by default).\n\
3914 Sort entries alphabetically if none of -cftuSUX nor --sort.\n\
3916 "), stdout);
3917 fputs (_("\
3918 Mandatory arguments to long options are mandatory for short options too.\n\
3919 "), stdout);
3920 fputs (_("\
3921 -a, --all do not hide entries starting with .\n\
3922 -A, --almost-all do not list implied . and ..\n\
3923 --author print the author of each file\n\
3924 -b, --escape print octal escapes for nongraphic characters\n\
3925 "), stdout);
3926 fputs (_("\
3927 --block-size=SIZE use SIZE-byte blocks\n\
3928 -B, --ignore-backups do not list implied entries ending with ~\n\
3929 -c with -lt: sort by, and show, ctime (time of last\n\
3930 modification of file status information)\n\
3931 with -l: show ctime and sort by name\n\
3932 otherwise: sort by ctime\n\
3933 "), stdout);
3934 fputs (_("\
3935 -C list entries by columns\n\
3936 --color[=WHEN] control whether color is used to distinguish file\n\
3937 types. WHEN may be `never', `always', or `auto'\n\
3938 -d, --directory list directory entries instead of contents,\n\
3939 and do not dereference symbolic links\n\
3940 -D, --dired generate output designed for Emacs' dired mode\n\
3941 "), stdout);
3942 fputs (_("\
3943 -f do not sort, enable -aU, disable -lst\n\
3944 -F, --classify append indicator (one of */=@|) to entries\n\
3945 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
3946 single-column -1, verbose -l, vertical -C\n\
3947 --full-time like -l --time-style=full-iso\n\
3948 "), stdout);
3949 fputs (_("\
3950 -g like -l, but do not list owner\n\
3951 -G, --no-group inhibit display of group information\n\
3952 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\n\
3953 --si likewise, but use powers of 1000 not 1024\n\
3954 -H, --dereference-command-line\n\
3955 follow symbolic links listed on the command line\n\
3956 --dereference-command-line-symlink-to-dir\n\
3957 follow each command line symbolic link\n\
3958 that points to a directory\n\
3959 "), stdout);
3960 fputs (_("\
3961 --indicator-style=WORD append indicator with style WORD to entry names:\n\
3962 none (default), classify (-F), file-type (-p)\n\
3963 -i, --inode print index number of each file\n\
3964 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
3965 -k like --block-size=1K\n\
3966 "), stdout);
3967 fputs (_("\
3968 -l use a long listing format\n\
3969 -L, --dereference when showing file information for a symbolic\n\
3970 link, show information for the file the link\n\
3971 references rather than for the link itself\n\
3972 -m fill width with a comma separated list of entries\n\
3973 "), stdout);
3974 fputs (_("\
3975 -n, --numeric-uid-gid like -l, but list numeric UIDs and GIDs\n\
3976 -N, --literal print raw entry names (don't treat e.g. control\n\
3977 characters specially)\n\
3978 -o like -l, but do not list group information\n\
3979 -p, --file-type append indicator (one of /=@|) to entries\n\
3980 "), stdout);
3981 fputs (_("\
3982 -q, --hide-control-chars print ? instead of non graphic characters\n\
3983 --show-control-chars show non graphic characters as-is (default\n\
3984 unless program is `ls' and output is a terminal)\n\
3985 -Q, --quote-name enclose entry names in double quotes\n\
3986 --quoting-style=WORD use quoting style WORD for entry names:\n\
3987 literal, locale, shell, shell-always, c, escape\n\
3988 "), stdout);
3989 fputs (_("\
3990 -r, --reverse reverse order while sorting\n\
3991 -R, --recursive list subdirectories recursively\n\
3992 -s, --size print size of each file, in blocks\n\
3993 "), stdout);
3994 fputs (_("\
3995 -S sort by file size\n\
3996 --sort=WORD extension -X, none -U, size -S, time -t,\n\
3997 version -v\n\
3998 status -c, time -t, atime -u, access -u, use -u\n\
3999 --time=WORD show time as WORD instead of modification time:\n\
4000 atime, access, use, ctime or status; use\n\
4001 specified time as sort key if --sort=time\n\
4002 "), stdout);
4003 fputs (_("\
4004 --time-style=STYLE show times using style STYLE:\n\
4005 full-iso, long-iso, iso, locale, +FORMAT\n\
4006 FORMAT is interpreted like `date'; if FORMAT is\n\
4007 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4008 non-recent files and FORMAT2 to recent files;\n\
4009 if STYLE is prefixed with `posix-', STYLE\n\
4010 takes effect only outside the POSIX locale\n\
4011 -t sort by modification time\n\
4012 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4013 "), stdout);
4014 fputs (_("\
4015 -u with -lt: sort by, and show, access time\n\
4016 with -l: show access time and sort by name\n\
4017 otherwise: sort by access time\n\
4018 -U do not sort; list entries in directory order\n\
4019 -v sort by version\n\
4020 "), stdout);
4021 fputs (_("\
4022 -w, --width=COLS assume screen width instead of current value\n\
4023 -x list entries by lines instead of by columns\n\
4024 -X sort alphabetically by entry extension\n\
4025 -1 list one file per line\n\
4026 "), stdout);
4027 fputs (HELP_OPTION_DESCRIPTION, stdout);
4028 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4029 fputs (_("\n\
4030 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4031 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4032 "), stdout);
4033 fputs (_("\
4035 By default, color is not used to distinguish types of files. That is\n\
4036 equivalent to using --color=none. Using the --color option without the\n\
4037 optional WHEN argument is equivalent to using --color=always. With\n\
4038 --color=auto, color codes are output only if standard output is connected\n\
4039 to a terminal (tty).\n\
4040 "), stdout);
4041 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
4043 exit (status);