global: convert indentation-TABs to spaces
[coreutils.git] / src / ls.c
blob6316dfa68a382814ce24df6e23b58e9cc7e02079
1 /* `dir', `vdir' and `ls' directory listing programs for GNU.
2 Copyright (C) 85, 88, 90, 91, 1995-2009 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* If ls_mode is LS_MULTI_COL,
18 the multi-column format is the default regardless
19 of the type of output device.
20 This is for the `dir' program.
22 If ls_mode is LS_LONG_FORMAT,
23 the long format is the default regardless of the
24 type of output device.
25 This is for the `vdir' program.
27 If ls_mode is LS_LS,
28 the output format depends on whether the output
29 device is a terminal.
30 This is for the `ls' program. */
32 /* Written by Richard Stallman and David MacKenzie. */
34 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
35 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
36 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
38 #include <config.h>
39 #include <sys/types.h>
41 #ifdef HAVE_CAP
42 # include <sys/capability.h>
43 #endif
45 #if HAVE_TERMIOS_H
46 # include <termios.h>
47 #endif
48 #if HAVE_STROPTS_H
49 # include <stropts.h>
50 #endif
51 #if HAVE_SYS_IOCTL_H
52 # include <sys/ioctl.h>
53 #endif
55 #ifdef WINSIZE_IN_PTEM
56 # include <sys/stream.h>
57 # include <sys/ptem.h>
58 #endif
60 #include <stdio.h>
61 #include <assert.h>
62 #include <setjmp.h>
63 #include <grp.h>
64 #include <pwd.h>
65 #include <getopt.h>
66 #include <signal.h>
67 #include <selinux/selinux.h>
68 #include <wchar.h>
70 #if HAVE_LANGINFO_CODESET
71 # include <langinfo.h>
72 #endif
74 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
75 present. */
76 #ifndef SA_NOCLDSTOP
77 # define SA_NOCLDSTOP 0
78 # define sigprocmask(How, Set, Oset) /* empty */
79 # define sigset_t int
80 # if ! HAVE_SIGINTERRUPT
81 # define siginterrupt(sig, flag) /* empty */
82 # endif
83 #endif
84 #ifndef SA_RESTART
85 # define SA_RESTART 0
86 #endif
88 #include "system.h"
89 #include <fnmatch.h>
91 #include "acl.h"
92 #include "argmatch.h"
93 #include "dev-ino.h"
94 #include "error.h"
95 #include "filenamecat.h"
96 #include "hash.h"
97 #include "human.h"
98 #include "filemode.h"
99 #include "filevercmp.h"
100 #include "idcache.h"
101 #include "ls.h"
102 #include "mbswidth.h"
103 #include "mpsort.h"
104 #include "obstack.h"
105 #include "quote.h"
106 #include "quotearg.h"
107 #include "same.h"
108 #include "stat-time.h"
109 #include "strftime.h"
110 #include "xstrtol.h"
111 #include "areadlink.h"
112 #include "mbsalign.h"
114 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
115 : (ls_mode == LS_MULTI_COL \
116 ? "dir" : "vdir"))
118 #define AUTHORS \
119 proper_name ("Richard M. Stallman"), \
120 proper_name ("David MacKenzie")
122 #define obstack_chunk_alloc malloc
123 #define obstack_chunk_free free
125 /* Return an int indicating the result of comparing two integers.
126 Subtracting doesn't always work, due to overflow. */
127 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
129 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
130 # define st_author st_uid
131 #endif
133 enum filetype
135 unknown,
136 fifo,
137 chardev,
138 directory,
139 blockdev,
140 normal,
141 symbolic_link,
142 sock,
143 whiteout,
144 arg_directory
147 /* Display letters and indicators for each filetype.
148 Keep these in sync with enum filetype. */
149 static char const filetype_letter[] = "?pcdb-lswd";
151 /* Ensure that filetype and filetype_letter have the same
152 number of elements. */
153 verify (sizeof filetype_letter - 1 == arg_directory + 1);
155 #define FILETYPE_INDICATORS \
157 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
158 C_LINK, C_SOCK, C_FILE, C_DIR \
161 enum acl_type
163 ACL_T_NONE,
164 ACL_T_SELINUX_ONLY,
165 ACL_T_YES
168 struct fileinfo
170 /* The file name. */
171 char *name;
173 /* For symbolic link, name of the file linked to, otherwise zero. */
174 char *linkname;
176 struct stat stat;
178 enum filetype filetype;
180 /* For symbolic link and long listing, st_mode of file linked to, otherwise
181 zero. */
182 mode_t linkmode;
184 /* SELinux security context. */
185 security_context_t scontext;
187 bool stat_ok;
189 /* For symbolic link and color printing, true if linked-to file
190 exists, otherwise false. */
191 bool linkok;
193 /* For long listings, true if the file has an access control list,
194 or an SELinux security context. */
195 enum acl_type acl_type;
198 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
200 /* Null is a valid character in a color indicator (think about Epson
201 printers, for example) so we have to use a length/buffer string
202 type. */
204 struct bin_str
206 size_t len; /* Number of bytes */
207 const char *string; /* Pointer to the same */
210 #if ! HAVE_TCGETPGRP
211 # define tcgetpgrp(Fd) 0
212 #endif
214 static size_t quote_name (FILE *out, const char *name,
215 struct quoting_options const *options,
216 size_t *width);
217 static char *make_link_name (char const *name, char const *linkname);
218 static int decode_switches (int argc, char **argv);
219 static bool file_ignored (char const *name);
220 static uintmax_t gobble_file (char const *name, enum filetype type,
221 ino_t inode, bool command_line_arg,
222 char const *dirname);
223 static bool print_color_indicator (const char *name, mode_t mode, int linkok,
224 bool stat_ok, enum filetype type,
225 nlink_t nlink);
226 static void put_indicator (const struct bin_str *ind);
227 static void add_ignore_pattern (const char *pattern);
228 static void attach (char *dest, const char *dirname, const char *name);
229 static void clear_files (void);
230 static void extract_dirs_from_files (char const *dirname,
231 bool command_line_arg);
232 static void get_link_name (char const *filename, struct fileinfo *f,
233 bool command_line_arg);
234 static void indent (size_t from, size_t to);
235 static size_t calculate_columns (bool by_columns);
236 static void print_current_files (void);
237 static void print_dir (char const *name, char const *realname,
238 bool command_line_arg);
239 static size_t print_file_name_and_frills (const struct fileinfo *f,
240 size_t start_col);
241 static void print_horizontal (void);
242 static int format_user_width (uid_t u);
243 static int format_group_width (gid_t g);
244 static void print_long_format (const struct fileinfo *f);
245 static void print_many_per_line (void);
246 static size_t print_name_with_quoting (const char *p, mode_t mode,
247 int linkok, bool stat_ok,
248 enum filetype type,
249 struct obstack *stack,
250 nlink_t nlink,
251 size_t start_col);
252 static void prep_non_filename_text (void);
253 static bool print_type_indicator (bool stat_ok, mode_t mode,
254 enum filetype type);
255 static void print_with_commas (void);
256 static void queue_directory (char const *name, char const *realname,
257 bool command_line_arg);
258 static void sort_files (void);
259 static void parse_ls_color (void);
260 void usage (int status);
262 /* Initial size of hash table.
263 Most hierarchies are likely to be shallower than this. */
264 #define INITIAL_TABLE_SIZE 30
266 /* The set of `active' directories, from the current command-line argument
267 to the level in the hierarchy at which files are being listed.
268 A directory is represented by its device and inode numbers (struct dev_ino).
269 A directory is added to this set when ls begins listing it or its
270 entries, and it is removed from the set just after ls has finished
271 processing it. This set is used solely to detect loops, e.g., with
272 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
273 static Hash_table *active_dir_set;
275 #define LOOP_DETECT (!!active_dir_set)
277 /* The table of files in the current directory:
279 `cwd_file' points to a vector of `struct fileinfo', one per file.
280 `cwd_n_alloc' is the number of elements space has been allocated for.
281 `cwd_n_used' is the number actually in use. */
283 /* Address of block containing the files that are described. */
284 static struct fileinfo *cwd_file;
286 /* Length of block that `cwd_file' points to, measured in files. */
287 static size_t cwd_n_alloc;
289 /* Index of first unused slot in `cwd_file'. */
290 static size_t cwd_n_used;
292 /* Vector of pointers to files, in proper sorted order, and the number
293 of entries allocated for it. */
294 static void **sorted_file;
295 static size_t sorted_file_alloc;
297 /* When true, in a color listing, color each symlink name according to the
298 type of file it points to. Otherwise, color them according to the `ln'
299 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
300 regardless. This is set when `ln=target' appears in LS_COLORS. */
302 static bool color_symlink_as_referent;
304 /* mode of appropriate file for colorization */
305 #define FILE_OR_LINK_MODE(File) \
306 ((color_symlink_as_referent & (File)->linkok) \
307 ? (File)->linkmode : (File)->stat.st_mode)
310 /* Record of one pending directory waiting to be listed. */
312 struct pending
314 char *name;
315 /* If the directory is actually the file pointed to by a symbolic link we
316 were told to list, `realname' will contain the name of the symbolic
317 link, otherwise zero. */
318 char *realname;
319 bool command_line_arg;
320 struct pending *next;
323 static struct pending *pending_dirs;
325 /* Current time in seconds and nanoseconds since 1970, updated as
326 needed when deciding whether a file is recent. */
328 static struct timespec current_time;
330 static bool print_scontext;
331 static char UNKNOWN_SECURITY_CONTEXT[] = "?";
333 /* Whether any of the files has an ACL. This affects the width of the
334 mode column. */
336 static bool any_has_acl;
338 /* The number of columns to use for columns containing inode numbers,
339 block sizes, link counts, owners, groups, authors, major device
340 numbers, minor device numbers, and file sizes, respectively. */
342 static int inode_number_width;
343 static int block_size_width;
344 static int nlink_width;
345 static int scontext_width;
346 static int owner_width;
347 static int group_width;
348 static int author_width;
349 static int major_device_number_width;
350 static int minor_device_number_width;
351 static int file_size_width;
353 /* Option flags */
355 /* long_format for lots of info, one per line.
356 one_per_line for just names, one per line.
357 many_per_line for just names, many per line, sorted vertically.
358 horizontal for just names, many per line, sorted horizontally.
359 with_commas for just names, many per line, separated by commas.
361 -l (and other options that imply -l), -1, -C, -x and -m control
362 this parameter. */
364 enum format
366 long_format, /* -l and other options that imply -l */
367 one_per_line, /* -1 */
368 many_per_line, /* -C */
369 horizontal, /* -x */
370 with_commas /* -m */
373 static enum format format;
375 /* `full-iso' uses full ISO-style dates and times. `long-iso' uses longer
376 ISO-style time stamps, though shorter than `full-iso'. `iso' uses shorter
377 ISO-style time stamps. `locale' uses locale-dependent time stamps. */
378 enum time_style
380 full_iso_time_style, /* --time-style=full-iso */
381 long_iso_time_style, /* --time-style=long-iso */
382 iso_time_style, /* --time-style=iso */
383 locale_time_style /* --time-style=locale */
386 static char const *const time_style_args[] =
388 "full-iso", "long-iso", "iso", "locale", NULL
390 static enum time_style const time_style_types[] =
392 full_iso_time_style, long_iso_time_style, iso_time_style,
393 locale_time_style
395 ARGMATCH_VERIFY (time_style_args, time_style_types);
397 /* Type of time to print or sort by. Controlled by -c and -u.
398 The values of each item of this enum are important since they are
399 used as indices in the sort functions array (see sort_files()). */
401 enum time_type
403 time_mtime, /* default */
404 time_ctime, /* -c */
405 time_atime, /* -u */
406 time_numtypes /* the number of elements of this enum */
409 static enum time_type time_type;
411 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
412 The values of each item of this enum are important since they are
413 used as indices in the sort functions array (see sort_files()). */
415 enum sort_type
417 sort_none = -1, /* -U */
418 sort_name, /* default */
419 sort_extension, /* -X */
420 sort_size, /* -S */
421 sort_version, /* -v */
422 sort_time, /* -t */
423 sort_numtypes /* the number of elements of this enum */
426 static enum sort_type sort_type;
428 /* Direction of sort.
429 false means highest first if numeric,
430 lowest first if alphabetic;
431 these are the defaults.
432 true means the opposite order in each case. -r */
434 static bool sort_reverse;
436 /* True means to display owner information. -g turns this off. */
438 static bool print_owner = true;
440 /* True means to display author information. */
442 static bool print_author;
444 /* True means to display group information. -G and -o turn this off. */
446 static bool print_group = true;
448 /* True means print the user and group id's as numbers rather
449 than as names. -n */
451 static bool numeric_ids;
453 /* True means mention the size in blocks of each file. -s */
455 static bool print_block_size;
457 /* Human-readable options for output. */
458 static int human_output_opts;
460 /* The units to use when printing sizes other than file sizes. */
461 static uintmax_t output_block_size;
463 /* Likewise, but for file sizes. */
464 static uintmax_t file_output_block_size = 1;
466 /* Follow the output with a special string. Using this format,
467 Emacs' dired mode starts up twice as fast, and can handle all
468 strange characters in file names. */
469 static bool dired;
471 /* `none' means don't mention the type of files.
472 `slash' means mention directories only, with a '/'.
473 `file_type' means mention file types.
474 `classify' means mention file types and mark executables.
476 Controlled by -F, -p, and --indicator-style. */
478 enum indicator_style
480 none, /* --indicator-style=none */
481 slash, /* -p, --indicator-style=slash */
482 file_type, /* --indicator-style=file-type */
483 classify /* -F, --indicator-style=classify */
486 static enum indicator_style indicator_style;
488 /* Names of indicator styles. */
489 static char const *const indicator_style_args[] =
491 "none", "slash", "file-type", "classify", NULL
493 static enum indicator_style const indicator_style_types[] =
495 none, slash, file_type, classify
497 ARGMATCH_VERIFY (indicator_style_args, indicator_style_types);
499 /* True means use colors to mark types. Also define the different
500 colors as well as the stuff for the LS_COLORS environment variable.
501 The LS_COLORS variable is now in a termcap-like format. */
503 static bool print_with_color;
505 /* Whether we used any colors in the output so far. If so, we will
506 need to restore the default color later. If not, we will need to
507 call prep_non_filename_text before using color for the first time. */
509 static bool used_color = false;
511 enum color_type
513 color_never, /* 0: default or --color=never */
514 color_always, /* 1: --color=always */
515 color_if_tty /* 2: --color=tty */
518 enum Dereference_symlink
520 DEREF_UNDEFINED = 1,
521 DEREF_NEVER,
522 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
523 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
524 DEREF_ALWAYS /* -L */
527 enum indicator_no
529 C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
530 C_FIFO, C_SOCK,
531 C_BLK, C_CHR, C_MISSING, C_ORPHAN, C_EXEC, C_DOOR, C_SETUID, C_SETGID,
532 C_STICKY, C_OTHER_WRITABLE, C_STICKY_OTHER_WRITABLE, C_CAP, C_MULTIHARDLINK,
533 C_CLR_TO_EOL
536 static const char *const indicator_name[]=
538 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
539 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
540 "ow", "tw", "ca", "mh", "cl", NULL
543 struct color_ext_type
545 struct bin_str ext; /* The extension we're looking for */
546 struct bin_str seq; /* The sequence to output when we do */
547 struct color_ext_type *next; /* Next in list */
550 static struct bin_str color_indicator[] =
552 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
553 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
554 { 0, NULL }, /* ec: End color (replaces lc+no+rc) */
555 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
556 { 0, NULL }, /* no: Normal */
557 { 0, NULL }, /* fi: File: default */
558 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
559 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
560 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
561 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
562 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
563 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
564 { 0, NULL }, /* mi: Missing file: undefined */
565 { 0, NULL }, /* or: Orphaned symlink: undefined */
566 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
567 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
568 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
569 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
570 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
571 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
572 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
573 { LEN_STR_PAIR ("30;41") }, /* ca: black on red */
574 { 0, NULL }, /* mh: disabled by default */
575 { LEN_STR_PAIR ("\033[K") }, /* cl: clear to end of line */
578 /* FIXME: comment */
579 static struct color_ext_type *color_ext_list = NULL;
581 /* Buffer for color sequences */
582 static char *color_buf;
584 /* True means to check for orphaned symbolic link, for displaying
585 colors. */
587 static bool check_symlink_color;
589 /* True means mention the inode number of each file. -i */
591 static bool print_inode;
593 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
594 other options that imply -l), and -L. */
596 static enum Dereference_symlink dereference;
598 /* True means when a directory is found, display info on its
599 contents. -R */
601 static bool recursive;
603 /* True means when an argument is a directory name, display info
604 on it itself. -d */
606 static bool immediate_dirs;
608 /* True means that directories are grouped before files. */
610 static bool directories_first;
612 /* Which files to ignore. */
614 static enum
616 /* Ignore files whose names start with `.', and files specified by
617 --hide and --ignore. */
618 IGNORE_DEFAULT,
620 /* Ignore `.', `..', and files specified by --ignore. */
621 IGNORE_DOT_AND_DOTDOT,
623 /* Ignore only files specified by --ignore. */
624 IGNORE_MINIMAL
625 } ignore_mode;
627 /* A linked list of shell-style globbing patterns. If a non-argument
628 file name matches any of these patterns, it is ignored.
629 Controlled by -I. Multiple -I options accumulate.
630 The -B option adds `*~' and `.*~' to this list. */
632 struct ignore_pattern
634 const char *pattern;
635 struct ignore_pattern *next;
638 static struct ignore_pattern *ignore_patterns;
640 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
641 variable itself to be ignored. */
642 static struct ignore_pattern *hide_patterns;
644 /* True means output nongraphic chars in file names as `?'.
645 (-q, --hide-control-chars)
646 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
647 independent. The algorithm is: first, obey the quoting style to get a
648 string representing the file name; then, if qmark_funny_chars is set,
649 replace all nonprintable chars in that string with `?'. It's necessary
650 to replace nonprintable chars even in quoted strings, because we don't
651 want to mess up the terminal if control chars get sent to it, and some
652 quoting methods pass through control chars as-is. */
653 static bool qmark_funny_chars;
655 /* Quoting options for file and dir name output. */
657 static struct quoting_options *filename_quoting_options;
658 static struct quoting_options *dirname_quoting_options;
660 /* The number of chars per hardware tab stop. Setting this to zero
661 inhibits the use of TAB characters for separating columns. -T */
662 static size_t tabsize;
664 /* True means print each directory name before listing it. */
666 static bool print_dir_name;
668 /* The line length to use for breaking lines in many-per-line format.
669 Can be set with -w. */
671 static size_t line_length;
673 /* If true, the file listing format requires that stat be called on
674 each file. */
676 static bool format_needs_stat;
678 /* Similar to `format_needs_stat', but set if only the file type is
679 needed. */
681 static bool format_needs_type;
683 /* An arbitrary limit on the number of bytes in a printed time stamp.
684 This is set to a relatively small value to avoid the need to worry
685 about denial-of-service attacks on servers that run "ls" on behalf
686 of remote clients. 1000 bytes should be enough for any practical
687 time stamp format. */
689 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
691 /* strftime formats for non-recent and recent files, respectively, in
692 -l output. */
694 static char const *long_time_format[2] =
696 /* strftime format for non-recent files (older than 6 months), in
697 -l output. This should contain the year, month and day (at
698 least), in an order that is understood by people in your
699 locale's territory. Please try to keep the number of used
700 screen columns small, because many people work in windows with
701 only 80 columns. But make this as wide as the other string
702 below, for recent files. */
703 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
704 so be wary of using variable width fields from the locale.
705 Note %b is handled specially by ls and aligned correctly.
706 Note also that specifying a width as in %5b is erroneous as strftime
707 will count bytes rather than characters in multibyte locales. */
708 N_("%b %e %Y"),
709 /* strftime format for recent files (younger than 6 months), in -l
710 output. This should contain the month, day and time (at
711 least), in an order that is understood by people in your
712 locale's territory. Please try to keep the number of used
713 screen columns small, because many people work in windows with
714 only 80 columns. But make this as wide as the other string
715 above, for non-recent files. */
716 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
717 so be wary of using variable width fields from the locale.
718 Note %b is handled specially by ls and aligned correctly.
719 Note also that specifying a width as in %5b is erroneous as strftime
720 will count bytes rather than characters in multibyte locales. */
721 N_("%b %e %H:%M")
724 /* The set of signals that are caught. */
726 static sigset_t caught_signals;
728 /* If nonzero, the value of the pending fatal signal. */
730 static sig_atomic_t volatile interrupt_signal;
732 /* A count of the number of pending stop signals that have been received. */
734 static sig_atomic_t volatile stop_signal_count;
736 /* Desired exit status. */
738 static int exit_status;
740 /* Exit statuses. */
741 enum
743 /* "ls" had a minor problem. E.g., while processing a directory,
744 ls obtained the name of an entry via readdir, yet was later
745 unable to stat that name. This happens when listing a directory
746 in which entries are actively being removed or renamed. */
747 LS_MINOR_PROBLEM = 1,
749 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
750 option or failure to stat a command line argument. */
751 LS_FAILURE = 2
754 /* For long options that have no equivalent short option, use a
755 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
756 enum
758 AUTHOR_OPTION = CHAR_MAX + 1,
759 BLOCK_SIZE_OPTION,
760 COLOR_OPTION,
761 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
762 FILE_TYPE_INDICATOR_OPTION,
763 FORMAT_OPTION,
764 FULL_TIME_OPTION,
765 GROUP_DIRECTORIES_FIRST_OPTION,
766 HIDE_OPTION,
767 INDICATOR_STYLE_OPTION,
768 QUOTING_STYLE_OPTION,
769 SHOW_CONTROL_CHARS_OPTION,
770 SI_OPTION,
771 SORT_OPTION,
772 TIME_OPTION,
773 TIME_STYLE_OPTION
776 static struct option const long_options[] =
778 {"all", no_argument, NULL, 'a'},
779 {"escape", no_argument, NULL, 'b'},
780 {"directory", no_argument, NULL, 'd'},
781 {"dired", no_argument, NULL, 'D'},
782 {"full-time", no_argument, NULL, FULL_TIME_OPTION},
783 {"group-directories-first", no_argument, NULL,
784 GROUP_DIRECTORIES_FIRST_OPTION},
785 {"human-readable", no_argument, NULL, 'h'},
786 {"inode", no_argument, NULL, 'i'},
787 {"numeric-uid-gid", no_argument, NULL, 'n'},
788 {"no-group", no_argument, NULL, 'G'},
789 {"hide-control-chars", no_argument, NULL, 'q'},
790 {"reverse", no_argument, NULL, 'r'},
791 {"size", no_argument, NULL, 's'},
792 {"width", required_argument, NULL, 'w'},
793 {"almost-all", no_argument, NULL, 'A'},
794 {"ignore-backups", no_argument, NULL, 'B'},
795 {"classify", no_argument, NULL, 'F'},
796 {"file-type", no_argument, NULL, FILE_TYPE_INDICATOR_OPTION},
797 {"si", no_argument, NULL, SI_OPTION},
798 {"dereference-command-line", no_argument, NULL, 'H'},
799 {"dereference-command-line-symlink-to-dir", no_argument, NULL,
800 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION},
801 {"hide", required_argument, NULL, HIDE_OPTION},
802 {"ignore", required_argument, NULL, 'I'},
803 {"indicator-style", required_argument, NULL, INDICATOR_STYLE_OPTION},
804 {"dereference", no_argument, NULL, 'L'},
805 {"literal", no_argument, NULL, 'N'},
806 {"quote-name", no_argument, NULL, 'Q'},
807 {"quoting-style", required_argument, NULL, QUOTING_STYLE_OPTION},
808 {"recursive", no_argument, NULL, 'R'},
809 {"format", required_argument, NULL, FORMAT_OPTION},
810 {"show-control-chars", no_argument, NULL, SHOW_CONTROL_CHARS_OPTION},
811 {"sort", required_argument, NULL, SORT_OPTION},
812 {"tabsize", required_argument, NULL, 'T'},
813 {"time", required_argument, NULL, TIME_OPTION},
814 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
815 {"color", optional_argument, NULL, COLOR_OPTION},
816 {"block-size", required_argument, NULL, BLOCK_SIZE_OPTION},
817 {"context", no_argument, 0, 'Z'},
818 {"author", no_argument, NULL, AUTHOR_OPTION},
819 {GETOPT_HELP_OPTION_DECL},
820 {GETOPT_VERSION_OPTION_DECL},
821 {NULL, 0, NULL, 0}
824 static char const *const format_args[] =
826 "verbose", "long", "commas", "horizontal", "across",
827 "vertical", "single-column", NULL
829 static enum format const format_types[] =
831 long_format, long_format, with_commas, horizontal, horizontal,
832 many_per_line, one_per_line
834 ARGMATCH_VERIFY (format_args, format_types);
836 static char const *const sort_args[] =
838 "none", "time", "size", "extension", "version", NULL
840 static enum sort_type const sort_types[] =
842 sort_none, sort_time, sort_size, sort_extension, sort_version
844 ARGMATCH_VERIFY (sort_args, sort_types);
846 static char const *const time_args[] =
848 "atime", "access", "use", "ctime", "status", NULL
850 static enum time_type const time_types[] =
852 time_atime, time_atime, time_atime, time_ctime, time_ctime
854 ARGMATCH_VERIFY (time_args, time_types);
856 static char const *const color_args[] =
858 /* force and none are for compatibility with another color-ls version */
859 "always", "yes", "force",
860 "never", "no", "none",
861 "auto", "tty", "if-tty", NULL
863 static enum color_type const color_types[] =
865 color_always, color_always, color_always,
866 color_never, color_never, color_never,
867 color_if_tty, color_if_tty, color_if_tty
869 ARGMATCH_VERIFY (color_args, color_types);
871 /* Information about filling a column. */
872 struct column_info
874 bool valid_len;
875 size_t line_len;
876 size_t *col_arr;
879 /* Array with information about column filledness. */
880 static struct column_info *column_info;
882 /* Maximum number of columns ever possible for this display. */
883 static size_t max_idx;
885 /* The minimum width of a column is 3: 1 character for the name and 2
886 for the separating white space. */
887 #define MIN_COLUMN_WIDTH 3
890 /* This zero-based index is used solely with the --dired option.
891 When that option is in effect, this counter is incremented for each
892 byte of output generated by this program so that the beginning
893 and ending indices (in that output) of every file name can be recorded
894 and later output themselves. */
895 static size_t dired_pos;
897 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
899 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
900 #define DIRED_FPUTS(s, stream, s_len) \
901 do {fputs (s, stream); dired_pos += s_len;} while (0)
903 /* Like DIRED_FPUTS, but for use when S is a literal string. */
904 #define DIRED_FPUTS_LITERAL(s, stream) \
905 do {fputs (s, stream); dired_pos += sizeof (s) - 1;} while (0)
907 #define DIRED_INDENT() \
908 do \
910 if (dired) \
911 DIRED_FPUTS_LITERAL (" ", stdout); \
913 while (0)
915 /* With --dired, store pairs of beginning and ending indices of filenames. */
916 static struct obstack dired_obstack;
918 /* With --dired, store pairs of beginning and ending indices of any
919 directory names that appear as headers (just before `total' line)
920 for lists of directory entries. Such directory names are seen when
921 listing hierarchies using -R and when a directory is listed with at
922 least one other command line argument. */
923 static struct obstack subdired_obstack;
925 /* Save the current index on the specified obstack, OBS. */
926 #define PUSH_CURRENT_DIRED_POS(obs) \
927 do \
929 if (dired) \
930 obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
932 while (0)
934 /* With -R, this stack is used to help detect directory cycles.
935 The device/inode pairs on this stack mirror the pairs in the
936 active_dir_set hash table. */
937 static struct obstack dev_ino_obstack;
939 /* Push a pair onto the device/inode stack. */
940 #define DEV_INO_PUSH(Dev, Ino) \
941 do \
943 struct dev_ino *di; \
944 obstack_blank (&dev_ino_obstack, sizeof (struct dev_ino)); \
945 di = -1 + (struct dev_ino *) obstack_next_free (&dev_ino_obstack); \
946 di->st_dev = (Dev); \
947 di->st_ino = (Ino); \
949 while (0)
951 /* Pop a dev/ino struct off the global dev_ino_obstack
952 and return that struct. */
953 static struct dev_ino
954 dev_ino_pop (void)
956 assert (sizeof (struct dev_ino) <= obstack_object_size (&dev_ino_obstack));
957 obstack_blank (&dev_ino_obstack, -(int) (sizeof (struct dev_ino)));
958 return *(struct dev_ino *) obstack_next_free (&dev_ino_obstack);
961 /* Note the use commented out below:
962 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
963 do \
965 struct stat sb; \
966 assert (Name); \
967 assert (0 <= stat (Name, &sb)); \
968 assert (sb.st_dev == Di.st_dev); \
969 assert (sb.st_ino == Di.st_ino); \
971 while (0)
974 /* Write to standard output PREFIX, followed by the quoting style and
975 a space-separated list of the integers stored in OS all on one line. */
977 static void
978 dired_dump_obstack (const char *prefix, struct obstack *os)
980 size_t n_pos;
982 n_pos = obstack_object_size (os) / sizeof (dired_pos);
983 if (n_pos > 0)
985 size_t i;
986 size_t *pos;
988 pos = (size_t *) obstack_finish (os);
989 fputs (prefix, stdout);
990 for (i = 0; i < n_pos; i++)
991 printf (" %lu", (unsigned long int) pos[i]);
992 putchar ('\n');
996 /* Read the abbreviated month names from the locale, to align them
997 and to determine the max width of the field and to truncate names
998 greater than our max allowed.
999 Note even though this handles multibyte locales correctly
1000 it's not restricted to them as single byte locales can have
1001 variable width abbreviated months and also precomputing/caching
1002 the names was seen to increase the performance of ls significantly. */
1004 /* max number of display cells to use */
1005 enum { MAX_MON_WIDTH = 5 };
1006 /* In the unlikely event that the abmon[] storage is not big enough
1007 an error message will be displayed, and we revert to using
1008 unmodified abbreviated month names from the locale database. */
1009 static char abmon[12][MAX_MON_WIDTH * 2 * MB_LEN_MAX + 1];
1010 /* minimum width needed to align %b, 0 => don't use precomputed values. */
1011 static size_t required_mon_width;
1013 static size_t
1014 abmon_init (void)
1016 #ifdef HAVE_NL_LANGINFO
1017 required_mon_width = MAX_MON_WIDTH;
1018 size_t curr_max_width;
1021 curr_max_width = required_mon_width;
1022 required_mon_width = 0;
1023 for (int i = 0; i < 12; i++)
1025 size_t width = curr_max_width;
1027 size_t req = mbsalign (nl_langinfo (ABMON_1 + i),
1028 abmon[i], sizeof (abmon[i]),
1029 &width, MBS_ALIGN_LEFT, 0);
1031 if (req == (size_t) -1 || req >= sizeof (abmon[i]))
1033 required_mon_width = 0; /* ignore precomputed strings. */
1034 return required_mon_width;
1037 required_mon_width = MAX (required_mon_width, width);
1040 while (curr_max_width > required_mon_width);
1041 #endif
1043 return required_mon_width;
1046 static size_t
1047 dev_ino_hash (void const *x, size_t table_size)
1049 struct dev_ino const *p = x;
1050 return (uintmax_t) p->st_ino % table_size;
1053 static bool
1054 dev_ino_compare (void const *x, void const *y)
1056 struct dev_ino const *a = x;
1057 struct dev_ino const *b = y;
1058 return SAME_INODE (*a, *b) ? true : false;
1061 static void
1062 dev_ino_free (void *x)
1064 free (x);
1067 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1068 active directories. Return true if there is already a matching
1069 entry in the table. */
1071 static bool
1072 visit_dir (dev_t dev, ino_t ino)
1074 struct dev_ino *ent;
1075 struct dev_ino *ent_from_table;
1076 bool found_match;
1078 ent = xmalloc (sizeof *ent);
1079 ent->st_ino = ino;
1080 ent->st_dev = dev;
1082 /* Attempt to insert this entry into the table. */
1083 ent_from_table = hash_insert (active_dir_set, ent);
1085 if (ent_from_table == NULL)
1087 /* Insertion failed due to lack of memory. */
1088 xalloc_die ();
1091 found_match = (ent_from_table != ent);
1093 if (found_match)
1095 /* ent was not inserted, so free it. */
1096 free (ent);
1099 return found_match;
1102 static void
1103 free_pending_ent (struct pending *p)
1105 free (p->name);
1106 free (p->realname);
1107 free (p);
1110 static bool
1111 is_colored (enum indicator_no type)
1113 size_t len = color_indicator[type].len;
1114 char const *s = color_indicator[type].string;
1115 return ! (len == 0
1116 || (len == 1 && strncmp (s, "0", 1) == 0)
1117 || (len == 2 && strncmp (s, "00", 2) == 0));
1120 static void
1121 restore_default_color (void)
1123 put_indicator (&color_indicator[C_LEFT]);
1124 put_indicator (&color_indicator[C_RIGHT]);
1127 /* An ordinary signal was received; arrange for the program to exit. */
1129 static void
1130 sighandler (int sig)
1132 if (! SA_NOCLDSTOP)
1133 signal (sig, SIG_IGN);
1134 if (! interrupt_signal)
1135 interrupt_signal = sig;
1138 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1140 static void
1141 stophandler (int sig)
1143 if (! SA_NOCLDSTOP)
1144 signal (sig, stophandler);
1145 if (! interrupt_signal)
1146 stop_signal_count++;
1149 /* Process any pending signals. If signals are caught, this function
1150 should be called periodically. Ideally there should never be an
1151 unbounded amount of time when signals are not being processed.
1152 Signal handling can restore the default colors, so callers must
1153 immediately change colors after invoking this function. */
1155 static void
1156 process_signals (void)
1158 while (interrupt_signal | stop_signal_count)
1160 int sig;
1161 int stops;
1162 sigset_t oldset;
1164 if (used_color)
1165 restore_default_color ();
1166 fflush (stdout);
1168 sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1170 /* Reload interrupt_signal and stop_signal_count, in case a new
1171 signal was handled before sigprocmask took effect. */
1172 sig = interrupt_signal;
1173 stops = stop_signal_count;
1175 /* SIGTSTP is special, since the application can receive that signal
1176 more than once. In this case, don't set the signal handler to the
1177 default. Instead, just raise the uncatchable SIGSTOP. */
1178 if (stops)
1180 stop_signal_count = stops - 1;
1181 sig = SIGSTOP;
1183 else
1184 signal (sig, SIG_DFL);
1186 /* Exit or suspend the program. */
1187 raise (sig);
1188 sigprocmask (SIG_SETMASK, &oldset, NULL);
1190 /* If execution reaches here, then the program has been
1191 continued (after being suspended). */
1196 main (int argc, char **argv)
1198 int i;
1199 struct pending *thispend;
1200 int n_files;
1202 /* The signals that are trapped, and the number of such signals. */
1203 static int const sig[] =
1205 /* This one is handled specially. */
1206 SIGTSTP,
1208 /* The usual suspects. */
1209 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1210 #ifdef SIGPOLL
1211 SIGPOLL,
1212 #endif
1213 #ifdef SIGPROF
1214 SIGPROF,
1215 #endif
1216 #ifdef SIGVTALRM
1217 SIGVTALRM,
1218 #endif
1219 #ifdef SIGXCPU
1220 SIGXCPU,
1221 #endif
1222 #ifdef SIGXFSZ
1223 SIGXFSZ,
1224 #endif
1226 enum { nsigs = ARRAY_CARDINALITY (sig) };
1228 #if ! SA_NOCLDSTOP
1229 bool caught_sig[nsigs];
1230 #endif
1232 initialize_main (&argc, &argv);
1233 set_program_name (argv[0]);
1234 setlocale (LC_ALL, "");
1235 bindtextdomain (PACKAGE, LOCALEDIR);
1236 textdomain (PACKAGE);
1238 initialize_exit_failure (LS_FAILURE);
1239 atexit (close_stdout);
1241 assert (ARRAY_CARDINALITY (color_indicator) + 1
1242 == ARRAY_CARDINALITY (indicator_name));
1244 exit_status = EXIT_SUCCESS;
1245 print_dir_name = true;
1246 pending_dirs = NULL;
1248 current_time.tv_sec = TYPE_MINIMUM (time_t);
1249 current_time.tv_nsec = -1;
1251 i = decode_switches (argc, argv);
1253 if (print_with_color)
1254 parse_ls_color ();
1256 /* Test print_with_color again, because the call to parse_ls_color
1257 may have just reset it -- e.g., if LS_COLORS is invalid. */
1258 if (print_with_color)
1260 /* Avoid following symbolic links when possible. */
1261 if (is_colored (C_ORPHAN)
1262 || (is_colored (C_EXEC) && color_symlink_as_referent)
1263 || (is_colored (C_MISSING) && format == long_format))
1264 check_symlink_color = true;
1266 /* If the standard output is a controlling terminal, watch out
1267 for signals, so that the colors can be restored to the
1268 default state if "ls" is suspended or interrupted. */
1270 if (0 <= tcgetpgrp (STDOUT_FILENO))
1272 int j;
1273 #if SA_NOCLDSTOP
1274 struct sigaction act;
1276 sigemptyset (&caught_signals);
1277 for (j = 0; j < nsigs; j++)
1279 sigaction (sig[j], NULL, &act);
1280 if (act.sa_handler != SIG_IGN)
1281 sigaddset (&caught_signals, sig[j]);
1284 act.sa_mask = caught_signals;
1285 act.sa_flags = SA_RESTART;
1287 for (j = 0; j < nsigs; j++)
1288 if (sigismember (&caught_signals, sig[j]))
1290 act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler;
1291 sigaction (sig[j], &act, NULL);
1293 #else
1294 for (j = 0; j < nsigs; j++)
1296 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1297 if (caught_sig[j])
1299 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1300 siginterrupt (sig[j], 0);
1303 #endif
1307 if (dereference == DEREF_UNDEFINED)
1308 dereference = ((immediate_dirs
1309 || indicator_style == classify
1310 || format == long_format)
1311 ? DEREF_NEVER
1312 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1314 /* When using -R, initialize a data structure we'll use to
1315 detect any directory cycles. */
1316 if (recursive)
1318 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1319 dev_ino_hash,
1320 dev_ino_compare,
1321 dev_ino_free);
1322 if (active_dir_set == NULL)
1323 xalloc_die ();
1325 obstack_init (&dev_ino_obstack);
1328 format_needs_stat = sort_type == sort_time || sort_type == sort_size
1329 || format == long_format
1330 || print_scontext
1331 || print_block_size;
1332 format_needs_type = (! format_needs_stat
1333 && (recursive
1334 || print_with_color
1335 || indicator_style != none
1336 || directories_first));
1338 if (dired)
1340 obstack_init (&dired_obstack);
1341 obstack_init (&subdired_obstack);
1344 cwd_n_alloc = 100;
1345 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1346 cwd_n_used = 0;
1348 clear_files ();
1350 n_files = argc - i;
1352 if (n_files <= 0)
1354 if (immediate_dirs)
1355 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1356 else
1357 queue_directory (".", NULL, true);
1359 else
1361 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1362 while (i < argc);
1364 if (cwd_n_used)
1366 sort_files ();
1367 if (!immediate_dirs)
1368 extract_dirs_from_files (NULL, true);
1369 /* `cwd_n_used' might be zero now. */
1372 /* In the following if/else blocks, it is sufficient to test `pending_dirs'
1373 (and not pending_dirs->name) because there may be no markers in the queue
1374 at this point. A marker may be enqueued when extract_dirs_from_files is
1375 called with a non-empty string or via print_dir. */
1376 if (cwd_n_used)
1378 print_current_files ();
1379 if (pending_dirs)
1380 DIRED_PUTCHAR ('\n');
1382 else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0)
1383 print_dir_name = false;
1385 while (pending_dirs)
1387 thispend = pending_dirs;
1388 pending_dirs = pending_dirs->next;
1390 if (LOOP_DETECT)
1392 if (thispend->name == NULL)
1394 /* thispend->name == NULL means this is a marker entry
1395 indicating we've finished processing the directory.
1396 Use its dev/ino numbers to remove the corresponding
1397 entry from the active_dir_set hash table. */
1398 struct dev_ino di = dev_ino_pop ();
1399 struct dev_ino *found = hash_delete (active_dir_set, &di);
1400 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1401 assert (found);
1402 dev_ino_free (found);
1403 free_pending_ent (thispend);
1404 continue;
1408 print_dir (thispend->name, thispend->realname,
1409 thispend->command_line_arg);
1411 free_pending_ent (thispend);
1412 print_dir_name = true;
1415 if (print_with_color)
1417 int j;
1419 if (used_color)
1420 restore_default_color ();
1421 fflush (stdout);
1423 /* Restore the default signal handling. */
1424 #if SA_NOCLDSTOP
1425 for (j = 0; j < nsigs; j++)
1426 if (sigismember (&caught_signals, sig[j]))
1427 signal (sig[j], SIG_DFL);
1428 #else
1429 for (j = 0; j < nsigs; j++)
1430 if (caught_sig[j])
1431 signal (sig[j], SIG_DFL);
1432 #endif
1434 /* Act on any signals that arrived before the default was restored.
1435 This can process signals out of order, but there doesn't seem to
1436 be an easy way to do them in order, and the order isn't that
1437 important anyway. */
1438 for (j = stop_signal_count; j; j--)
1439 raise (SIGSTOP);
1440 j = interrupt_signal;
1441 if (j)
1442 raise (j);
1445 if (dired)
1447 /* No need to free these since we're about to exit. */
1448 dired_dump_obstack ("//DIRED//", &dired_obstack);
1449 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack);
1450 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1451 quoting_style_args[get_quoting_style (filename_quoting_options)]);
1454 if (LOOP_DETECT)
1456 assert (hash_get_n_entries (active_dir_set) == 0);
1457 hash_free (active_dir_set);
1460 exit (exit_status);
1463 /* Set all the option flags according to the switches specified.
1464 Return the index of the first non-option argument. */
1466 static int
1467 decode_switches (int argc, char **argv)
1469 char *time_style_option = NULL;
1471 /* Record whether there is an option specifying sort type. */
1472 bool sort_type_specified = false;
1474 qmark_funny_chars = false;
1476 /* initialize all switches to default settings */
1478 switch (ls_mode)
1480 case LS_MULTI_COL:
1481 /* This is for the `dir' program. */
1482 format = many_per_line;
1483 set_quoting_style (NULL, escape_quoting_style);
1484 break;
1486 case LS_LONG_FORMAT:
1487 /* This is for the `vdir' program. */
1488 format = long_format;
1489 set_quoting_style (NULL, escape_quoting_style);
1490 break;
1492 case LS_LS:
1493 /* This is for the `ls' program. */
1494 if (isatty (STDOUT_FILENO))
1496 format = many_per_line;
1497 /* See description of qmark_funny_chars, above. */
1498 qmark_funny_chars = true;
1500 else
1502 format = one_per_line;
1503 qmark_funny_chars = false;
1505 break;
1507 default:
1508 abort ();
1511 time_type = time_mtime;
1512 sort_type = sort_name;
1513 sort_reverse = false;
1514 numeric_ids = false;
1515 print_block_size = false;
1516 indicator_style = none;
1517 print_inode = false;
1518 dereference = DEREF_UNDEFINED;
1519 recursive = false;
1520 immediate_dirs = false;
1521 ignore_mode = IGNORE_DEFAULT;
1522 ignore_patterns = NULL;
1523 hide_patterns = NULL;
1524 print_scontext = false;
1526 /* FIXME: put this in a function. */
1528 char const *q_style = getenv ("QUOTING_STYLE");
1529 if (q_style)
1531 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
1532 if (0 <= i)
1533 set_quoting_style (NULL, quoting_style_vals[i]);
1534 else
1535 error (0, 0,
1536 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
1537 quotearg (q_style));
1542 char const *ls_block_size = getenv ("LS_BLOCK_SIZE");
1543 human_options (ls_block_size,
1544 &human_output_opts, &output_block_size);
1545 if (ls_block_size || getenv ("BLOCK_SIZE"))
1546 file_output_block_size = output_block_size;
1549 line_length = 80;
1551 char const *p = getenv ("COLUMNS");
1552 if (p && *p)
1554 unsigned long int tmp_ulong;
1555 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1556 && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX)
1558 line_length = tmp_ulong;
1560 else
1562 error (0, 0,
1563 _("ignoring invalid width in environment variable COLUMNS: %s"),
1564 quotearg (p));
1569 #ifdef TIOCGWINSZ
1571 struct winsize ws;
1573 if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1
1574 && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col)
1575 line_length = ws.ws_col;
1577 #endif
1580 char const *p = getenv ("TABSIZE");
1581 tabsize = 8;
1582 if (p)
1584 unsigned long int tmp_ulong;
1585 if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
1586 && tmp_ulong <= SIZE_MAX)
1588 tabsize = tmp_ulong;
1590 else
1592 error (0, 0,
1593 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1594 quotearg (p));
1599 for (;;)
1601 int oi = -1;
1602 int c = getopt_long (argc, argv,
1603 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1604 long_options, &oi);
1605 if (c == -1)
1606 break;
1608 switch (c)
1610 case 'a':
1611 ignore_mode = IGNORE_MINIMAL;
1612 break;
1614 case 'b':
1615 set_quoting_style (NULL, escape_quoting_style);
1616 break;
1618 case 'c':
1619 time_type = time_ctime;
1620 break;
1622 case 'd':
1623 immediate_dirs = true;
1624 break;
1626 case 'f':
1627 /* Same as enabling -a -U and disabling -l -s. */
1628 ignore_mode = IGNORE_MINIMAL;
1629 sort_type = sort_none;
1630 sort_type_specified = true;
1631 /* disable -l */
1632 if (format == long_format)
1633 format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line);
1634 print_block_size = false; /* disable -s */
1635 print_with_color = false; /* disable --color */
1636 break;
1638 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1639 indicator_style = file_type;
1640 break;
1642 case 'g':
1643 format = long_format;
1644 print_owner = false;
1645 break;
1647 case 'h':
1648 human_output_opts = human_autoscale | human_SI | human_base_1024;
1649 file_output_block_size = output_block_size = 1;
1650 break;
1652 case 'i':
1653 print_inode = true;
1654 break;
1656 case 'k':
1657 human_output_opts = 0;
1658 file_output_block_size = output_block_size = 1024;
1659 break;
1661 case 'l':
1662 format = long_format;
1663 break;
1665 case 'm':
1666 format = with_commas;
1667 break;
1669 case 'n':
1670 numeric_ids = true;
1671 format = long_format;
1672 break;
1674 case 'o': /* Just like -l, but don't display group info. */
1675 format = long_format;
1676 print_group = false;
1677 break;
1679 case 'p':
1680 indicator_style = slash;
1681 break;
1683 case 'q':
1684 qmark_funny_chars = true;
1685 break;
1687 case 'r':
1688 sort_reverse = true;
1689 break;
1691 case 's':
1692 print_block_size = true;
1693 break;
1695 case 't':
1696 sort_type = sort_time;
1697 sort_type_specified = true;
1698 break;
1700 case 'u':
1701 time_type = time_atime;
1702 break;
1704 case 'v':
1705 sort_type = sort_version;
1706 sort_type_specified = true;
1707 break;
1709 case 'w':
1711 unsigned long int tmp_ulong;
1712 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1713 || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX))
1714 error (LS_FAILURE, 0, _("invalid line width: %s"),
1715 quotearg (optarg));
1716 line_length = tmp_ulong;
1717 break;
1720 case 'x':
1721 format = horizontal;
1722 break;
1724 case 'A':
1725 if (ignore_mode == IGNORE_DEFAULT)
1726 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1727 break;
1729 case 'B':
1730 add_ignore_pattern ("*~");
1731 add_ignore_pattern (".*~");
1732 break;
1734 case 'C':
1735 format = many_per_line;
1736 break;
1738 case 'D':
1739 dired = true;
1740 break;
1742 case 'F':
1743 indicator_style = classify;
1744 break;
1746 case 'G': /* inhibit display of group info */
1747 print_group = false;
1748 break;
1750 case 'H':
1751 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1752 break;
1754 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1755 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1756 break;
1758 case 'I':
1759 add_ignore_pattern (optarg);
1760 break;
1762 case 'L':
1763 dereference = DEREF_ALWAYS;
1764 break;
1766 case 'N':
1767 set_quoting_style (NULL, literal_quoting_style);
1768 break;
1770 case 'Q':
1771 set_quoting_style (NULL, c_quoting_style);
1772 break;
1774 case 'R':
1775 recursive = true;
1776 break;
1778 case 'S':
1779 sort_type = sort_size;
1780 sort_type_specified = true;
1781 break;
1783 case 'T':
1785 unsigned long int tmp_ulong;
1786 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK
1787 || SIZE_MAX < tmp_ulong)
1788 error (LS_FAILURE, 0, _("invalid tab size: %s"),
1789 quotearg (optarg));
1790 tabsize = tmp_ulong;
1791 break;
1794 case 'U':
1795 sort_type = sort_none;
1796 sort_type_specified = true;
1797 break;
1799 case 'X':
1800 sort_type = sort_extension;
1801 sort_type_specified = true;
1802 break;
1804 case '1':
1805 /* -1 has no effect after -l. */
1806 if (format != long_format)
1807 format = one_per_line;
1808 break;
1810 case AUTHOR_OPTION:
1811 print_author = true;
1812 break;
1814 case HIDE_OPTION:
1816 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1817 hide->pattern = optarg;
1818 hide->next = hide_patterns;
1819 hide_patterns = hide;
1821 break;
1823 case SORT_OPTION:
1824 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1825 sort_type_specified = true;
1826 break;
1828 case GROUP_DIRECTORIES_FIRST_OPTION:
1829 directories_first = true;
1830 break;
1832 case TIME_OPTION:
1833 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
1834 break;
1836 case FORMAT_OPTION:
1837 format = XARGMATCH ("--format", optarg, format_args, format_types);
1838 break;
1840 case FULL_TIME_OPTION:
1841 format = long_format;
1842 time_style_option = bad_cast ("full-iso");
1843 break;
1845 case COLOR_OPTION:
1847 int i;
1848 if (optarg)
1849 i = XARGMATCH ("--color", optarg, color_args, color_types);
1850 else
1851 /* Using --color with no argument is equivalent to using
1852 --color=always. */
1853 i = color_always;
1855 print_with_color = (i == color_always
1856 || (i == color_if_tty
1857 && isatty (STDOUT_FILENO)));
1859 if (print_with_color)
1861 /* Don't use TAB characters in output. Some terminal
1862 emulators can't handle the combination of tabs and
1863 color codes on the same line. */
1864 tabsize = 0;
1866 break;
1869 case INDICATOR_STYLE_OPTION:
1870 indicator_style = XARGMATCH ("--indicator-style", optarg,
1871 indicator_style_args,
1872 indicator_style_types);
1873 break;
1875 case QUOTING_STYLE_OPTION:
1876 set_quoting_style (NULL,
1877 XARGMATCH ("--quoting-style", optarg,
1878 quoting_style_args,
1879 quoting_style_vals));
1880 break;
1882 case TIME_STYLE_OPTION:
1883 time_style_option = optarg;
1884 break;
1886 case SHOW_CONTROL_CHARS_OPTION:
1887 qmark_funny_chars = false;
1888 break;
1890 case BLOCK_SIZE_OPTION:
1892 enum strtol_error e = human_options (optarg, &human_output_opts,
1893 &output_block_size);
1894 if (e != LONGINT_OK)
1895 xstrtol_fatal (e, oi, 0, long_options, optarg);
1896 file_output_block_size = output_block_size;
1898 break;
1900 case SI_OPTION:
1901 human_output_opts = human_autoscale | human_SI;
1902 file_output_block_size = output_block_size = 1;
1903 break;
1905 case 'Z':
1906 print_scontext = true;
1907 break;
1909 case_GETOPT_HELP_CHAR;
1911 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1913 default:
1914 usage (LS_FAILURE);
1918 max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH);
1920 filename_quoting_options = clone_quoting_options (NULL);
1921 if (get_quoting_style (filename_quoting_options) == escape_quoting_style)
1922 set_char_quoting (filename_quoting_options, ' ', 1);
1923 if (file_type <= indicator_style)
1925 char const *p;
1926 for (p = "*=>@|" + indicator_style - file_type; *p; p++)
1927 set_char_quoting (filename_quoting_options, *p, 1);
1930 dirname_quoting_options = clone_quoting_options (NULL);
1931 set_char_quoting (dirname_quoting_options, ':', 1);
1933 /* --dired is meaningful only with --format=long (-l).
1934 Otherwise, ignore it. FIXME: warn about this?
1935 Alternatively, make --dired imply --format=long? */
1936 if (dired && format != long_format)
1937 dired = false;
1939 /* If -c or -u is specified and not -l (or any other option that implies -l),
1940 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
1941 The behavior of ls when using either -c or -u but with neither -l nor -t
1942 appears to be unspecified by POSIX. So, with GNU ls, `-u' alone means
1943 sort by atime (this is the one that's not specified by the POSIX spec),
1944 -lu means show atime and sort by name, -lut means show atime and sort
1945 by atime. */
1947 if ((time_type == time_ctime || time_type == time_atime)
1948 && !sort_type_specified && format != long_format)
1950 sort_type = sort_time;
1953 if (format == long_format)
1955 char *style = time_style_option;
1956 static char const posix_prefix[] = "posix-";
1958 if (! style)
1959 if (! (style = getenv ("TIME_STYLE")))
1960 style = bad_cast ("locale");
1962 while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0)
1964 if (! hard_locale (LC_TIME))
1965 return optind;
1966 style += sizeof posix_prefix - 1;
1969 if (*style == '+')
1971 char *p0 = style + 1;
1972 char *p1 = strchr (p0, '\n');
1973 if (! p1)
1974 p1 = p0;
1975 else
1977 if (strchr (p1 + 1, '\n'))
1978 error (LS_FAILURE, 0, _("invalid time style format %s"),
1979 quote (p0));
1980 *p1++ = '\0';
1982 long_time_format[0] = p0;
1983 long_time_format[1] = p1;
1985 else
1986 switch (XARGMATCH ("time style", style,
1987 time_style_args,
1988 time_style_types))
1990 case full_iso_time_style:
1991 long_time_format[0] = long_time_format[1] =
1992 "%Y-%m-%d %H:%M:%S.%N %z";
1993 break;
1995 case long_iso_time_style:
1996 case_long_iso_time_style:
1997 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
1998 break;
2000 case iso_time_style:
2001 long_time_format[0] = "%Y-%m-%d ";
2002 long_time_format[1] = "%m-%d %H:%M";
2003 break;
2005 case locale_time_style:
2006 if (hard_locale (LC_TIME))
2008 /* Ensure that the locale has translations for both
2009 formats. If not, fall back on long-iso format. */
2010 int i;
2011 for (i = 0; i < 2; i++)
2013 char const *locale_format =
2014 dcgettext (NULL, long_time_format[i], LC_TIME);
2015 if (locale_format == long_time_format[i])
2016 goto case_long_iso_time_style;
2017 long_time_format[i] = locale_format;
2021 /* Note we leave %5b etc. alone so user widths/flags are honored. */
2022 if (strstr (long_time_format[0],"%b") || strstr (long_time_format[1],"%b"))
2023 if (!abmon_init ())
2024 error (0, 0, _("error initializing month strings"));
2027 return optind;
2030 /* Parse a string as part of the LS_COLORS variable; this may involve
2031 decoding all kinds of escape characters. If equals_end is set an
2032 unescaped equal sign ends the string, otherwise only a : or \0
2033 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2034 true if successful.
2036 The resulting string is *not* null-terminated, but may contain
2037 embedded nulls.
2039 Note that both dest and src are char **; on return they point to
2040 the first free byte after the array and the character that ended
2041 the input string, respectively. */
2043 static bool
2044 get_funky_string (char **dest, const char **src, bool equals_end,
2045 size_t *output_count)
2047 char num; /* For numerical codes */
2048 size_t count; /* Something to count with */
2049 enum {
2050 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
2051 } state;
2052 const char *p;
2053 char *q;
2055 p = *src; /* We don't want to double-indirect */
2056 q = *dest; /* the whole darn time. */
2058 count = 0; /* No characters counted in yet. */
2059 num = 0;
2061 state = ST_GND; /* Start in ground state. */
2062 while (state < ST_END)
2064 switch (state)
2066 case ST_GND: /* Ground state (no escapes) */
2067 switch (*p)
2069 case ':':
2070 case '\0':
2071 state = ST_END; /* End of string */
2072 break;
2073 case '\\':
2074 state = ST_BACKSLASH; /* Backslash scape sequence */
2075 ++p;
2076 break;
2077 case '^':
2078 state = ST_CARET; /* Caret escape */
2079 ++p;
2080 break;
2081 case '=':
2082 if (equals_end)
2084 state = ST_END; /* End */
2085 break;
2087 /* else fall through */
2088 default:
2089 *(q++) = *(p++);
2090 ++count;
2091 break;
2093 break;
2095 case ST_BACKSLASH: /* Backslash escaped character */
2096 switch (*p)
2098 case '0':
2099 case '1':
2100 case '2':
2101 case '3':
2102 case '4':
2103 case '5':
2104 case '6':
2105 case '7':
2106 state = ST_OCTAL; /* Octal sequence */
2107 num = *p - '0';
2108 break;
2109 case 'x':
2110 case 'X':
2111 state = ST_HEX; /* Hex sequence */
2112 num = 0;
2113 break;
2114 case 'a': /* Bell */
2115 num = '\a';
2116 break;
2117 case 'b': /* Backspace */
2118 num = '\b';
2119 break;
2120 case 'e': /* Escape */
2121 num = 27;
2122 break;
2123 case 'f': /* Form feed */
2124 num = '\f';
2125 break;
2126 case 'n': /* Newline */
2127 num = '\n';
2128 break;
2129 case 'r': /* Carriage return */
2130 num = '\r';
2131 break;
2132 case 't': /* Tab */
2133 num = '\t';
2134 break;
2135 case 'v': /* Vtab */
2136 num = '\v';
2137 break;
2138 case '?': /* Delete */
2139 num = 127;
2140 break;
2141 case '_': /* Space */
2142 num = ' ';
2143 break;
2144 case '\0': /* End of string */
2145 state = ST_ERROR; /* Error! */
2146 break;
2147 default: /* Escaped character like \ ^ : = */
2148 num = *p;
2149 break;
2151 if (state == ST_BACKSLASH)
2153 *(q++) = num;
2154 ++count;
2155 state = ST_GND;
2157 ++p;
2158 break;
2160 case ST_OCTAL: /* Octal sequence */
2161 if (*p < '0' || *p > '7')
2163 *(q++) = num;
2164 ++count;
2165 state = ST_GND;
2167 else
2168 num = (num << 3) + (*(p++) - '0');
2169 break;
2171 case ST_HEX: /* Hex sequence */
2172 switch (*p)
2174 case '0':
2175 case '1':
2176 case '2':
2177 case '3':
2178 case '4':
2179 case '5':
2180 case '6':
2181 case '7':
2182 case '8':
2183 case '9':
2184 num = (num << 4) + (*(p++) - '0');
2185 break;
2186 case 'a':
2187 case 'b':
2188 case 'c':
2189 case 'd':
2190 case 'e':
2191 case 'f':
2192 num = (num << 4) + (*(p++) - 'a') + 10;
2193 break;
2194 case 'A':
2195 case 'B':
2196 case 'C':
2197 case 'D':
2198 case 'E':
2199 case 'F':
2200 num = (num << 4) + (*(p++) - 'A') + 10;
2201 break;
2202 default:
2203 *(q++) = num;
2204 ++count;
2205 state = ST_GND;
2206 break;
2208 break;
2210 case ST_CARET: /* Caret escape */
2211 state = ST_GND; /* Should be the next state... */
2212 if (*p >= '@' && *p <= '~')
2214 *(q++) = *(p++) & 037;
2215 ++count;
2217 else if (*p == '?')
2219 *(q++) = 127;
2220 ++count;
2222 else
2223 state = ST_ERROR;
2224 break;
2226 default:
2227 abort ();
2231 *dest = q;
2232 *src = p;
2233 *output_count = count;
2235 return state != ST_ERROR;
2238 static void
2239 parse_ls_color (void)
2241 const char *p; /* Pointer to character being parsed */
2242 char *buf; /* color_buf buffer pointer */
2243 int state; /* State of parser */
2244 int ind_no; /* Indicator number */
2245 char label[3]; /* Indicator label */
2246 struct color_ext_type *ext; /* Extension we are working on */
2248 if ((p = getenv ("LS_COLORS")) == NULL || *p == '\0')
2249 return;
2251 ext = NULL;
2252 strcpy (label, "??");
2254 /* This is an overly conservative estimate, but any possible
2255 LS_COLORS string will *not* generate a color_buf longer than
2256 itself, so it is a safe way of allocating a buffer in
2257 advance. */
2258 buf = color_buf = xstrdup (p);
2260 state = 1;
2261 while (state > 0)
2263 switch (state)
2265 case 1: /* First label character */
2266 switch (*p)
2268 case ':':
2269 ++p;
2270 break;
2272 case '*':
2273 /* Allocate new extension block and add to head of
2274 linked list (this way a later definition will
2275 override an earlier one, which can be useful for
2276 having terminal-specific defs override global). */
2278 ext = xmalloc (sizeof *ext);
2279 ext->next = color_ext_list;
2280 color_ext_list = ext;
2282 ++p;
2283 ext->ext.string = buf;
2285 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2286 ? 4 : -1);
2287 break;
2289 case '\0':
2290 state = 0; /* Done! */
2291 break;
2293 default: /* Assume it is file type label */
2294 label[0] = *(p++);
2295 state = 2;
2296 break;
2298 break;
2300 case 2: /* Second label character */
2301 if (*p)
2303 label[1] = *(p++);
2304 state = 3;
2306 else
2307 state = -1; /* Error */
2308 break;
2310 case 3: /* Equal sign after indicator label */
2311 state = -1; /* Assume failure... */
2312 if (*(p++) == '=')/* It *should* be... */
2314 for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no)
2316 if (STREQ (label, indicator_name[ind_no]))
2318 color_indicator[ind_no].string = buf;
2319 state = (get_funky_string (&buf, &p, false,
2320 &color_indicator[ind_no].len)
2321 ? 1 : -1);
2322 break;
2325 if (state == -1)
2326 error (0, 0, _("unrecognized prefix: %s"), quotearg (label));
2328 break;
2330 case 4: /* Equal sign after *.ext */
2331 if (*(p++) == '=')
2333 ext->seq.string = buf;
2334 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2335 ? 1 : -1);
2337 else
2338 state = -1;
2339 break;
2343 if (state < 0)
2345 struct color_ext_type *e;
2346 struct color_ext_type *e2;
2348 error (0, 0,
2349 _("unparsable value for LS_COLORS environment variable"));
2350 free (color_buf);
2351 for (e = color_ext_list; e != NULL; /* empty */)
2353 e2 = e;
2354 e = e->next;
2355 free (e2);
2357 print_with_color = false;
2360 if (color_indicator[C_LINK].len == 6
2361 && !strncmp (color_indicator[C_LINK].string, "target", 6))
2362 color_symlink_as_referent = true;
2365 /* Set the exit status to report a failure. If SERIOUS, it is a
2366 serious failure; otherwise, it is merely a minor problem. */
2368 static void
2369 set_exit_status (bool serious)
2371 if (serious)
2372 exit_status = LS_FAILURE;
2373 else if (exit_status == EXIT_SUCCESS)
2374 exit_status = LS_MINOR_PROBLEM;
2377 /* Assuming a failure is serious if SERIOUS, use the printf-style
2378 MESSAGE to report the failure to access a file named FILE. Assume
2379 errno is set appropriately for the failure. */
2381 static void
2382 file_failure (bool serious, char const *message, char const *file)
2384 error (0, errno, message, quotearg_colon (file));
2385 set_exit_status (serious);
2388 /* Request that the directory named NAME have its contents listed later.
2389 If REALNAME is nonzero, it will be used instead of NAME when the
2390 directory name is printed. This allows symbolic links to directories
2391 to be treated as regular directories but still be listed under their
2392 real names. NAME == NULL is used to insert a marker entry for the
2393 directory named in REALNAME.
2394 If NAME is non-NULL, we use its dev/ino information to save
2395 a call to stat -- when doing a recursive (-R) traversal.
2396 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2398 static void
2399 queue_directory (char const *name, char const *realname, bool command_line_arg)
2401 struct pending *new = xmalloc (sizeof *new);
2402 new->realname = realname ? xstrdup (realname) : NULL;
2403 new->name = name ? xstrdup (name) : NULL;
2404 new->command_line_arg = command_line_arg;
2405 new->next = pending_dirs;
2406 pending_dirs = new;
2409 /* Read directory NAME, and list the files in it.
2410 If REALNAME is nonzero, print its name instead of NAME;
2411 this is used for symbolic links to directories.
2412 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2414 static void
2415 print_dir (char const *name, char const *realname, bool command_line_arg)
2417 DIR *dirp;
2418 struct dirent *next;
2419 uintmax_t total_blocks = 0;
2420 static bool first = true;
2422 errno = 0;
2423 dirp = opendir (name);
2424 if (!dirp)
2426 file_failure (command_line_arg, _("cannot open directory %s"), name);
2427 return;
2430 if (LOOP_DETECT)
2432 struct stat dir_stat;
2433 int fd = dirfd (dirp);
2435 /* If dirfd failed, endure the overhead of using stat. */
2436 if ((0 <= fd
2437 ? fstat (fd, &dir_stat)
2438 : stat (name, &dir_stat)) < 0)
2440 file_failure (command_line_arg,
2441 _("cannot determine device and inode of %s"), name);
2442 closedir (dirp);
2443 return;
2446 /* If we've already visited this dev/inode pair, warn that
2447 we've found a loop, and do not process this directory. */
2448 if (visit_dir (dir_stat.st_dev, dir_stat.st_ino))
2450 error (0, 0, _("%s: not listing already-listed directory"),
2451 quotearg_colon (name));
2452 closedir (dirp);
2453 return;
2456 DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino);
2459 if (recursive | print_dir_name)
2461 if (!first)
2462 DIRED_PUTCHAR ('\n');
2463 first = false;
2464 DIRED_INDENT ();
2465 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2466 dired_pos += quote_name (stdout, realname ? realname : name,
2467 dirname_quoting_options, NULL);
2468 PUSH_CURRENT_DIRED_POS (&subdired_obstack);
2469 DIRED_FPUTS_LITERAL (":\n", stdout);
2472 /* Read the directory entries, and insert the subfiles into the `cwd_file'
2473 table. */
2475 clear_files ();
2477 while (1)
2479 /* Set errno to zero so we can distinguish between a readdir failure
2480 and when readdir simply finds that there are no more entries. */
2481 errno = 0;
2482 next = readdir (dirp);
2483 if (next)
2485 if (! file_ignored (next->d_name))
2487 enum filetype type = unknown;
2489 #if HAVE_STRUCT_DIRENT_D_TYPE
2490 switch (next->d_type)
2492 case DT_BLK: type = blockdev; break;
2493 case DT_CHR: type = chardev; break;
2494 case DT_DIR: type = directory; break;
2495 case DT_FIFO: type = fifo; break;
2496 case DT_LNK: type = symbolic_link; break;
2497 case DT_REG: type = normal; break;
2498 case DT_SOCK: type = sock; break;
2499 # ifdef DT_WHT
2500 case DT_WHT: type = whiteout; break;
2501 # endif
2503 #endif
2504 total_blocks += gobble_file (next->d_name, type, D_INO (next),
2505 false, name);
2507 /* In this narrow case, print out each name right away, so
2508 ls uses constant memory while processing the entries of
2509 this directory. Useful when there are many (millions)
2510 of entries in a directory. */
2511 if (format == one_per_line && sort_type == sort_none
2512 && !print_block_size && !recursive)
2514 /* We must call sort_files in spite of
2515 "sort_type == sort_none" for its initialization
2516 of the sorted_file vector. */
2517 sort_files ();
2518 print_current_files ();
2519 clear_files ();
2523 else if (errno != 0)
2525 file_failure (command_line_arg, _("reading directory %s"), name);
2526 if (errno != EOVERFLOW)
2527 break;
2529 else
2530 break;
2533 if (closedir (dirp) != 0)
2535 file_failure (command_line_arg, _("closing directory %s"), name);
2536 /* Don't return; print whatever we got. */
2539 /* Sort the directory contents. */
2540 sort_files ();
2542 /* If any member files are subdirectories, perhaps they should have their
2543 contents listed rather than being mentioned here as files. */
2545 if (recursive)
2546 extract_dirs_from_files (name, command_line_arg);
2548 if (format == long_format || print_block_size)
2550 const char *p;
2551 char buf[LONGEST_HUMAN_READABLE + 1];
2553 DIRED_INDENT ();
2554 p = _("total");
2555 DIRED_FPUTS (p, stdout, strlen (p));
2556 DIRED_PUTCHAR (' ');
2557 p = human_readable (total_blocks, buf, human_output_opts,
2558 ST_NBLOCKSIZE, output_block_size);
2559 DIRED_FPUTS (p, stdout, strlen (p));
2560 DIRED_PUTCHAR ('\n');
2563 if (cwd_n_used)
2564 print_current_files ();
2567 /* Add `pattern' to the list of patterns for which files that match are
2568 not listed. */
2570 static void
2571 add_ignore_pattern (const char *pattern)
2573 struct ignore_pattern *ignore;
2575 ignore = xmalloc (sizeof *ignore);
2576 ignore->pattern = pattern;
2577 /* Add it to the head of the linked list. */
2578 ignore->next = ignore_patterns;
2579 ignore_patterns = ignore;
2582 /* Return true if one of the PATTERNS matches FILE. */
2584 static bool
2585 patterns_match (struct ignore_pattern const *patterns, char const *file)
2587 struct ignore_pattern const *p;
2588 for (p = patterns; p; p = p->next)
2589 if (fnmatch (p->pattern, file, FNM_PERIOD) == 0)
2590 return true;
2591 return false;
2594 /* Return true if FILE should be ignored. */
2596 static bool
2597 file_ignored (char const *name)
2599 return ((ignore_mode != IGNORE_MINIMAL
2600 && name[0] == '.'
2601 && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')]))
2602 || (ignore_mode == IGNORE_DEFAULT
2603 && patterns_match (hide_patterns, name))
2604 || patterns_match (ignore_patterns, name));
2607 /* POSIX requires that a file size be printed without a sign, even
2608 when negative. Assume the typical case where negative sizes are
2609 actually positive values that have wrapped around. */
2611 static uintmax_t
2612 unsigned_file_size (off_t size)
2614 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2617 /* Enter and remove entries in the table `cwd_file'. */
2619 /* Empty the table of files. */
2621 static void
2622 clear_files (void)
2624 size_t i;
2626 for (i = 0; i < cwd_n_used; i++)
2628 struct fileinfo *f = sorted_file[i];
2629 free (f->name);
2630 free (f->linkname);
2631 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
2632 freecon (f->scontext);
2635 cwd_n_used = 0;
2636 any_has_acl = false;
2637 inode_number_width = 0;
2638 block_size_width = 0;
2639 nlink_width = 0;
2640 owner_width = 0;
2641 group_width = 0;
2642 author_width = 0;
2643 scontext_width = 0;
2644 major_device_number_width = 0;
2645 minor_device_number_width = 0;
2646 file_size_width = 0;
2649 /* Add a file to the current table of files.
2650 Verify that the file exists, and print an error message if it does not.
2651 Return the number of blocks that the file occupies. */
2653 static uintmax_t
2654 gobble_file (char const *name, enum filetype type, ino_t inode,
2655 bool command_line_arg, char const *dirname)
2657 uintmax_t blocks = 0;
2658 struct fileinfo *f;
2660 /* An inode value prior to gobble_file necessarily came from readdir,
2661 which is not used for command line arguments. */
2662 assert (! command_line_arg || inode == NOT_AN_INODE_NUMBER);
2664 if (cwd_n_used == cwd_n_alloc)
2666 cwd_file = xnrealloc (cwd_file, cwd_n_alloc, 2 * sizeof *cwd_file);
2667 cwd_n_alloc *= 2;
2670 f = &cwd_file[cwd_n_used];
2671 memset (f, '\0', sizeof *f);
2672 f->stat.st_ino = inode;
2673 f->filetype = type;
2675 if (command_line_arg
2676 || format_needs_stat
2677 /* When coloring a directory (we may know the type from
2678 direct.d_type), we have to stat it in order to indicate
2679 sticky and/or other-writable attributes. */
2680 || (type == directory && print_with_color)
2681 /* When dereferencing symlinks, the inode and type must come from
2682 stat, but readdir provides the inode and type of lstat. */
2683 || ((print_inode || format_needs_type)
2684 && (type == symbolic_link || type == unknown)
2685 && (dereference == DEREF_ALWAYS
2686 || (command_line_arg && dereference != DEREF_NEVER)
2687 || color_symlink_as_referent || check_symlink_color))
2688 /* Command line dereferences are already taken care of by the above
2689 assertion that the inode number is not yet known. */
2690 || (print_inode && inode == NOT_AN_INODE_NUMBER)
2691 || (format_needs_type
2692 && (type == unknown || command_line_arg
2693 /* --indicator-style=classify (aka -F)
2694 requires that we stat each regular file
2695 to see if it's executable. */
2696 || (type == normal && (indicator_style == classify
2697 /* This is so that --color ends up
2698 highlighting files with the executable
2699 bit set even when options like -F are
2700 not specified. */
2701 || (print_with_color
2702 && is_colored (C_EXEC))
2703 )))))
2706 /* Absolute name of this file. */
2707 char *absolute_name;
2708 bool do_deref;
2709 int err;
2711 if (name[0] == '/' || dirname[0] == 0)
2712 absolute_name = (char *) name;
2713 else
2715 absolute_name = alloca (strlen (name) + strlen (dirname) + 2);
2716 attach (absolute_name, dirname, name);
2719 switch (dereference)
2721 case DEREF_ALWAYS:
2722 err = stat (absolute_name, &f->stat);
2723 do_deref = true;
2724 break;
2726 case DEREF_COMMAND_LINE_ARGUMENTS:
2727 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
2728 if (command_line_arg)
2730 bool need_lstat;
2731 err = stat (absolute_name, &f->stat);
2732 do_deref = true;
2734 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
2735 break;
2737 need_lstat = (err < 0
2738 ? errno == ENOENT
2739 : ! S_ISDIR (f->stat.st_mode));
2740 if (!need_lstat)
2741 break;
2743 /* stat failed because of ENOENT, maybe indicating a dangling
2744 symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a
2745 directory, and --dereference-command-line-symlink-to-dir is
2746 in effect. Fall through so that we call lstat instead. */
2749 default: /* DEREF_NEVER */
2750 err = lstat (absolute_name, &f->stat);
2751 do_deref = false;
2752 break;
2755 if (err != 0)
2757 /* Failure to stat a command line argument leads to
2758 an exit status of 2. For other files, stat failure
2759 provokes an exit status of 1. */
2760 file_failure (command_line_arg,
2761 _("cannot access %s"), absolute_name);
2762 if (command_line_arg)
2763 return 0;
2765 f->name = xstrdup (name);
2766 cwd_n_used++;
2768 return 0;
2771 f->stat_ok = true;
2773 if (format == long_format || print_scontext)
2775 bool have_selinux = false;
2776 bool have_acl = false;
2777 int attr_len = (do_deref
2778 ? getfilecon (absolute_name, &f->scontext)
2779 : lgetfilecon (absolute_name, &f->scontext));
2780 err = (attr_len < 0);
2782 /* Contrary to its documented API, getfilecon may return 0,
2783 yet set f->scontext to NULL (on at least Debian's libselinux1
2784 2.0.15-2+b1), so work around that bug.
2785 FIXME: remove this work-around in 2011, or whenever affected
2786 versions of libselinux are long gone. */
2787 if (attr_len == 0)
2789 err = 0;
2790 f->scontext = xstrdup ("unlabeled");
2793 if (err == 0)
2794 have_selinux = ! STREQ ("unlabeled", f->scontext);
2795 else
2797 f->scontext = UNKNOWN_SECURITY_CONTEXT;
2799 /* When requesting security context information, don't make
2800 ls fail just because the file (even a command line argument)
2801 isn't on the right type of file system. I.e., a getfilecon
2802 failure isn't in the same class as a stat failure. */
2803 if (errno == ENOTSUP || errno == EOPNOTSUPP || errno == ENODATA)
2804 err = 0;
2807 if (err == 0 && format == long_format)
2809 int n = file_has_acl (absolute_name, &f->stat);
2810 err = (n < 0);
2811 have_acl = (0 < n);
2814 f->acl_type = (!have_selinux && !have_acl
2815 ? ACL_T_NONE
2816 : (have_selinux && !have_acl
2817 ? ACL_T_SELINUX_ONLY
2818 : ACL_T_YES));
2819 any_has_acl |= f->acl_type != ACL_T_NONE;
2821 if (err)
2822 error (0, errno, "%s", quotearg_colon (absolute_name));
2825 if (S_ISLNK (f->stat.st_mode)
2826 && (format == long_format || check_symlink_color))
2828 char *linkname;
2829 struct stat linkstats;
2831 get_link_name (absolute_name, f, command_line_arg);
2832 linkname = make_link_name (absolute_name, f->linkname);
2834 /* Avoid following symbolic links when possible, ie, when
2835 they won't be traced and when no indicator is needed. */
2836 if (linkname
2837 && (file_type <= indicator_style || check_symlink_color)
2838 && stat (linkname, &linkstats) == 0)
2840 f->linkok = true;
2842 /* Symbolic links to directories that are mentioned on the
2843 command line are automatically traced if not being
2844 listed as files. */
2845 if (!command_line_arg || format == long_format
2846 || !S_ISDIR (linkstats.st_mode))
2848 /* Get the linked-to file's mode for the filetype indicator
2849 in long listings. */
2850 f->linkmode = linkstats.st_mode;
2853 free (linkname);
2856 /* When not distinguishing types of symlinks, pretend we know that
2857 it is stat'able, so that it will be colored as a regular symlink,
2858 and not as an orphan. */
2859 if (S_ISLNK (f->stat.st_mode) && !check_symlink_color)
2860 f->linkok = true;
2862 if (S_ISLNK (f->stat.st_mode))
2863 f->filetype = symbolic_link;
2864 else if (S_ISDIR (f->stat.st_mode))
2866 if (command_line_arg & !immediate_dirs)
2867 f->filetype = arg_directory;
2868 else
2869 f->filetype = directory;
2871 else
2872 f->filetype = normal;
2874 blocks = ST_NBLOCKS (f->stat);
2875 if (format == long_format || print_block_size)
2877 char buf[LONGEST_HUMAN_READABLE + 1];
2878 int len = mbswidth (human_readable (blocks, buf, human_output_opts,
2879 ST_NBLOCKSIZE, output_block_size),
2881 if (block_size_width < len)
2882 block_size_width = len;
2885 if (format == long_format)
2887 if (print_owner)
2889 int len = format_user_width (f->stat.st_uid);
2890 if (owner_width < len)
2891 owner_width = len;
2894 if (print_group)
2896 int len = format_group_width (f->stat.st_gid);
2897 if (group_width < len)
2898 group_width = len;
2901 if (print_author)
2903 int len = format_user_width (f->stat.st_author);
2904 if (author_width < len)
2905 author_width = len;
2909 if (print_scontext)
2911 int len = strlen (f->scontext);
2912 if (scontext_width < len)
2913 scontext_width = len;
2916 if (format == long_format)
2918 char b[INT_BUFSIZE_BOUND (uintmax_t)];
2919 int b_len = strlen (umaxtostr (f->stat.st_nlink, b));
2920 if (nlink_width < b_len)
2921 nlink_width = b_len;
2923 if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode))
2925 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2926 int len = strlen (umaxtostr (major (f->stat.st_rdev), buf));
2927 if (major_device_number_width < len)
2928 major_device_number_width = len;
2929 len = strlen (umaxtostr (minor (f->stat.st_rdev), buf));
2930 if (minor_device_number_width < len)
2931 minor_device_number_width = len;
2932 len = major_device_number_width + 2 + minor_device_number_width;
2933 if (file_size_width < len)
2934 file_size_width = len;
2936 else
2938 char buf[LONGEST_HUMAN_READABLE + 1];
2939 uintmax_t size = unsigned_file_size (f->stat.st_size);
2940 int len = mbswidth (human_readable (size, buf, human_output_opts,
2941 1, file_output_block_size),
2943 if (file_size_width < len)
2944 file_size_width = len;
2949 if (print_inode)
2951 char buf[INT_BUFSIZE_BOUND (uintmax_t)];
2952 int len = strlen (umaxtostr (f->stat.st_ino, buf));
2953 if (inode_number_width < len)
2954 inode_number_width = len;
2957 f->name = xstrdup (name);
2958 cwd_n_used++;
2960 return blocks;
2963 /* Return true if F refers to a directory. */
2964 static bool
2965 is_directory (const struct fileinfo *f)
2967 return f->filetype == directory || f->filetype == arg_directory;
2970 /* Put the name of the file that FILENAME is a symbolic link to
2971 into the LINKNAME field of `f'. COMMAND_LINE_ARG indicates whether
2972 FILENAME is a command-line argument. */
2974 static void
2975 get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg)
2977 f->linkname = areadlink_with_size (filename, f->stat.st_size);
2978 if (f->linkname == NULL)
2979 file_failure (command_line_arg, _("cannot read symbolic link %s"),
2980 filename);
2983 /* If `linkname' is a relative name and `name' contains one or more
2984 leading directories, return `linkname' with those directories
2985 prepended; otherwise, return a copy of `linkname'.
2986 If `linkname' is zero, return zero. */
2988 static char *
2989 make_link_name (char const *name, char const *linkname)
2991 char *linkbuf;
2992 size_t bufsiz;
2994 if (!linkname)
2995 return NULL;
2997 if (*linkname == '/')
2998 return xstrdup (linkname);
3000 /* The link is to a relative name. Prepend any leading directory
3001 in `name' to the link name. */
3002 linkbuf = strrchr (name, '/');
3003 if (linkbuf == 0)
3004 return xstrdup (linkname);
3006 bufsiz = linkbuf - name + 1;
3007 linkbuf = xmalloc (bufsiz + strlen (linkname) + 1);
3008 strncpy (linkbuf, name, bufsiz);
3009 strcpy (linkbuf + bufsiz, linkname);
3010 return linkbuf;
3013 /* Return true if the last component of NAME is `.' or `..'
3014 This is so we don't try to recurse on `././././. ...' */
3016 static bool
3017 basename_is_dot_or_dotdot (const char *name)
3019 char const *base = last_component (name);
3020 return dot_or_dotdot (base);
3023 /* Remove any entries from CWD_FILE that are for directories,
3024 and queue them to be listed as directories instead.
3025 DIRNAME is the prefix to prepend to each dirname
3026 to make it correct relative to ls's working dir;
3027 if it is null, no prefix is needed and "." and ".." should not be ignored.
3028 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3029 This is desirable when processing directories recursively. */
3031 static void
3032 extract_dirs_from_files (char const *dirname, bool command_line_arg)
3034 size_t i;
3035 size_t j;
3036 bool ignore_dot_and_dot_dot = (dirname != NULL);
3038 if (dirname && LOOP_DETECT)
3040 /* Insert a marker entry first. When we dequeue this marker entry,
3041 we'll know that DIRNAME has been processed and may be removed
3042 from the set of active directories. */
3043 queue_directory (NULL, dirname, false);
3046 /* Queue the directories last one first, because queueing reverses the
3047 order. */
3048 for (i = cwd_n_used; i-- != 0; )
3050 struct fileinfo *f = sorted_file[i];
3052 if (is_directory (f)
3053 && (! ignore_dot_and_dot_dot
3054 || ! basename_is_dot_or_dotdot (f->name)))
3056 if (!dirname || f->name[0] == '/')
3057 queue_directory (f->name, f->linkname, command_line_arg);
3058 else
3060 char *name = file_name_concat (dirname, f->name, NULL);
3061 queue_directory (name, f->linkname, command_line_arg);
3062 free (name);
3064 if (f->filetype == arg_directory)
3065 free (f->name);
3069 /* Now delete the directories from the table, compacting all the remaining
3070 entries. */
3072 for (i = 0, j = 0; i < cwd_n_used; i++)
3074 struct fileinfo *f = sorted_file[i];
3075 sorted_file[j] = f;
3076 j += (f->filetype != arg_directory);
3078 cwd_n_used = j;
3081 /* Use strcoll to compare strings in this locale. If an error occurs,
3082 report an error and longjmp to failed_strcoll. */
3084 static jmp_buf failed_strcoll;
3086 static int
3087 xstrcoll (char const *a, char const *b)
3089 int diff;
3090 errno = 0;
3091 diff = strcoll (a, b);
3092 if (errno)
3094 error (0, errno, _("cannot compare file names %s and %s"),
3095 quote_n (0, a), quote_n (1, b));
3096 set_exit_status (false);
3097 longjmp (failed_strcoll, 1);
3099 return diff;
3102 /* Comparison routines for sorting the files. */
3104 typedef void const *V;
3105 typedef int (*qsortFunc)(V a, V b);
3107 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
3108 The do { ... } while(0) makes it possible to use the macro more like
3109 a statement, without violating C89 rules: */
3110 #define DIRFIRST_CHECK(a, b) \
3111 do \
3113 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
3114 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
3115 if (a_is_dir && !b_is_dir) \
3116 return -1; /* a goes before b */ \
3117 if (!a_is_dir && b_is_dir) \
3118 return 1; /* b goes before a */ \
3120 while (0)
3122 /* Define the 8 different sort function variants required for each sortkey.
3123 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3124 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3125 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3126 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3127 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3128 /* direct, non-dirfirst versions */ \
3129 static int xstrcoll_##key_name (V a, V b) \
3130 { return key_cmp_func (a, b, xstrcoll); } \
3131 static int strcmp_##key_name (V a, V b) \
3132 { return key_cmp_func (a, b, strcmp); } \
3134 /* reverse, non-dirfirst versions */ \
3135 static int rev_xstrcoll_##key_name (V a, V b) \
3136 { return key_cmp_func (b, a, xstrcoll); } \
3137 static int rev_strcmp_##key_name (V a, V b) \
3138 { return key_cmp_func (b, a, strcmp); } \
3140 /* direct, dirfirst versions */ \
3141 static int xstrcoll_df_##key_name (V a, V b) \
3142 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
3143 static int strcmp_df_##key_name (V a, V b) \
3144 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
3146 /* reverse, dirfirst versions */ \
3147 static int rev_xstrcoll_df_##key_name (V a, V b) \
3148 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
3149 static int rev_strcmp_df_##key_name (V a, V b) \
3150 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
3152 static inline int
3153 cmp_ctime (struct fileinfo const *a, struct fileinfo const *b,
3154 int (*cmp) (char const *, char const *))
3156 int diff = timespec_cmp (get_stat_ctime (&b->stat),
3157 get_stat_ctime (&a->stat));
3158 return diff ? diff : cmp (a->name, b->name);
3161 static inline int
3162 cmp_mtime (struct fileinfo const *a, struct fileinfo const *b,
3163 int (*cmp) (char const *, char const *))
3165 int diff = timespec_cmp (get_stat_mtime (&b->stat),
3166 get_stat_mtime (&a->stat));
3167 return diff ? diff : cmp (a->name, b->name);
3170 static inline int
3171 cmp_atime (struct fileinfo const *a, struct fileinfo const *b,
3172 int (*cmp) (char const *, char const *))
3174 int diff = timespec_cmp (get_stat_atime (&b->stat),
3175 get_stat_atime (&a->stat));
3176 return diff ? diff : cmp (a->name, b->name);
3179 static inline int
3180 cmp_size (struct fileinfo const *a, struct fileinfo const *b,
3181 int (*cmp) (char const *, char const *))
3183 int diff = longdiff (b->stat.st_size, a->stat.st_size);
3184 return diff ? diff : cmp (a->name, b->name);
3187 static inline int
3188 cmp_name (struct fileinfo const *a, struct fileinfo const *b,
3189 int (*cmp) (char const *, char const *))
3191 return cmp (a->name, b->name);
3194 /* Compare file extensions. Files with no extension are `smallest'.
3195 If extensions are the same, compare by filenames instead. */
3197 static inline int
3198 cmp_extension (struct fileinfo const *a, struct fileinfo const *b,
3199 int (*cmp) (char const *, char const *))
3201 char const *base1 = strrchr (a->name, '.');
3202 char const *base2 = strrchr (b->name, '.');
3203 int diff = cmp (base1 ? base1 : "", base2 ? base2 : "");
3204 return diff ? diff : cmp (a->name, b->name);
3207 DEFINE_SORT_FUNCTIONS (ctime, cmp_ctime)
3208 DEFINE_SORT_FUNCTIONS (mtime, cmp_mtime)
3209 DEFINE_SORT_FUNCTIONS (atime, cmp_atime)
3210 DEFINE_SORT_FUNCTIONS (size, cmp_size)
3211 DEFINE_SORT_FUNCTIONS (name, cmp_name)
3212 DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
3214 /* Compare file versions.
3215 Unlike all other compare functions above, cmp_version depends only
3216 on filevercmp, which does not fail (even for locale reasons), and does not
3217 need a secondary sort key. See lib/filevercmp.h for function description.
3219 All the other sort options, in fact, need xstrcoll and strcmp variants,
3220 because they all use a string comparison (either as the primary or secondary
3221 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3222 locale reasons. Last, strverscmp is ALWAYS available in coreutils,
3223 thanks to the gnulib library. */
3224 static inline int
3225 cmp_version (struct fileinfo const *a, struct fileinfo const *b)
3227 return filevercmp (a->name, b->name);
3230 static int xstrcoll_version (V a, V b)
3231 { return cmp_version (a, b); }
3232 static int rev_xstrcoll_version (V a, V b)
3233 { return cmp_version (b, a); }
3234 static int xstrcoll_df_version (V a, V b)
3235 { DIRFIRST_CHECK (a, b); return cmp_version (a, b); }
3236 static int rev_xstrcoll_df_version (V a, V b)
3237 { DIRFIRST_CHECK (a, b); return cmp_version (b, a); }
3240 /* We have 2^3 different variants for each sortkey function
3241 (for 3 independent sort modes).
3242 The function pointers stored in this array must be dereferenced as:
3244 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3246 Note that the order in which sortkeys are listed in the function pointer
3247 array below is defined by the order of the elements in the time_type and
3248 sort_type enums! */
3250 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3253 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3254 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3255 }, \
3257 { strcmp_##key_name, strcmp_df_##key_name }, \
3258 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3262 static qsortFunc const sort_functions[][2][2][2] =
3264 LIST_SORTFUNCTION_VARIANTS (name),
3265 LIST_SORTFUNCTION_VARIANTS (extension),
3266 LIST_SORTFUNCTION_VARIANTS (size),
3270 { xstrcoll_version, xstrcoll_df_version },
3271 { rev_xstrcoll_version, rev_xstrcoll_df_version },
3274 /* We use NULL for the strcmp variants of version comparison
3275 since as explained in cmp_version definition, version comparison
3276 does not rely on xstrcoll, so it will never longjmp, and never
3277 need to try the strcmp fallback. */
3279 { NULL, NULL },
3280 { NULL, NULL },
3284 /* last are time sort functions */
3285 LIST_SORTFUNCTION_VARIANTS (mtime),
3286 LIST_SORTFUNCTION_VARIANTS (ctime),
3287 LIST_SORTFUNCTION_VARIANTS (atime)
3290 /* The number of sortkeys is calculated as
3291 the number of elements in the sort_type enum (i.e. sort_numtypes) +
3292 the number of elements in the time_type enum (i.e. time_numtypes) - 1
3293 This is because when sort_type==sort_time, we have up to
3294 time_numtypes possible sortkeys.
3296 This line verifies at compile-time that the array of sort functions has been
3297 initialized for all possible sortkeys. */
3298 verify (ARRAY_CARDINALITY (sort_functions)
3299 == sort_numtypes + time_numtypes - 1 );
3301 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
3303 static void
3304 initialize_ordering_vector (void)
3306 size_t i;
3307 for (i = 0; i < cwd_n_used; i++)
3308 sorted_file[i] = &cwd_file[i];
3311 /* Sort the files now in the table. */
3313 static void
3314 sort_files (void)
3316 bool use_strcmp;
3318 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
3320 free (sorted_file);
3321 sorted_file = xnmalloc (cwd_n_used, 3 * sizeof *sorted_file);
3322 sorted_file_alloc = 3 * cwd_n_used;
3325 initialize_ordering_vector ();
3327 if (sort_type == sort_none)
3328 return;
3330 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3331 ignore strcoll failures, as a failing strcoll might be a
3332 comparison function that is not a total order, and if we ignored
3333 the failure this might cause qsort to dump core. */
3335 if (! setjmp (failed_strcoll))
3336 use_strcmp = false; /* strcoll() succeeded */
3337 else
3339 use_strcmp = true;
3340 assert (sort_type != sort_version);
3341 initialize_ordering_vector ();
3344 /* When sort_type == sort_time, use time_type as subindex. */
3345 mpsort ((void const **) sorted_file, cwd_n_used,
3346 sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)]
3347 [use_strcmp][sort_reverse]
3348 [directories_first]);
3351 /* List all the files now in the table. */
3353 static void
3354 print_current_files (void)
3356 size_t i;
3358 switch (format)
3360 case one_per_line:
3361 for (i = 0; i < cwd_n_used; i++)
3363 print_file_name_and_frills (sorted_file[i], 0);
3364 putchar ('\n');
3366 break;
3368 case many_per_line:
3369 print_many_per_line ();
3370 break;
3372 case horizontal:
3373 print_horizontal ();
3374 break;
3376 case with_commas:
3377 print_with_commas ();
3378 break;
3380 case long_format:
3381 for (i = 0; i < cwd_n_used; i++)
3383 print_long_format (sorted_file[i]);
3384 DIRED_PUTCHAR ('\n');
3386 break;
3390 /* Replace the first %b with precomputed aligned month names.
3391 Note on glibc-2.7 at least, this speeds up the whole `ls -lU`
3392 process by around 17%, compared to letting strftime() handle the %b. */
3394 static size_t
3395 align_nstrftime (char *buf, size_t size, char const *fmt, struct tm const *tm,
3396 int __utc, int __ns)
3398 const char *nfmt = fmt;
3399 /* In the unlikely event that rpl_fmt below is not large enough,
3400 the replacement is not done. A malloc here slows ls down by 2% */
3401 char rpl_fmt[sizeof (abmon[0]) + 100];
3402 const char *pb;
3403 if (required_mon_width && (pb = strstr (fmt, "%b")))
3405 if (strlen (fmt) < (sizeof (rpl_fmt) - sizeof (abmon[0]) + 2))
3407 char *pfmt = rpl_fmt;
3408 nfmt = rpl_fmt;
3410 pfmt = mempcpy (pfmt, fmt, pb - fmt);
3411 pfmt = stpcpy (pfmt, abmon[tm->tm_mon]);
3412 strcpy (pfmt, pb + 2);
3415 size_t ret = nstrftime (buf, size, nfmt, tm, __utc, __ns);
3416 return ret;
3419 /* Return the expected number of columns in a long-format time stamp,
3420 or zero if it cannot be calculated. */
3422 static int
3423 long_time_expected_width (void)
3425 static int width = -1;
3427 if (width < 0)
3429 time_t epoch = 0;
3430 struct tm const *tm = localtime (&epoch);
3431 char buf[TIME_STAMP_LEN_MAXIMUM + 1];
3433 /* In case you're wondering if localtime can fail with an input time_t
3434 value of 0, let's just say it's very unlikely, but not inconceivable.
3435 The TZ environment variable would have to specify a time zone that
3436 is 2**31-1900 years or more ahead of UTC. This could happen only on
3437 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3438 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3439 their implementations limit the offset to 167:59 and 24:00, resp. */
3440 if (tm)
3442 size_t len =
3443 align_nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0);
3444 if (len != 0)
3445 width = mbsnwidth (buf, len, 0);
3448 if (width < 0)
3449 width = 0;
3452 return width;
3455 /* Print the user or group name NAME, with numeric id ID, using a
3456 print width of WIDTH columns. */
3458 static void
3459 format_user_or_group (char const *name, unsigned long int id, int width)
3461 size_t len;
3463 if (name)
3465 int width_gap = width - mbswidth (name, 0);
3466 int pad = MAX (0, width_gap);
3467 fputs (name, stdout);
3468 len = strlen (name) + pad;
3471 putchar (' ');
3472 while (pad--);
3474 else
3476 printf ("%*lu ", width, id);
3477 len = width;
3480 dired_pos += len + 1;
3483 /* Print the name or id of the user with id U, using a print width of
3484 WIDTH. */
3486 static void
3487 format_user (uid_t u, int width, bool stat_ok)
3489 format_user_or_group (! stat_ok ? "?" :
3490 (numeric_ids ? NULL : getuser (u)), u, width);
3493 /* Likewise, for groups. */
3495 static void
3496 format_group (gid_t g, int width, bool stat_ok)
3498 format_user_or_group (! stat_ok ? "?" :
3499 (numeric_ids ? NULL : getgroup (g)), g, width);
3502 /* Return the number of columns that format_user_or_group will print. */
3504 static int
3505 format_user_or_group_width (char const *name, unsigned long int id)
3507 if (name)
3509 int len = mbswidth (name, 0);
3510 return MAX (0, len);
3512 else
3514 char buf[INT_BUFSIZE_BOUND (unsigned long int)];
3515 sprintf (buf, "%lu", id);
3516 return strlen (buf);
3520 /* Return the number of columns that format_user will print. */
3522 static int
3523 format_user_width (uid_t u)
3525 return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3528 /* Likewise, for groups. */
3530 static int
3531 format_group_width (gid_t g)
3533 return format_user_or_group_width (numeric_ids ? NULL : getgroup (g), g);
3537 /* Print information about F in long format. */
3539 static void
3540 print_long_format (const struct fileinfo *f)
3542 char modebuf[12];
3543 char buf
3544 [LONGEST_HUMAN_READABLE + 1 /* inode */
3545 + LONGEST_HUMAN_READABLE + 1 /* size in blocks */
3546 + sizeof (modebuf) - 1 + 1 /* mode string */
3547 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
3548 + LONGEST_HUMAN_READABLE + 2 /* major device number */
3549 + LONGEST_HUMAN_READABLE + 1 /* minor device number */
3550 + TIME_STAMP_LEN_MAXIMUM + 1 /* max length of time/date */
3552 size_t s;
3553 char *p;
3554 struct timespec when_timespec;
3555 struct tm *when_local;
3557 /* Compute the mode string, except remove the trailing space if no
3558 file in this directory has an ACL or SELinux security context. */
3559 if (f->stat_ok)
3560 filemodestring (&f->stat, modebuf);
3561 else
3563 modebuf[0] = filetype_letter[f->filetype];
3564 memset (modebuf + 1, '?', 10);
3565 modebuf[11] = '\0';
3567 if (! any_has_acl)
3568 modebuf[10] = '\0';
3569 else if (f->acl_type == ACL_T_SELINUX_ONLY)
3570 modebuf[10] = '.';
3571 else if (f->acl_type == ACL_T_YES)
3572 modebuf[10] = '+';
3574 switch (time_type)
3576 case time_ctime:
3577 when_timespec = get_stat_ctime (&f->stat);
3578 break;
3579 case time_mtime:
3580 when_timespec = get_stat_mtime (&f->stat);
3581 break;
3582 case time_atime:
3583 when_timespec = get_stat_atime (&f->stat);
3584 break;
3585 default:
3586 abort ();
3589 p = buf;
3591 if (print_inode)
3593 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3594 sprintf (p, "%*s ", inode_number_width,
3595 (f->stat.st_ino == NOT_AN_INODE_NUMBER
3596 ? "?"
3597 : umaxtostr (f->stat.st_ino, hbuf)));
3598 /* Increment by strlen (p) here, rather than by inode_number_width + 1.
3599 The latter is wrong when inode_number_width is zero. */
3600 p += strlen (p);
3603 if (print_block_size)
3605 char hbuf[LONGEST_HUMAN_READABLE + 1];
3606 char const *blocks =
3607 (! f->stat_ok
3608 ? "?"
3609 : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
3610 ST_NBLOCKSIZE, output_block_size));
3611 int pad;
3612 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
3613 *p++ = ' ';
3614 while ((*p++ = *blocks++))
3615 continue;
3616 p[-1] = ' ';
3619 /* The last byte of the mode string is the POSIX
3620 "optional alternate access method flag". */
3622 char hbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3623 sprintf (p, "%s %*s ", modebuf, nlink_width,
3624 ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf));
3626 /* Increment by strlen (p) here, rather than by, e.g.,
3627 sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
3628 The latter is wrong when nlink_width is zero. */
3629 p += strlen (p);
3631 DIRED_INDENT ();
3633 if (print_owner | print_group | print_author | print_scontext)
3635 DIRED_FPUTS (buf, stdout, p - buf);
3637 if (print_owner)
3638 format_user (f->stat.st_uid, owner_width, f->stat_ok);
3640 if (print_group)
3641 format_group (f->stat.st_gid, group_width, f->stat_ok);
3643 if (print_author)
3644 format_user (f->stat.st_author, author_width, f->stat_ok);
3646 if (print_scontext)
3647 format_user_or_group (f->scontext, 0, scontext_width);
3649 p = buf;
3652 if (f->stat_ok
3653 && (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)))
3655 char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3656 char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)];
3657 int blanks_width = (file_size_width
3658 - (major_device_number_width + 2
3659 + minor_device_number_width));
3660 sprintf (p, "%*s, %*s ",
3661 major_device_number_width + MAX (0, blanks_width),
3662 umaxtostr (major (f->stat.st_rdev), majorbuf),
3663 minor_device_number_width,
3664 umaxtostr (minor (f->stat.st_rdev), minorbuf));
3665 p += file_size_width + 1;
3667 else
3669 char hbuf[LONGEST_HUMAN_READABLE + 1];
3670 char const *size =
3671 (! f->stat_ok
3672 ? "?"
3673 : human_readable (unsigned_file_size (f->stat.st_size),
3674 hbuf, human_output_opts, 1, file_output_block_size));
3675 int pad;
3676 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
3677 *p++ = ' ';
3678 while ((*p++ = *size++))
3679 continue;
3680 p[-1] = ' ';
3683 when_local = localtime (&when_timespec.tv_sec);
3684 s = 0;
3685 *p = '\1';
3687 if (f->stat_ok && when_local)
3689 struct timespec six_months_ago;
3690 bool recent;
3691 char const *fmt;
3693 /* If the file appears to be in the future, update the current
3694 time, in case the file happens to have been modified since
3695 the last time we checked the clock. */
3696 if (timespec_cmp (current_time, when_timespec) < 0)
3698 /* Note that gettime may call gettimeofday which, on some non-
3699 compliant systems, clobbers the buffer used for localtime's result.
3700 But it's ok here, because we use a gettimeofday wrapper that
3701 saves and restores the buffer around the gettimeofday call. */
3702 gettime (&current_time);
3705 /* Consider a time to be recent if it is within the past six
3706 months. A Gregorian year has 365.2425 * 24 * 60 * 60 ==
3707 31556952 seconds on the average. Write this value as an
3708 integer constant to avoid floating point hassles. */
3709 six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2;
3710 six_months_ago.tv_nsec = current_time.tv_nsec;
3712 recent = (timespec_cmp (six_months_ago, when_timespec) < 0
3713 && (timespec_cmp (when_timespec, current_time) < 0));
3714 fmt = long_time_format[recent];
3716 /* We assume here that all time zones are offset from UTC by a
3717 whole number of seconds. */
3718 s = align_nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt,
3719 when_local, 0, when_timespec.tv_nsec);
3722 if (s || !*p)
3724 p += s;
3725 *p++ = ' ';
3727 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
3728 *p = '\0';
3730 else
3732 /* The time cannot be converted using the desired format, so
3733 print it as a huge integer number of seconds. */
3734 char hbuf[INT_BUFSIZE_BOUND (intmax_t)];
3735 sprintf (p, "%*s ", long_time_expected_width (),
3736 (! f->stat_ok
3737 ? "?"
3738 : timetostr (when_timespec.tv_sec, hbuf)));
3739 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
3740 p += strlen (p);
3743 DIRED_FPUTS (buf, stdout, p - buf);
3744 size_t w = print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok,
3745 f->stat_ok, f->filetype, &dired_obstack,
3746 f->stat.st_nlink, p - buf);
3748 if (f->filetype == symbolic_link)
3750 if (f->linkname)
3752 DIRED_FPUTS_LITERAL (" -> ", stdout);
3753 print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1,
3754 f->stat_ok, f->filetype, NULL,
3755 f->stat.st_nlink, (p - buf) + w + 4);
3756 if (indicator_style != none)
3757 print_type_indicator (true, f->linkmode, unknown);
3760 else if (indicator_style != none)
3761 print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
3764 /* Output to OUT a quoted representation of the file name NAME,
3765 using OPTIONS to control quoting. Produce no output if OUT is NULL.
3766 Store the number of screen columns occupied by NAME's quoted
3767 representation into WIDTH, if non-NULL. Return the number of bytes
3768 produced. */
3770 static size_t
3771 quote_name (FILE *out, const char *name, struct quoting_options const *options,
3772 size_t *width)
3774 char smallbuf[BUFSIZ];
3775 size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options);
3776 char *buf;
3777 size_t displayed_width IF_LINT (= 0);
3779 if (len < sizeof smallbuf)
3780 buf = smallbuf;
3781 else
3783 buf = alloca (len + 1);
3784 quotearg_buffer (buf, len + 1, name, -1, options);
3787 if (qmark_funny_chars)
3789 if (MB_CUR_MAX > 1)
3791 char const *p = buf;
3792 char const *plimit = buf + len;
3793 char *q = buf;
3794 displayed_width = 0;
3796 while (p < plimit)
3797 switch (*p)
3799 case ' ': case '!': case '"': case '#': case '%':
3800 case '&': case '\'': case '(': case ')': case '*':
3801 case '+': case ',': case '-': case '.': case '/':
3802 case '0': case '1': case '2': case '3': case '4':
3803 case '5': case '6': case '7': case '8': case '9':
3804 case ':': case ';': case '<': case '=': case '>':
3805 case '?':
3806 case 'A': case 'B': case 'C': case 'D': case 'E':
3807 case 'F': case 'G': case 'H': case 'I': case 'J':
3808 case 'K': case 'L': case 'M': case 'N': case 'O':
3809 case 'P': case 'Q': case 'R': case 'S': case 'T':
3810 case 'U': case 'V': case 'W': case 'X': case 'Y':
3811 case 'Z':
3812 case '[': case '\\': case ']': case '^': case '_':
3813 case 'a': case 'b': case 'c': case 'd': case 'e':
3814 case 'f': case 'g': case 'h': case 'i': case 'j':
3815 case 'k': case 'l': case 'm': case 'n': case 'o':
3816 case 'p': case 'q': case 'r': case 's': case 't':
3817 case 'u': case 'v': case 'w': case 'x': case 'y':
3818 case 'z': case '{': case '|': case '}': case '~':
3819 /* These characters are printable ASCII characters. */
3820 *q++ = *p++;
3821 displayed_width += 1;
3822 break;
3823 default:
3824 /* If we have a multibyte sequence, copy it until we
3825 reach its end, replacing each non-printable multibyte
3826 character with a single question mark. */
3828 DECLARE_ZEROED_AGGREGATE (mbstate_t, mbstate);
3831 wchar_t wc;
3832 size_t bytes;
3833 int w;
3835 bytes = mbrtowc (&wc, p, plimit - p, &mbstate);
3837 if (bytes == (size_t) -1)
3839 /* An invalid multibyte sequence was
3840 encountered. Skip one input byte, and
3841 put a question mark. */
3842 p++;
3843 *q++ = '?';
3844 displayed_width += 1;
3845 break;
3848 if (bytes == (size_t) -2)
3850 /* An incomplete multibyte character
3851 at the end. Replace it entirely with
3852 a question mark. */
3853 p = plimit;
3854 *q++ = '?';
3855 displayed_width += 1;
3856 break;
3859 if (bytes == 0)
3860 /* A null wide character was encountered. */
3861 bytes = 1;
3863 w = wcwidth (wc);
3864 if (w >= 0)
3866 /* A printable multibyte character.
3867 Keep it. */
3868 for (; bytes > 0; --bytes)
3869 *q++ = *p++;
3870 displayed_width += w;
3872 else
3874 /* An unprintable multibyte character.
3875 Replace it entirely with a question
3876 mark. */
3877 p += bytes;
3878 *q++ = '?';
3879 displayed_width += 1;
3882 while (! mbsinit (&mbstate));
3884 break;
3887 /* The buffer may have shrunk. */
3888 len = q - buf;
3890 else
3892 char *p = buf;
3893 char const *plimit = buf + len;
3895 while (p < plimit)
3897 if (! isprint (to_uchar (*p)))
3898 *p = '?';
3899 p++;
3901 displayed_width = len;
3904 else if (width != NULL)
3906 if (MB_CUR_MAX > 1)
3907 displayed_width = mbsnwidth (buf, len, 0);
3908 else
3910 char const *p = buf;
3911 char const *plimit = buf + len;
3913 displayed_width = 0;
3914 while (p < plimit)
3916 if (isprint (to_uchar (*p)))
3917 displayed_width++;
3918 p++;
3923 if (out != NULL)
3924 fwrite (buf, 1, len, out);
3925 if (width != NULL)
3926 *width = displayed_width;
3927 return len;
3930 static size_t
3931 print_name_with_quoting (const char *p, mode_t mode, int linkok,
3932 bool stat_ok, enum filetype type,
3933 struct obstack *stack, nlink_t nlink,
3934 size_t start_col)
3936 bool used_color_this_time
3937 = (print_with_color
3938 && print_color_indicator (p, mode, linkok, stat_ok, type, nlink));
3940 if (stack)
3941 PUSH_CURRENT_DIRED_POS (stack);
3943 size_t width = quote_name (stdout, p, filename_quoting_options, NULL);
3944 dired_pos += width;
3946 if (stack)
3947 PUSH_CURRENT_DIRED_POS (stack);
3949 if (used_color_this_time)
3951 process_signals ();
3952 prep_non_filename_text ();
3953 if (start_col / line_length != (start_col + width - 1) / line_length)
3954 put_indicator (&color_indicator[C_CLR_TO_EOL]);
3957 return width;
3960 static void
3961 prep_non_filename_text (void)
3963 if (color_indicator[C_END].string != NULL)
3964 put_indicator (&color_indicator[C_END]);
3965 else
3967 put_indicator (&color_indicator[C_LEFT]);
3968 put_indicator (&color_indicator[C_RESET]);
3969 put_indicator (&color_indicator[C_RIGHT]);
3973 /* Print the file name of `f' with appropriate quoting.
3974 Also print file size, inode number, and filetype indicator character,
3975 as requested by switches. */
3977 static size_t
3978 print_file_name_and_frills (const struct fileinfo *f, size_t start_col)
3980 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
3982 if (print_inode)
3983 printf ("%*s ", format == with_commas ? 0 : inode_number_width,
3984 umaxtostr (f->stat.st_ino, buf));
3986 if (print_block_size)
3987 printf ("%*s ", format == with_commas ? 0 : block_size_width,
3988 human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
3989 ST_NBLOCKSIZE, output_block_size));
3991 if (print_scontext)
3992 printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext);
3994 size_t width = print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f),
3995 f->linkok, f->stat_ok, f->filetype,
3996 NULL, f->stat.st_nlink, start_col);
3998 if (indicator_style != none)
3999 width += print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4001 return width;
4004 /* Given these arguments describing a file, return the single-byte
4005 type indicator, or 0. */
4006 static char
4007 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4009 char c;
4011 if (stat_ok ? S_ISREG (mode) : type == normal)
4013 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
4014 c = '*';
4015 else
4016 c = 0;
4018 else
4020 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
4021 c = '/';
4022 else if (indicator_style == slash)
4023 c = 0;
4024 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
4025 c = '@';
4026 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
4027 c = '|';
4028 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
4029 c = '=';
4030 else if (stat_ok && S_ISDOOR (mode))
4031 c = '>';
4032 else
4033 c = 0;
4035 return c;
4038 static bool
4039 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4041 char c = get_type_indicator (stat_ok, mode, type);
4042 if (c)
4043 DIRED_PUTCHAR (c);
4044 return !!c;
4047 #ifdef HAVE_CAP
4048 /* Return true if NAME has a capability (see linux/capability.h) */
4049 static bool
4050 has_capability (char const *name)
4052 char *result;
4053 bool has_cap;
4055 cap_t cap_d = cap_get_file (name);
4056 if (cap_d == NULL)
4057 return false;
4059 result = cap_to_text (cap_d, NULL);
4060 cap_free (cap_d);
4061 if (!result)
4062 return false;
4064 /* check if human-readable capability string is empty */
4065 has_cap = !!*result;
4067 cap_free (result);
4068 return has_cap;
4070 #else
4071 static bool
4072 has_capability (char const *name ATTRIBUTE_UNUSED)
4074 return false;
4076 #endif
4078 /* Returns whether any color sequence was printed. */
4079 static bool
4080 print_color_indicator (const char *name, mode_t mode, int linkok,
4081 bool stat_ok, enum filetype filetype,
4082 nlink_t nlink)
4084 int type;
4085 struct color_ext_type *ext; /* Color extension */
4086 size_t len; /* Length of name */
4088 /* Is this a nonexistent file? If so, linkok == -1. */
4090 if (linkok == -1 && color_indicator[C_MISSING].string != NULL)
4091 type = C_MISSING;
4092 else if (! stat_ok)
4094 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
4095 type = filetype_indicator[filetype];
4097 else
4099 if (S_ISREG (mode))
4101 type = C_FILE;
4102 if ((mode & S_ISUID) != 0)
4103 type = C_SETUID;
4104 else if ((mode & S_ISGID) != 0)
4105 type = C_SETGID;
4106 else if (is_colored (C_CAP) && has_capability (name))
4107 type = C_CAP;
4108 else if ((mode & S_IXUGO) != 0)
4109 type = C_EXEC;
4110 else if (is_colored (C_MULTIHARDLINK) && (1 < nlink))
4111 type = C_MULTIHARDLINK;
4113 else if (S_ISDIR (mode))
4115 if ((mode & S_ISVTX) && (mode & S_IWOTH))
4116 type = C_STICKY_OTHER_WRITABLE;
4117 else if ((mode & S_IWOTH) != 0)
4118 type = C_OTHER_WRITABLE;
4119 else if ((mode & S_ISVTX) != 0)
4120 type = C_STICKY;
4121 else
4122 type = C_DIR;
4124 else if (S_ISLNK (mode))
4125 type = ((!linkok && color_indicator[C_ORPHAN].string)
4126 ? C_ORPHAN : C_LINK);
4127 else if (S_ISFIFO (mode))
4128 type = C_FIFO;
4129 else if (S_ISSOCK (mode))
4130 type = C_SOCK;
4131 else if (S_ISBLK (mode))
4132 type = C_BLK;
4133 else if (S_ISCHR (mode))
4134 type = C_CHR;
4135 else if (S_ISDOOR (mode))
4136 type = C_DOOR;
4137 else
4139 /* Classify a file of some other type as C_ORPHAN. */
4140 type = C_ORPHAN;
4144 /* Check the file's suffix only if still classified as C_FILE. */
4145 ext = NULL;
4146 if (type == C_FILE)
4148 /* Test if NAME has a recognized suffix. */
4150 len = strlen (name);
4151 name += len; /* Pointer to final \0. */
4152 for (ext = color_ext_list; ext != NULL; ext = ext->next)
4154 if (ext->ext.len <= len
4155 && strncmp (name - ext->ext.len, ext->ext.string,
4156 ext->ext.len) == 0)
4157 break;
4162 const struct bin_str *const s
4163 = ext ? &(ext->seq) : &color_indicator[type];
4164 if (s->string != NULL)
4166 put_indicator (&color_indicator[C_LEFT]);
4167 put_indicator (s);
4168 put_indicator (&color_indicator[C_RIGHT]);
4169 return true;
4171 else
4172 return false;
4176 /* Output a color indicator (which may contain nulls). */
4177 static void
4178 put_indicator (const struct bin_str *ind)
4180 if (! used_color)
4182 used_color = true;
4183 prep_non_filename_text ();
4186 fwrite (ind->string, ind->len, 1, stdout);
4189 static size_t
4190 length_of_file_name_and_frills (const struct fileinfo *f)
4192 size_t len = 0;
4193 size_t name_width;
4194 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4196 if (print_inode)
4197 len += 1 + (format == with_commas
4198 ? strlen (umaxtostr (f->stat.st_ino, buf))
4199 : inode_number_width);
4201 if (print_block_size)
4202 len += 1 + (format == with_commas
4203 ? strlen (human_readable (ST_NBLOCKS (f->stat), buf,
4204 human_output_opts, ST_NBLOCKSIZE,
4205 output_block_size))
4206 : block_size_width);
4208 if (print_scontext)
4209 len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width);
4211 quote_name (NULL, f->name, filename_quoting_options, &name_width);
4212 len += name_width;
4214 if (indicator_style != none)
4216 char c = get_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype);
4217 len += (c != 0);
4220 return len;
4223 static void
4224 print_many_per_line (void)
4226 size_t row; /* Current row. */
4227 size_t cols = calculate_columns (true);
4228 struct column_info const *line_fmt = &column_info[cols - 1];
4230 /* Calculate the number of rows that will be in each column except possibly
4231 for a short column on the right. */
4232 size_t rows = cwd_n_used / cols + (cwd_n_used % cols != 0);
4234 for (row = 0; row < rows; row++)
4236 size_t col = 0;
4237 size_t filesno = row;
4238 size_t pos = 0;
4240 /* Print the next row. */
4241 while (1)
4243 struct fileinfo const *f = sorted_file[filesno];
4244 size_t name_length = length_of_file_name_and_frills (f);
4245 size_t max_name_length = line_fmt->col_arr[col++];
4246 print_file_name_and_frills (f, pos);
4248 filesno += rows;
4249 if (filesno >= cwd_n_used)
4250 break;
4252 indent (pos + name_length, pos + max_name_length);
4253 pos += max_name_length;
4255 putchar ('\n');
4259 static void
4260 print_horizontal (void)
4262 size_t filesno;
4263 size_t pos = 0;
4264 size_t cols = calculate_columns (false);
4265 struct column_info const *line_fmt = &column_info[cols - 1];
4266 struct fileinfo const *f = sorted_file[0];
4267 size_t name_length = length_of_file_name_and_frills (f);
4268 size_t max_name_length = line_fmt->col_arr[0];
4270 /* Print first entry. */
4271 print_file_name_and_frills (f, 0);
4273 /* Now the rest. */
4274 for (filesno = 1; filesno < cwd_n_used; ++filesno)
4276 size_t col = filesno % cols;
4278 if (col == 0)
4280 putchar ('\n');
4281 pos = 0;
4283 else
4285 indent (pos + name_length, pos + max_name_length);
4286 pos += max_name_length;
4289 f = sorted_file[filesno];
4290 print_file_name_and_frills (f, pos);
4292 name_length = length_of_file_name_and_frills (f);
4293 max_name_length = line_fmt->col_arr[col];
4295 putchar ('\n');
4298 static void
4299 print_with_commas (void)
4301 size_t filesno;
4302 size_t pos = 0;
4304 for (filesno = 0; filesno < cwd_n_used; filesno++)
4306 struct fileinfo const *f = sorted_file[filesno];
4307 size_t len = length_of_file_name_and_frills (f);
4309 if (filesno != 0)
4311 char separator;
4313 if (pos + len + 2 < line_length)
4315 pos += 2;
4316 separator = ' ';
4318 else
4320 pos = 0;
4321 separator = '\n';
4324 putchar (',');
4325 putchar (separator);
4328 print_file_name_and_frills (f, pos);
4329 pos += len;
4331 putchar ('\n');
4334 /* Assuming cursor is at position FROM, indent up to position TO.
4335 Use a TAB character instead of two or more spaces whenever possible. */
4337 static void
4338 indent (size_t from, size_t to)
4340 while (from < to)
4342 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4344 putchar ('\t');
4345 from += tabsize - from % tabsize;
4347 else
4349 putchar (' ');
4350 from++;
4355 /* Put DIRNAME/NAME into DEST, handling `.' and `/' properly. */
4356 /* FIXME: maybe remove this function someday. See about using a
4357 non-malloc'ing version of file_name_concat. */
4359 static void
4360 attach (char *dest, const char *dirname, const char *name)
4362 const char *dirnamep = dirname;
4364 /* Copy dirname if it is not ".". */
4365 if (dirname[0] != '.' || dirname[1] != 0)
4367 while (*dirnamep)
4368 *dest++ = *dirnamep++;
4369 /* Add '/' if `dirname' doesn't already end with it. */
4370 if (dirnamep > dirname && dirnamep[-1] != '/')
4371 *dest++ = '/';
4373 while (*name)
4374 *dest++ = *name++;
4375 *dest = 0;
4378 /* Allocate enough column info suitable for the current number of
4379 files and display columns, and initialize the info to represent the
4380 narrowest possible columns. */
4382 static void
4383 init_column_info (void)
4385 size_t i;
4386 size_t max_cols = MIN (max_idx, cwd_n_used);
4388 /* Currently allocated columns in column_info. */
4389 static size_t column_info_alloc;
4391 if (column_info_alloc < max_cols)
4393 size_t new_column_info_alloc;
4394 size_t *p;
4396 if (max_cols < max_idx / 2)
4398 /* The number of columns is far less than the display width
4399 allows. Grow the allocation, but only so that it's
4400 double the current requirements. If the display is
4401 extremely wide, this avoids allocating a lot of memory
4402 that is never needed. */
4403 column_info = xnrealloc (column_info, max_cols,
4404 2 * sizeof *column_info);
4405 new_column_info_alloc = 2 * max_cols;
4407 else
4409 column_info = xnrealloc (column_info, max_idx, sizeof *column_info);
4410 new_column_info_alloc = max_idx;
4413 /* Allocate the new size_t objects by computing the triangle
4414 formula n * (n + 1) / 2, except that we don't need to
4415 allocate the part of the triangle that we've already
4416 allocated. Check for address arithmetic overflow. */
4418 size_t column_info_growth = new_column_info_alloc - column_info_alloc;
4419 size_t s = column_info_alloc + 1 + new_column_info_alloc;
4420 size_t t = s * column_info_growth;
4421 if (s < new_column_info_alloc || t / column_info_growth != s)
4422 xalloc_die ();
4423 p = xnmalloc (t / 2, sizeof *p);
4426 /* Grow the triangle by parceling out the cells just allocated. */
4427 for (i = column_info_alloc; i < new_column_info_alloc; i++)
4429 column_info[i].col_arr = p;
4430 p += i + 1;
4433 column_info_alloc = new_column_info_alloc;
4436 for (i = 0; i < max_cols; ++i)
4438 size_t j;
4440 column_info[i].valid_len = true;
4441 column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH;
4442 for (j = 0; j <= i; ++j)
4443 column_info[i].col_arr[j] = MIN_COLUMN_WIDTH;
4447 /* Calculate the number of columns needed to represent the current set
4448 of files in the current display width. */
4450 static size_t
4451 calculate_columns (bool by_columns)
4453 size_t filesno; /* Index into cwd_file. */
4454 size_t cols; /* Number of files across. */
4456 /* Normally the maximum number of columns is determined by the
4457 screen width. But if few files are available this might limit it
4458 as well. */
4459 size_t max_cols = MIN (max_idx, cwd_n_used);
4461 init_column_info ();
4463 /* Compute the maximum number of possible columns. */
4464 for (filesno = 0; filesno < cwd_n_used; ++filesno)
4466 struct fileinfo const *f = sorted_file[filesno];
4467 size_t name_length = length_of_file_name_and_frills (f);
4468 size_t i;
4470 for (i = 0; i < max_cols; ++i)
4472 if (column_info[i].valid_len)
4474 size_t idx = (by_columns
4475 ? filesno / ((cwd_n_used + i) / (i + 1))
4476 : filesno % (i + 1));
4477 size_t real_length = name_length + (idx == i ? 0 : 2);
4479 if (column_info[i].col_arr[idx] < real_length)
4481 column_info[i].line_len += (real_length
4482 - column_info[i].col_arr[idx]);
4483 column_info[i].col_arr[idx] = real_length;
4484 column_info[i].valid_len = (column_info[i].line_len
4485 < line_length);
4491 /* Find maximum allowed columns. */
4492 for (cols = max_cols; 1 < cols; --cols)
4494 if (column_info[cols - 1].valid_len)
4495 break;
4498 return cols;
4501 void
4502 usage (int status)
4504 if (status != EXIT_SUCCESS)
4505 fprintf (stderr, _("Try `%s --help' for more information.\n"),
4506 program_name);
4507 else
4509 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
4510 fputs (_("\
4511 List information about the FILEs (the current directory by default).\n\
4512 Sort entries alphabetically if none of -cftuvSUX nor --sort.\n\
4514 "), stdout);
4515 fputs (_("\
4516 Mandatory arguments to long options are mandatory for short options too.\n\
4517 "), stdout);
4518 fputs (_("\
4519 -a, --all do not ignore entries starting with .\n\
4520 -A, --almost-all do not list implied . and ..\n\
4521 --author with -l, print the author of each file\n\
4522 -b, --escape print octal escapes for nongraphic characters\n\
4523 "), stdout);
4524 fputs (_("\
4525 --block-size=SIZE use SIZE-byte blocks\n\
4526 -B, --ignore-backups do not list implied entries ending with ~\n\
4527 -c with -lt: sort by, and show, ctime (time of last\n\
4528 modification of file status information)\n\
4529 with -l: show ctime and sort by name\n\
4530 otherwise: sort by ctime\n\
4531 "), stdout);
4532 fputs (_("\
4533 -C list entries by columns\n\
4534 --color[=WHEN] control whether color is used to distinguish file\n\
4535 types. WHEN may be `never', `always', or `auto'\n\
4536 -d, --directory list directory entries instead of contents,\n\
4537 and do not dereference symbolic links\n\
4538 -D, --dired generate output designed for Emacs' dired mode\n\
4539 "), stdout);
4540 fputs (_("\
4541 -f do not sort, enable -aU, disable -ls --color\n\
4542 -F, --classify append indicator (one of */=>@|) to entries\n\
4543 --file-type likewise, except do not append `*'\n\
4544 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
4545 single-column -1, verbose -l, vertical -C\n\
4546 --full-time like -l --time-style=full-iso\n\
4547 "), stdout);
4548 fputs (_("\
4549 -g like -l, but do not list owner\n\
4550 "), stdout);
4551 fputs (_("\
4552 --group-directories-first\n\
4553 group directories before files.\n\
4554 augment with a --sort option, but any\n\
4555 use of --sort=none (-U) disables grouping\n\
4556 "), stdout);
4557 fputs (_("\
4558 -G, --no-group in a long listing, don't print group names\n\
4559 -h, --human-readable with -l, print sizes in human readable format\n\
4560 (e.g., 1K 234M 2G)\n\
4561 --si likewise, but use powers of 1000 not 1024\n\
4562 "), stdout);
4563 fputs (_("\
4564 -H, --dereference-command-line\n\
4565 follow symbolic links listed on the command line\n\
4566 --dereference-command-line-symlink-to-dir\n\
4567 follow each command line symbolic link\n\
4568 that points to a directory\n\
4569 --hide=PATTERN do not list implied entries matching shell PATTERN\n\
4570 (overridden by -a or -A)\n\
4571 "), stdout);
4572 fputs (_("\
4573 --indicator-style=WORD append indicator with style WORD to entry names:\n\
4574 none (default), slash (-p),\n\
4575 file-type (--file-type), classify (-F)\n\
4576 -i, --inode print the index number of each file\n\
4577 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\n\
4578 -k like --block-size=1K\n\
4579 "), stdout);
4580 fputs (_("\
4581 -l use a long listing format\n\
4582 -L, --dereference when showing file information for a symbolic\n\
4583 link, show information for the file the link\n\
4584 references rather than for the link itself\n\
4585 -m fill width with a comma separated list of entries\n\
4586 "), stdout);
4587 fputs (_("\
4588 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
4589 -N, --literal print raw entry names (don't treat e.g. control\n\
4590 characters specially)\n\
4591 -o like -l, but do not list group information\n\
4592 -p, --indicator-style=slash\n\
4593 append / indicator to directories\n\
4594 "), stdout);
4595 fputs (_("\
4596 -q, --hide-control-chars print ? instead of non graphic characters\n\
4597 --show-control-chars show non graphic characters as-is (default\n\
4598 unless program is `ls' and output is a terminal)\n\
4599 -Q, --quote-name enclose entry names in double quotes\n\
4600 --quoting-style=WORD use quoting style WORD for entry names:\n\
4601 literal, locale, shell, shell-always, c, escape\n\
4602 "), stdout);
4603 fputs (_("\
4604 -r, --reverse reverse order while sorting\n\
4605 -R, --recursive list subdirectories recursively\n\
4606 -s, --size print the allocated size of each file, in blocks\n\
4607 "), stdout);
4608 fputs (_("\
4609 -S sort by file size\n\
4610 --sort=WORD sort by WORD instead of name: none -U,\n\
4611 extension -X, size -S, time -t, version -v\n\
4612 --time=WORD with -l, show time as WORD instead of modification\n\
4613 time: atime -u, access -u, use -u, ctime -c,\n\
4614 or status -c; use specified time as sort key\n\
4615 if --sort=time\n\
4616 "), stdout);
4617 fputs (_("\
4618 --time-style=STYLE with -l, show times using style STYLE:\n\
4619 full-iso, long-iso, iso, locale, +FORMAT.\n\
4620 FORMAT is interpreted like `date'; if FORMAT is\n\
4621 FORMAT1<newline>FORMAT2, FORMAT1 applies to\n\
4622 non-recent files and FORMAT2 to recent files;\n\
4623 if STYLE is prefixed with `posix-', STYLE\n\
4624 takes effect only outside the POSIX locale\n\
4625 "), stdout);
4626 fputs (_("\
4627 -t sort by modification time\n\
4628 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
4629 "), stdout);
4630 fputs (_("\
4631 -u with -lt: sort by, and show, access time\n\
4632 with -l: show access time and sort by name\n\
4633 otherwise: sort by access time\n\
4634 -U do not sort; list entries in directory order\n\
4635 -v natural sort of (version) numbers within text\n\
4636 "), stdout);
4637 fputs (_("\
4638 -w, --width=COLS assume screen width instead of current value\n\
4639 -x list entries by lines instead of by columns\n\
4640 -X sort alphabetically by entry extension\n\
4641 -Z, --context print any SELinux security context of each file\n\
4642 -1 list one file per line\n\
4643 "), stdout);
4644 fputs (HELP_OPTION_DESCRIPTION, stdout);
4645 fputs (VERSION_OPTION_DESCRIPTION, stdout);
4646 fputs (_("\n\
4647 SIZE may be (or may be an integer optionally followed by) one of following:\n\
4648 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
4649 "), stdout);
4650 fputs (_("\
4652 By default, color is not used to distinguish types of files. That is\n\
4653 equivalent to using --color=none. Using the --color option without the\n\
4654 optional WHEN argument is equivalent to using --color=always. With\n\
4655 --color=auto, color codes are output only if standard output is connected\n\
4656 to a terminal (tty). The environment variable LS_COLORS can influence the\n\
4657 colors, and can be set easily by the dircolors command.\n\
4658 "), stdout);
4659 fputs (_("\
4661 Exit status:\n\
4662 0 if OK,\n\
4663 1 if minor problems (e.g., cannot access subdirectory),\n\
4664 2 if serious trouble (e.g., cannot access command-line argument).\n\
4665 "), stdout);
4666 emit_bug_reporting_address ();
4668 exit (status);