1 /* 'dir', 'vdir' and 'ls' directory listing programs for GNU.
2 Copyright (C) 1985-2022 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 <https://www.gnu.org/licenses/>. */
17 /* If ls_mode is LS_MULTI_COL,
18 the multi-column format is the default regardless
19 of the type of output device.
20 This is for the 'dir' program.
22 If ls_mode is LS_LONG_FORMAT,
23 the long format is the default regardless of the
24 type of output device.
25 This is for the 'vdir' program.
28 the output format depends on whether the output
30 This is for the 'ls' program. */
32 /* Written by Richard Stallman and David MacKenzie. */
34 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
35 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
36 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
39 #include <sys/types.h>
45 #include <sys/ioctl.h>
47 #ifdef WINSIZE_IN_PTEM
48 # include <sys/stream.h>
49 # include <sys/ptem.h>
58 #include <selinux/selinux.h>
61 #if HAVE_LANGINFO_CODESET
62 # include <langinfo.h>
65 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
68 # define SA_NOCLDSTOP 0
69 # define sigprocmask(How, Set, Oset) /* empty */
71 # if ! HAVE_SIGINTERRUPT
72 # define siginterrupt(sig, flag) /* empty */
76 /* NonStop circa 2011 lacks both SA_RESTART and siginterrupt, so don't
77 restart syscalls after a signal handler fires. This may cause
78 colors to get messed up on the screen if 'ls' is interrupted, but
79 that's the best we can do on such a platform. */
89 #include "c-strcase.h"
93 #include "filenamecat.h"
94 #include "hard-locale.h"
98 #include "filevercmp.h"
101 #include "mbswidth.h"
106 #include "stat-size.h"
107 #include "stat-time.h"
108 #include "strftime.h"
109 #include "xdectoint.h"
111 #include "xstrtol-error.h"
112 #include "areadlink.h"
113 #include "mbsalign.h"
114 #include "dircolors.h"
115 #include "xgethostname.h"
117 #include "canonicalize.h"
120 /* Include <sys/capability.h> last to avoid a clash of <sys/types.h>
121 include guards with some premature versions of libcap.
122 For more details, see <https://bugzilla.redhat.com/483548>. */
124 # include <sys/capability.h>
127 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
128 : (ls_mode == LS_MULTI_COL \
132 proper_name ("Richard M. Stallman"), \
133 proper_name ("David MacKenzie")
135 #define obstack_chunk_alloc malloc
136 #define obstack_chunk_free free
138 /* Unix-based readdir implementations have historically returned a dirent.d_ino
139 value that is sometimes not equal to the stat-obtained st_ino value for
140 that same entry. This error occurs for a readdir entry that refers
141 to a mount point. readdir's error is to return the inode number of
142 the underlying directory -- one that typically cannot be stat'ed, as
143 long as a file system is mounted on that directory. RELIABLE_D_INO
144 encapsulates whether we can use the more efficient approach of relying
145 on readdir-supplied d_ino values, or whether we must incur the cost of
146 calling stat or lstat to obtain each guaranteed-valid inode number. */
148 #ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
149 # define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
152 #if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
153 # define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
155 # define RELIABLE_D_INO(dp) D_INO (dp)
158 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
159 # define st_author st_uid
176 /* Display letters and indicators for each filetype.
177 Keep these in sync with enum filetype. */
178 static char const filetype_letter
[] = "?pcdb-lswd";
180 /* Ensure that filetype and filetype_letter have the same
181 number of elements. */
182 verify (sizeof filetype_letter
- 1 == arg_directory
+ 1);
184 #define FILETYPE_INDICATORS \
186 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
187 C_LINK, C_SOCK, C_FILE, C_DIR \
193 ACL_T_LSM_CONTEXT_ONLY
,
202 /* For symbolic link, name of the file linked to, otherwise zero. */
205 /* For terminal hyperlinks. */
210 enum filetype filetype
;
212 /* For symbolic link and long listing, st_mode of file linked to, otherwise
216 /* security context. */
221 /* For symbolic link and color printing, true if linked-to file
222 exists, otherwise false. */
225 /* For long listings, true if the file has an access control list,
226 or a security context. */
227 enum acl_type acl_type
;
229 /* For color listings, true if a regular file has capability info. */
232 /* Whether file name needs quoting. tri-state with -1 == unknown. */
235 /* Cached screen width (including quoting). */
239 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
241 /* Null is a valid character in a color indicator (think about Epson
242 printers, for example) so we have to use a length/buffer string
247 size_t len
; /* Number of bytes */
248 char const *string
; /* Pointer to the same */
252 # define tcgetpgrp(Fd) 0
255 static size_t quote_name (char const *name
,
256 struct quoting_options
const *options
,
257 int needs_general_quoting
,
258 const struct bin_str
*color
,
259 bool allow_pad
, struct obstack
*stack
,
260 char const *absolute_name
);
261 static size_t quote_name_buf (char **inbuf
, size_t bufsize
, char *name
,
262 struct quoting_options
const *options
,
263 int needs_general_quoting
, size_t *width
,
265 static char *make_link_name (char const *name
, char const *linkname
);
266 static int decode_switches (int argc
, char **argv
);
267 static bool file_ignored (char const *name
);
268 static uintmax_t gobble_file (char const *name
, enum filetype type
,
269 ino_t inode
, bool command_line_arg
,
270 char const *dirname
);
271 static const struct bin_str
* get_color_indicator (const struct fileinfo
*f
,
272 bool symlink_target
);
273 static bool print_color_indicator (const struct bin_str
*ind
);
274 static void put_indicator (const struct bin_str
*ind
);
275 static void add_ignore_pattern (char const *pattern
);
276 static void attach (char *dest
, char const *dirname
, char const *name
);
277 static void clear_files (void);
278 static void extract_dirs_from_files (char const *dirname
,
279 bool command_line_arg
);
280 static void get_link_name (char const *filename
, struct fileinfo
*f
,
281 bool command_line_arg
);
282 static void indent (size_t from
, size_t to
);
283 static size_t calculate_columns (bool by_columns
);
284 static void print_current_files (void);
285 static void print_dir (char const *name
, char const *realname
,
286 bool command_line_arg
);
287 static size_t print_file_name_and_frills (const struct fileinfo
*f
,
289 static void print_horizontal (void);
290 static int format_user_width (uid_t u
);
291 static int format_group_width (gid_t g
);
292 static void print_long_format (const struct fileinfo
*f
);
293 static void print_many_per_line (void);
294 static size_t print_name_with_quoting (const struct fileinfo
*f
,
296 struct obstack
*stack
,
298 static void prep_non_filename_text (void);
299 static bool print_type_indicator (bool stat_ok
, mode_t mode
,
301 static void print_with_separator (char sep
);
302 static void queue_directory (char const *name
, char const *realname
,
303 bool command_line_arg
);
304 static void sort_files (void);
305 static void parse_ls_color (void);
307 static int getenv_quoting_style (void);
309 static size_t quote_name_width (char const *name
,
310 struct quoting_options
const *options
,
311 int needs_general_quoting
);
313 /* Initial size of hash table.
314 Most hierarchies are likely to be shallower than this. */
315 enum { INITIAL_TABLE_SIZE
= 30 };
317 /* The set of 'active' directories, from the current command-line argument
318 to the level in the hierarchy at which files are being listed.
319 A directory is represented by its device and inode numbers (struct dev_ino).
320 A directory is added to this set when ls begins listing it or its
321 entries, and it is removed from the set just after ls has finished
322 processing it. This set is used solely to detect loops, e.g., with
323 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
324 static Hash_table
*active_dir_set
;
326 #define LOOP_DETECT (!!active_dir_set)
328 /* The table of files in the current directory:
330 'cwd_file' points to a vector of 'struct fileinfo', one per file.
331 'cwd_n_alloc' is the number of elements space has been allocated for.
332 'cwd_n_used' is the number actually in use. */
334 /* Address of block containing the files that are described. */
335 static struct fileinfo
*cwd_file
;
337 /* Length of block that 'cwd_file' points to, measured in files. */
338 static size_t cwd_n_alloc
;
340 /* Index of first unused slot in 'cwd_file'. */
341 static size_t cwd_n_used
;
343 /* Whether files needs may need padding due to quoting. */
344 static bool cwd_some_quoted
;
346 /* Whether quoting style _may_ add outer quotes,
347 and whether aligning those is useful. */
348 static bool align_variable_outer_quotes
;
350 /* Vector of pointers to files, in proper sorted order, and the number
351 of entries allocated for it. */
352 static void **sorted_file
;
353 static size_t sorted_file_alloc
;
355 /* When true, in a color listing, color each symlink name according to the
356 type of file it points to. Otherwise, color them according to the 'ln'
357 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
358 regardless. This is set when 'ln=target' appears in LS_COLORS. */
360 static bool color_symlink_as_referent
;
362 static char const *hostname
;
364 /* Mode of appropriate file for coloring. */
366 file_or_link_mode (struct fileinfo
const *file
)
368 return (color_symlink_as_referent
&& file
->linkok
369 ? file
->linkmode
: file
->stat
.st_mode
);
373 /* Record of one pending directory waiting to be listed. */
378 /* If the directory is actually the file pointed to by a symbolic link we
379 were told to list, 'realname' will contain the name of the symbolic
380 link, otherwise zero. */
382 bool command_line_arg
;
383 struct pending
*next
;
386 static struct pending
*pending_dirs
;
388 /* Current time in seconds and nanoseconds since 1970, updated as
389 needed when deciding whether a file is recent. */
391 static struct timespec current_time
;
393 static bool print_scontext
;
394 static char UNKNOWN_SECURITY_CONTEXT
[] = "?";
396 /* Whether any of the files has an ACL. This affects the width of the
399 static bool any_has_acl
;
401 /* The number of columns to use for columns containing inode numbers,
402 block sizes, link counts, owners, groups, authors, major device
403 numbers, minor device numbers, and file sizes, respectively. */
405 static int inode_number_width
;
406 static int block_size_width
;
407 static int nlink_width
;
408 static int scontext_width
;
409 static int owner_width
;
410 static int group_width
;
411 static int author_width
;
412 static int major_device_number_width
;
413 static int minor_device_number_width
;
414 static int file_size_width
;
418 /* long_format for lots of info, one per line.
419 one_per_line for just names, one per line.
420 many_per_line for just names, many per line, sorted vertically.
421 horizontal for just names, many per line, sorted horizontally.
422 with_commas for just names, many per line, separated by commas.
424 -l (and other options that imply -l), -1, -C, -x and -m control
429 long_format
, /* -l and other options that imply -l */
430 one_per_line
, /* -1 */
431 many_per_line
, /* -C */
436 static enum format format
;
438 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
439 ISO-style timestamps, though shorter than 'full-iso'. 'iso' uses shorter
440 ISO-style timestamps. 'locale' uses locale-dependent timestamps. */
443 full_iso_time_style
, /* --time-style=full-iso */
444 long_iso_time_style
, /* --time-style=long-iso */
445 iso_time_style
, /* --time-style=iso */
446 locale_time_style
/* --time-style=locale */
449 static char const *const time_style_args
[] =
451 "full-iso", "long-iso", "iso", "locale", NULL
453 static enum time_style
const time_style_types
[] =
455 full_iso_time_style
, long_iso_time_style
, iso_time_style
,
458 ARGMATCH_VERIFY (time_style_args
, time_style_types
);
460 /* Type of time to print or sort by. Controlled by -c and -u.
461 The values of each item of this enum are important since they are
462 used as indices in the sort functions array (see sort_files()). */
466 time_mtime
= 0, /* default */
469 time_btime
, /* birth time */
470 time_numtypes
/* the number of elements of this enum */
473 static enum time_type time_type
;
475 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
476 The values of each item of this enum are important since they are
477 used as indices in the sort functions array (see sort_files()). */
481 sort_name
= 0, /* default */
482 sort_extension
, /* -X */
485 sort_version
, /* -v */
486 sort_time
, /* -t; must be second to last */
487 sort_none
, /* -U; must be last */
488 sort_numtypes
/* the number of elements of this enum */
491 static enum sort_type sort_type
;
493 /* Direction of sort.
494 false means highest first if numeric,
495 lowest first if alphabetic;
496 these are the defaults.
497 true means the opposite order in each case. -r */
499 static bool sort_reverse
;
501 /* True means to display owner information. -g turns this off. */
503 static bool print_owner
= true;
505 /* True means to display author information. */
507 static bool print_author
;
509 /* True means to display group information. -G and -o turn this off. */
511 static bool print_group
= true;
513 /* True means print the user and group id's as numbers rather
516 static bool numeric_ids
;
518 /* True means mention the size in blocks of each file. -s */
520 static bool print_block_size
;
522 /* Human-readable options for output, when printing block counts. */
523 static int human_output_opts
;
525 /* The units to use when printing block counts. */
526 static uintmax_t output_block_size
;
528 /* Likewise, but for file sizes. */
529 static int file_human_output_opts
;
530 static uintmax_t file_output_block_size
= 1;
532 /* Follow the output with a special string. Using this format,
533 Emacs' dired mode starts up twice as fast, and can handle all
534 strange characters in file names. */
537 /* 'none' means don't mention the type of files.
538 'slash' means mention directories only, with a '/'.
539 'file_type' means mention file types.
540 'classify' means mention file types and mark executables.
542 Controlled by -F, -p, and --indicator-style. */
546 none
= 0, /* --indicator-style=none (default) */
547 slash
, /* -p, --indicator-style=slash */
548 file_type
, /* --indicator-style=file-type */
549 classify
/* -F, --indicator-style=classify */
552 static enum indicator_style indicator_style
;
554 /* Names of indicator styles. */
555 static char const *const indicator_style_args
[] =
557 "none", "slash", "file-type", "classify", NULL
559 static enum indicator_style
const indicator_style_types
[] =
561 none
, slash
, file_type
, classify
563 ARGMATCH_VERIFY (indicator_style_args
, indicator_style_types
);
565 /* True means use colors to mark types. Also define the different
566 colors as well as the stuff for the LS_COLORS environment variable.
567 The LS_COLORS variable is now in a termcap-like format. */
569 static bool print_with_color
;
571 static bool print_hyperlink
;
573 /* Whether we used any colors in the output so far. If so, we will
574 need to restore the default color later. If not, we will need to
575 call prep_non_filename_text before using color for the first time. */
577 static bool used_color
= false;
581 when_never
, /* 0: default or --color=never */
582 when_always
, /* 1: --color=always */
583 when_if_tty
/* 2: --color=tty */
586 enum Dereference_symlink
588 DEREF_UNDEFINED
= 0, /* default */
590 DEREF_COMMAND_LINE_ARGUMENTS
, /* -H */
591 DEREF_COMMAND_LINE_SYMLINK_TO_DIR
, /* the default, in certain cases */
592 DEREF_ALWAYS
/* -L */
597 C_LEFT
, C_RIGHT
, C_END
, C_RESET
, C_NORM
, C_FILE
, C_DIR
, C_LINK
,
599 C_BLK
, C_CHR
, C_MISSING
, C_ORPHAN
, C_EXEC
, C_DOOR
, C_SETUID
, C_SETGID
,
600 C_STICKY
, C_OTHER_WRITABLE
, C_STICKY_OTHER_WRITABLE
, C_CAP
, C_MULTIHARDLINK
,
604 static char const *const indicator_name
[]=
606 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
607 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
608 "ow", "tw", "ca", "mh", "cl", NULL
611 struct color_ext_type
613 struct bin_str ext
; /* The extension we're looking for */
614 struct bin_str seq
; /* The sequence to output when we do */
615 struct color_ext_type
*next
; /* Next in list */
618 static struct bin_str color_indicator
[] =
620 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
621 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
622 { 0, NULL
}, /* ec: End color (replaces lc+rs+rc) */
623 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
624 { 0, NULL
}, /* no: Normal */
625 { 0, NULL
}, /* fi: File: default */
626 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
627 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
628 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
629 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
630 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
631 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
632 { 0, NULL
}, /* mi: Missing file: undefined */
633 { 0, NULL
}, /* or: Orphaned symlink: undefined */
634 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
635 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
636 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
637 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
638 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
639 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
640 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
641 { LEN_STR_PAIR ("30;41") }, /* ca: black on red */
642 { 0, NULL
}, /* mh: disabled by default */
643 { LEN_STR_PAIR ("\033[K") }, /* cl: clear to end of line */
647 static struct color_ext_type
*color_ext_list
= NULL
;
649 /* Buffer for color sequences */
650 static char *color_buf
;
652 /* True means to check for orphaned symbolic link, for displaying
653 colors, or to group symlink to directories with other dirs. */
655 static bool check_symlink_mode
;
657 /* True means mention the inode number of each file. -i */
659 static bool print_inode
;
661 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
662 other options that imply -l), and -L. */
664 static enum Dereference_symlink dereference
;
666 /* True means when a directory is found, display info on its
669 static bool recursive
;
671 /* True means when an argument is a directory name, display info
674 static bool immediate_dirs
;
676 /* True means that directories are grouped before files. */
678 static bool directories_first
;
680 /* Which files to ignore. */
684 /* Ignore files whose names start with '.', and files specified by
685 --hide and --ignore. */
688 /* Ignore '.', '..', and files specified by --ignore. */
689 IGNORE_DOT_AND_DOTDOT
,
691 /* Ignore only files specified by --ignore. */
695 /* A linked list of shell-style globbing patterns. If a non-argument
696 file name matches any of these patterns, it is ignored.
697 Controlled by -I. Multiple -I options accumulate.
698 The -B option adds '*~' and '.*~' to this list. */
700 struct ignore_pattern
703 struct ignore_pattern
*next
;
706 static struct ignore_pattern
*ignore_patterns
;
708 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
709 variable itself to be ignored. */
710 static struct ignore_pattern
*hide_patterns
;
712 /* True means output nongraphic chars in file names as '?'.
713 (-q, --hide-control-chars)
714 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
715 independent. The algorithm is: first, obey the quoting style to get a
716 string representing the file name; then, if qmark_funny_chars is set,
717 replace all nonprintable chars in that string with '?'. It's necessary
718 to replace nonprintable chars even in quoted strings, because we don't
719 want to mess up the terminal if control chars get sent to it, and some
720 quoting methods pass through control chars as-is. */
721 static bool qmark_funny_chars
;
723 /* Quoting options for file and dir name output. */
725 static struct quoting_options
*filename_quoting_options
;
726 static struct quoting_options
*dirname_quoting_options
;
728 /* The number of chars per hardware tab stop. Setting this to zero
729 inhibits the use of TAB characters for separating columns. -T */
730 static size_t tabsize
;
732 /* True means print each directory name before listing it. */
734 static bool print_dir_name
;
736 /* The line length to use for breaking lines in many-per-line format.
737 Can be set with -w. If zero, there is no limit. */
739 static size_t line_length
;
741 /* The local time zone rules, as per the TZ environment variable. */
743 static timezone_t localtz
;
745 /* If true, the file listing format requires that stat be called on
748 static bool format_needs_stat
;
750 /* Similar to 'format_needs_stat', but set if only the file type is
753 static bool format_needs_type
;
755 /* An arbitrary limit on the number of bytes in a printed timestamp.
756 This is set to a relatively small value to avoid the need to worry
757 about denial-of-service attacks on servers that run "ls" on behalf
758 of remote clients. 1000 bytes should be enough for any practical
761 enum { TIME_STAMP_LEN_MAXIMUM
= MAX (1000, INT_STRLEN_BOUND (time_t)) };
763 /* strftime formats for non-recent and recent files, respectively, in
766 static char const *long_time_format
[2] =
768 /* strftime format for non-recent files (older than 6 months), in
769 -l output. This should contain the year, month and day (at
770 least), in an order that is understood by people in your
771 locale's territory. Please try to keep the number of used
772 screen columns small, because many people work in windows with
773 only 80 columns. But make this as wide as the other string
774 below, for recent files. */
775 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
776 so be wary of using variable width fields from the locale.
777 Note %b is handled specially by ls and aligned correctly.
778 Note also that specifying a width as in %5b is erroneous as strftime
779 will count bytes rather than characters in multibyte locales. */
781 /* strftime format for recent files (younger than 6 months), in -l
782 output. This should contain the month, day and time (at
783 least), in an order that is understood by people in your
784 locale's territory. Please try to keep the number of used
785 screen columns small, because many people work in windows with
786 only 80 columns. But make this as wide as the other string
787 above, for non-recent files. */
788 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
789 so be wary of using variable width fields from the locale.
790 Note %b is handled specially by ls and aligned correctly.
791 Note also that specifying a width as in %5b is erroneous as strftime
792 will count bytes rather than characters in multibyte locales. */
796 /* The set of signals that are caught. */
798 static sigset_t caught_signals
;
800 /* If nonzero, the value of the pending fatal signal. */
802 static sig_atomic_t volatile interrupt_signal
;
804 /* A count of the number of pending stop signals that have been received. */
806 static sig_atomic_t volatile stop_signal_count
;
808 /* Desired exit status. */
810 static int exit_status
;
815 /* "ls" had a minor problem. E.g., while processing a directory,
816 ls obtained the name of an entry via readdir, yet was later
817 unable to stat that name. This happens when listing a directory
818 in which entries are actively being removed or renamed. */
819 LS_MINOR_PROBLEM
= 1,
821 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
822 option or failure to stat a command line argument. */
826 /* For long options that have no equivalent short option, use a
827 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
830 AUTHOR_OPTION
= CHAR_MAX
+ 1,
833 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
,
834 FILE_TYPE_INDICATOR_OPTION
,
837 GROUP_DIRECTORIES_FIRST_OPTION
,
840 INDICATOR_STYLE_OPTION
,
841 QUOTING_STYLE_OPTION
,
842 SHOW_CONTROL_CHARS_OPTION
,
850 static struct option
const long_options
[] =
852 {"all", no_argument
, NULL
, 'a'},
853 {"escape", no_argument
, NULL
, 'b'},
854 {"directory", no_argument
, NULL
, 'd'},
855 {"dired", no_argument
, NULL
, 'D'},
856 {"full-time", no_argument
, NULL
, FULL_TIME_OPTION
},
857 {"group-directories-first", no_argument
, NULL
,
858 GROUP_DIRECTORIES_FIRST_OPTION
},
859 {"human-readable", no_argument
, NULL
, 'h'},
860 {"inode", no_argument
, NULL
, 'i'},
861 {"kibibytes", no_argument
, NULL
, 'k'},
862 {"numeric-uid-gid", no_argument
, NULL
, 'n'},
863 {"no-group", no_argument
, NULL
, 'G'},
864 {"hide-control-chars", no_argument
, NULL
, 'q'},
865 {"reverse", no_argument
, NULL
, 'r'},
866 {"size", no_argument
, NULL
, 's'},
867 {"width", required_argument
, NULL
, 'w'},
868 {"almost-all", no_argument
, NULL
, 'A'},
869 {"ignore-backups", no_argument
, NULL
, 'B'},
870 {"classify", optional_argument
, NULL
, 'F'},
871 {"file-type", no_argument
, NULL
, FILE_TYPE_INDICATOR_OPTION
},
872 {"si", no_argument
, NULL
, SI_OPTION
},
873 {"dereference-command-line", no_argument
, NULL
, 'H'},
874 {"dereference-command-line-symlink-to-dir", no_argument
, NULL
,
875 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
},
876 {"hide", required_argument
, NULL
, HIDE_OPTION
},
877 {"ignore", required_argument
, NULL
, 'I'},
878 {"indicator-style", required_argument
, NULL
, INDICATOR_STYLE_OPTION
},
879 {"dereference", no_argument
, NULL
, 'L'},
880 {"literal", no_argument
, NULL
, 'N'},
881 {"quote-name", no_argument
, NULL
, 'Q'},
882 {"quoting-style", required_argument
, NULL
, QUOTING_STYLE_OPTION
},
883 {"recursive", no_argument
, NULL
, 'R'},
884 {"format", required_argument
, NULL
, FORMAT_OPTION
},
885 {"show-control-chars", no_argument
, NULL
, SHOW_CONTROL_CHARS_OPTION
},
886 {"sort", required_argument
, NULL
, SORT_OPTION
},
887 {"tabsize", required_argument
, NULL
, 'T'},
888 {"time", required_argument
, NULL
, TIME_OPTION
},
889 {"time-style", required_argument
, NULL
, TIME_STYLE_OPTION
},
890 {"zero", no_argument
, NULL
, ZERO_OPTION
},
891 {"color", optional_argument
, NULL
, COLOR_OPTION
},
892 {"hyperlink", optional_argument
, NULL
, HYPERLINK_OPTION
},
893 {"block-size", required_argument
, NULL
, BLOCK_SIZE_OPTION
},
894 {"context", no_argument
, 0, 'Z'},
895 {"author", no_argument
, NULL
, AUTHOR_OPTION
},
896 {GETOPT_HELP_OPTION_DECL
},
897 {GETOPT_VERSION_OPTION_DECL
},
901 static char const *const format_args
[] =
903 "verbose", "long", "commas", "horizontal", "across",
904 "vertical", "single-column", NULL
906 static enum format
const format_types
[] =
908 long_format
, long_format
, with_commas
, horizontal
, horizontal
,
909 many_per_line
, one_per_line
911 ARGMATCH_VERIFY (format_args
, format_types
);
913 static char const *const sort_args
[] =
915 "none", "time", "size", "extension", "version", "width", NULL
917 static enum sort_type
const sort_types
[] =
919 sort_none
, sort_time
, sort_size
, sort_extension
, sort_version
, sort_width
921 ARGMATCH_VERIFY (sort_args
, sort_types
);
923 static char const *const time_args
[] =
925 "atime", "access", "use",
930 static enum time_type
const time_types
[] =
932 time_atime
, time_atime
, time_atime
,
933 time_ctime
, time_ctime
,
934 time_btime
, time_btime
,
936 ARGMATCH_VERIFY (time_args
, time_types
);
938 static char const *const when_args
[] =
940 /* force and none are for compatibility with another color-ls version */
941 "always", "yes", "force",
942 "never", "no", "none",
943 "auto", "tty", "if-tty", NULL
945 static enum when_type
const when_types
[] =
947 when_always
, when_always
, when_always
,
948 when_never
, when_never
, when_never
,
949 when_if_tty
, when_if_tty
, when_if_tty
951 ARGMATCH_VERIFY (when_args
, when_types
);
953 /* Information about filling a column. */
961 /* Array with information about column filledness. */
962 static struct column_info
*column_info
;
964 /* Maximum number of columns ever possible for this display. */
965 static size_t max_idx
;
967 /* The minimum width of a column is 3: 1 character for the name and 2
968 for the separating white space. */
969 enum { MIN_COLUMN_WIDTH
= 3 };
972 /* This zero-based index is for the --dired option. It is incremented
973 for each byte of output generated by this program so that the beginning
974 and ending indices (in that output) of every file name can be recorded
975 and later output themselves. */
976 static off_t dired_pos
;
979 dired_outbyte (char c
)
985 /* Output the buffer S, of length S_LEN, and increment DIRED_POS by S_LEN. */
987 dired_outbuf (char const *s
, size_t s_len
)
990 fwrite (s
, sizeof *s
, s_len
, stdout
);
993 /* Output the string S, and increment DIRED_POS by its length. */
995 dired_outstring (char const *s
)
997 dired_outbuf (s
, strlen (s
));
1004 dired_outstring (" ");
1007 /* With --dired, store pairs of beginning and ending indices of file names. */
1008 static struct obstack dired_obstack
;
1010 /* With --dired, store pairs of beginning and ending indices of any
1011 directory names that appear as headers (just before 'total' line)
1012 for lists of directory entries. Such directory names are seen when
1013 listing hierarchies using -R and when a directory is listed with at
1014 least one other command line argument. */
1015 static struct obstack subdired_obstack
;
1017 /* Save the current index on the specified obstack, OBS. */
1019 push_current_dired_pos (struct obstack
*obs
)
1022 obstack_grow (obs
, &dired_pos
, sizeof dired_pos
);
1025 /* With -R, this stack is used to help detect directory cycles.
1026 The device/inode pairs on this stack mirror the pairs in the
1027 active_dir_set hash table. */
1028 static struct obstack dev_ino_obstack
;
1030 /* Push a pair onto the device/inode stack. */
1032 dev_ino_push (dev_t dev
, ino_t ino
)
1036 int dev_ino_size
= sizeof *di
;
1037 obstack_blank (&dev_ino_obstack
, dev_ino_size
);
1038 vdi
= obstack_next_free (&dev_ino_obstack
);
1045 /* Pop a dev/ino struct off the global dev_ino_obstack
1046 and return that struct. */
1047 static struct dev_ino
1052 int dev_ino_size
= sizeof *di
;
1053 assert (dev_ino_size
<= obstack_object_size (&dev_ino_obstack
));
1054 obstack_blank_fast (&dev_ino_obstack
, -dev_ino_size
);
1055 vdi
= obstack_next_free (&dev_ino_obstack
);
1061 assert_matching_dev_ino (char const *name
, struct dev_ino di
)
1065 assert (0 <= stat (name
, &sb
));
1066 assert (sb
.st_dev
== di
.st_dev
);
1067 assert (sb
.st_ino
== di
.st_ino
);
1070 static char eolbyte
= '\n';
1072 /* Write to standard output PREFIX, followed by the quoting style and
1073 a space-separated list of the integers stored in OS all on one line. */
1076 dired_dump_obstack (char const *prefix
, struct obstack
*os
)
1080 n_pos
= obstack_object_size (os
) / sizeof (dired_pos
);
1083 off_t
*pos
= obstack_finish (os
);
1084 fputs (prefix
, stdout
);
1085 for (size_t i
= 0; i
< n_pos
; i
++)
1087 intmax_t p
= pos
[i
];
1088 printf (" %"PRIdMAX
, p
);
1094 /* Return the platform birthtime member of the stat structure,
1095 or fallback to the mtime member, which we have populated
1096 from the statx structure or reset to an invalid timestamp
1097 where birth time is not supported. */
1098 static struct timespec
1099 get_stat_btime (struct stat
const *st
)
1101 struct timespec btimespec
;
1103 #if HAVE_STATX && defined STATX_INO
1104 btimespec
= get_stat_mtime (st
);
1106 btimespec
= get_stat_birthtime (st
);
1112 #if HAVE_STATX && defined STATX_INO
1115 time_type_to_statx (void)
1135 calc_req_mask (void)
1137 unsigned int mask
= STATX_MODE
;
1142 if (print_block_size
)
1143 mask
|= STATX_BLOCKS
;
1145 if (format
== long_format
) {
1146 mask
|= STATX_NLINK
| STATX_SIZE
| time_type_to_statx ();
1147 if (print_owner
|| print_author
)
1158 case sort_extension
:
1162 mask
|= time_type_to_statx ();
1175 do_statx (int fd
, char const *name
, struct stat
*st
, int flags
,
1179 bool want_btime
= mask
& STATX_BTIME
;
1180 int ret
= statx (fd
, name
, flags
, mask
, &stx
);
1183 statx_to_stat (&stx
, st
);
1184 /* Since we only need one timestamp type,
1185 store birth time in st_mtim. */
1188 if (stx
.stx_mask
& STATX_BTIME
)
1189 st
->st_mtim
= statx_timestamp_to_timespec (stx
.stx_btime
);
1191 st
->st_mtim
.tv_sec
= st
->st_mtim
.tv_nsec
= -1;
1199 do_stat (char const *name
, struct stat
*st
)
1201 return do_statx (AT_FDCWD
, name
, st
, 0, calc_req_mask ());
1205 do_lstat (char const *name
, struct stat
*st
)
1207 return do_statx (AT_FDCWD
, name
, st
, AT_SYMLINK_NOFOLLOW
, calc_req_mask ());
1211 stat_for_mode (char const *name
, struct stat
*st
)
1213 return do_statx (AT_FDCWD
, name
, st
, 0, STATX_MODE
);
1216 /* dev+ino should be static, so no need to sync with backing store */
1218 stat_for_ino (char const *name
, struct stat
*st
)
1220 return do_statx (AT_FDCWD
, name
, st
, 0, STATX_INO
);
1224 fstat_for_ino (int fd
, struct stat
*st
)
1226 return do_statx (fd
, "", st
, AT_EMPTY_PATH
, STATX_INO
);
1230 do_stat (char const *name
, struct stat
*st
)
1232 return stat (name
, st
);
1236 do_lstat (char const *name
, struct stat
*st
)
1238 return lstat (name
, st
);
1242 stat_for_mode (char const *name
, struct stat
*st
)
1244 return stat (name
, st
);
1248 stat_for_ino (char const *name
, struct stat
*st
)
1250 return stat (name
, st
);
1254 fstat_for_ino (int fd
, struct stat
*st
)
1256 return fstat (fd
, st
);
1260 /* Return the address of the first plain %b spec in FMT, or NULL if
1261 there is no such spec. %5b etc. do not match, so that user
1262 widths/flags are honored. */
1266 first_percent_b (char const *fmt
)
1272 case 'b': return fmt
;
1273 case '%': fmt
++; break;
1278 static char RFC3986
[256];
1280 file_escape_init (void)
1282 for (int i
= 0; i
< 256; i
++)
1283 RFC3986
[i
] |= c_isalnum (i
) || i
== '~' || i
== '-' || i
== '.' || i
== '_';
1286 /* Read the abbreviated month names from the locale, to align them
1287 and to determine the max width of the field and to truncate names
1288 greater than our max allowed.
1289 Note even though this handles multibyte locales correctly
1290 it's not restricted to them as single byte locales can have
1291 variable width abbreviated months and also precomputing/caching
1292 the names was seen to increase the performance of ls significantly. */
1294 /* max number of display cells to use.
1295 As of 2018 the abmon for Arabic has entries with width 12.
1296 It doesn't make much sense to support wider than this
1297 and locales should aim for abmon entries of width <= 5. */
1298 enum { MAX_MON_WIDTH
= 12 };
1299 /* abformat[RECENT][MON] is the format to use for timestamps with
1300 recentness RECENT and month MON. */
1301 enum { ABFORMAT_SIZE
= 128 };
1302 static char abformat
[2][12][ABFORMAT_SIZE
];
1303 /* True if precomputed formats should be used. This can be false if
1304 nl_langinfo fails, if a format or month abbreviation is unusually
1305 long, or if a month abbreviation contains '%'. */
1306 static bool use_abformat
;
1308 /* Store into ABMON the abbreviated month names, suitably aligned.
1309 Return true if successful. */
1312 abmon_init (char abmon
[12][ABFORMAT_SIZE
])
1314 #ifndef HAVE_NL_LANGINFO
1317 size_t required_mon_width
= MAX_MON_WIDTH
;
1318 size_t curr_max_width
;
1321 curr_max_width
= required_mon_width
;
1322 required_mon_width
= 0;
1323 for (int i
= 0; i
< 12; i
++)
1325 size_t width
= curr_max_width
;
1326 char const *abbr
= nl_langinfo (ABMON_1
+ i
);
1327 if (strchr (abbr
, '%'))
1329 mbs_align_t alignment
= isdigit (to_uchar (*abbr
))
1330 ? MBS_ALIGN_RIGHT
: MBS_ALIGN_LEFT
;
1331 size_t req
= mbsalign (abbr
, abmon
[i
], ABFORMAT_SIZE
,
1332 &width
, alignment
, 0);
1333 if (! (req
< ABFORMAT_SIZE
))
1335 required_mon_width
= MAX (required_mon_width
, width
);
1338 while (curr_max_width
> required_mon_width
);
1344 /* Initialize ABFORMAT and USE_ABFORMAT. */
1347 abformat_init (void)
1350 for (int recent
= 0; recent
< 2; recent
++)
1351 pb
[recent
] = first_percent_b (long_time_format
[recent
]);
1352 if (! (pb
[0] || pb
[1]))
1355 char abmon
[12][ABFORMAT_SIZE
];
1356 if (! abmon_init (abmon
))
1359 for (int recent
= 0; recent
< 2; recent
++)
1361 char const *fmt
= long_time_format
[recent
];
1362 for (int i
= 0; i
< 12; i
++)
1364 char *nfmt
= abformat
[recent
][i
];
1368 nbytes
= snprintf (nfmt
, ABFORMAT_SIZE
, "%s", fmt
);
1371 if (! (pb
[recent
] - fmt
<= MIN (ABFORMAT_SIZE
, INT_MAX
)))
1373 int prefix_len
= pb
[recent
] - fmt
;
1374 nbytes
= snprintf (nfmt
, ABFORMAT_SIZE
, "%.*s%s%s",
1375 prefix_len
, fmt
, abmon
[i
], pb
[recent
] + 2);
1378 if (! (0 <= nbytes
&& nbytes
< ABFORMAT_SIZE
))
1383 use_abformat
= true;
1387 dev_ino_hash (void const *x
, size_t table_size
)
1389 struct dev_ino
const *p
= x
;
1390 return (uintmax_t) p
->st_ino
% table_size
;
1394 dev_ino_compare (void const *x
, void const *y
)
1396 struct dev_ino
const *a
= x
;
1397 struct dev_ino
const *b
= y
;
1398 return SAME_INODE (*a
, *b
) ? true : false;
1402 dev_ino_free (void *x
)
1407 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1408 active directories. Return true if there is already a matching
1409 entry in the table. */
1412 visit_dir (dev_t dev
, ino_t ino
)
1414 struct dev_ino
*ent
;
1415 struct dev_ino
*ent_from_table
;
1418 ent
= xmalloc (sizeof *ent
);
1422 /* Attempt to insert this entry into the table. */
1423 ent_from_table
= hash_insert (active_dir_set
, ent
);
1425 if (ent_from_table
== NULL
)
1427 /* Insertion failed due to lack of memory. */
1431 found_match
= (ent_from_table
!= ent
);
1435 /* ent was not inserted, so free it. */
1443 free_pending_ent (struct pending
*p
)
1451 is_colored (enum indicator_no type
)
1453 size_t len
= color_indicator
[type
].len
;
1454 char const *s
= color_indicator
[type
].string
;
1456 || (len
== 1 && STRNCMP_LIT (s
, "0") == 0)
1457 || (len
== 2 && STRNCMP_LIT (s
, "00") == 0));
1461 restore_default_color (void)
1463 put_indicator (&color_indicator
[C_LEFT
]);
1464 put_indicator (&color_indicator
[C_RIGHT
]);
1468 set_normal_color (void)
1470 if (print_with_color
&& is_colored (C_NORM
))
1472 put_indicator (&color_indicator
[C_LEFT
]);
1473 put_indicator (&color_indicator
[C_NORM
]);
1474 put_indicator (&color_indicator
[C_RIGHT
]);
1478 /* An ordinary signal was received; arrange for the program to exit. */
1481 sighandler (int sig
)
1484 signal (sig
, SIG_IGN
);
1485 if (! interrupt_signal
)
1486 interrupt_signal
= sig
;
1489 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1492 stophandler (int sig
)
1495 signal (sig
, stophandler
);
1496 if (! interrupt_signal
)
1497 stop_signal_count
++;
1500 /* Process any pending signals. If signals are caught, this function
1501 should be called periodically. Ideally there should never be an
1502 unbounded amount of time when signals are not being processed.
1503 Signal handling can restore the default colors, so callers must
1504 immediately change colors after invoking this function. */
1507 process_signals (void)
1509 while (interrupt_signal
|| stop_signal_count
)
1516 restore_default_color ();
1519 sigprocmask (SIG_BLOCK
, &caught_signals
, &oldset
);
1521 /* Reload interrupt_signal and stop_signal_count, in case a new
1522 signal was handled before sigprocmask took effect. */
1523 sig
= interrupt_signal
;
1524 stops
= stop_signal_count
;
1526 /* SIGTSTP is special, since the application can receive that signal
1527 more than once. In this case, don't set the signal handler to the
1528 default. Instead, just raise the uncatchable SIGSTOP. */
1531 stop_signal_count
= stops
- 1;
1535 signal (sig
, SIG_DFL
);
1537 /* Exit or suspend the program. */
1539 sigprocmask (SIG_SETMASK
, &oldset
, NULL
);
1541 /* If execution reaches here, then the program has been
1542 continued (after being suspended). */
1546 /* Setup signal handlers if INIT is true,
1547 otherwise restore to the default. */
1550 signal_setup (bool init
)
1552 /* The signals that are trapped, and the number of such signals. */
1553 static int const sig
[] =
1555 /* This one is handled specially. */
1558 /* The usual suspects. */
1559 SIGALRM
, SIGHUP
, SIGINT
, SIGPIPE
, SIGQUIT
, SIGTERM
,
1576 enum { nsigs
= ARRAY_CARDINALITY (sig
) };
1579 static bool caught_sig
[nsigs
];
1587 struct sigaction act
;
1589 sigemptyset (&caught_signals
);
1590 for (j
= 0; j
< nsigs
; j
++)
1592 sigaction (sig
[j
], NULL
, &act
);
1593 if (act
.sa_handler
!= SIG_IGN
)
1594 sigaddset (&caught_signals
, sig
[j
]);
1597 act
.sa_mask
= caught_signals
;
1598 act
.sa_flags
= SA_RESTART
;
1600 for (j
= 0; j
< nsigs
; j
++)
1601 if (sigismember (&caught_signals
, sig
[j
]))
1603 act
.sa_handler
= sig
[j
] == SIGTSTP
? stophandler
: sighandler
;
1604 sigaction (sig
[j
], &act
, NULL
);
1607 for (j
= 0; j
< nsigs
; j
++)
1609 caught_sig
[j
] = (signal (sig
[j
], SIG_IGN
) != SIG_IGN
);
1612 signal (sig
[j
], sig
[j
] == SIGTSTP
? stophandler
: sighandler
);
1613 siginterrupt (sig
[j
], 0);
1621 for (j
= 0; j
< nsigs
; j
++)
1622 if (sigismember (&caught_signals
, sig
[j
]))
1623 signal (sig
[j
], SIG_DFL
);
1625 for (j
= 0; j
< nsigs
; j
++)
1627 signal (sig
[j
], SIG_DFL
);
1635 signal_setup (true);
1639 signal_restore (void)
1641 signal_setup (false);
1645 main (int argc
, char **argv
)
1648 struct pending
*thispend
;
1651 initialize_main (&argc
, &argv
);
1652 set_program_name (argv
[0]);
1653 setlocale (LC_ALL
, "");
1654 bindtextdomain (PACKAGE
, LOCALEDIR
);
1655 textdomain (PACKAGE
);
1657 initialize_exit_failure (LS_FAILURE
);
1658 atexit (close_stdout
);
1660 assert (ARRAY_CARDINALITY (color_indicator
) + 1
1661 == ARRAY_CARDINALITY (indicator_name
));
1663 exit_status
= EXIT_SUCCESS
;
1664 print_dir_name
= true;
1665 pending_dirs
= NULL
;
1667 current_time
.tv_sec
= TYPE_MINIMUM (time_t);
1668 current_time
.tv_nsec
= -1;
1670 i
= decode_switches (argc
, argv
);
1672 if (print_with_color
)
1675 /* Test print_with_color again, because the call to parse_ls_color
1676 may have just reset it -- e.g., if LS_COLORS is invalid. */
1678 if (print_with_color
)
1680 /* Don't use TAB characters in output. Some terminal
1681 emulators can't handle the combination of tabs and
1682 color codes on the same line. */
1686 if (directories_first
)
1687 check_symlink_mode
= true;
1688 else if (print_with_color
)
1690 /* Avoid following symbolic links when possible. */
1691 if (is_colored (C_ORPHAN
)
1692 || (is_colored (C_EXEC
) && color_symlink_as_referent
)
1693 || (is_colored (C_MISSING
) && format
== long_format
))
1694 check_symlink_mode
= true;
1697 if (dereference
== DEREF_UNDEFINED
)
1698 dereference
= ((immediate_dirs
1699 || indicator_style
== classify
1700 || format
== long_format
)
1702 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR
);
1704 /* When using -R, initialize a data structure we'll use to
1705 detect any directory cycles. */
1708 active_dir_set
= hash_initialize (INITIAL_TABLE_SIZE
, NULL
,
1712 if (active_dir_set
== NULL
)
1715 obstack_init (&dev_ino_obstack
);
1718 localtz
= tzalloc (getenv ("TZ"));
1720 format_needs_stat
= sort_type
== sort_time
|| sort_type
== sort_size
1721 || format
== long_format
1723 || print_block_size
;
1724 format_needs_type
= (! format_needs_stat
1727 || indicator_style
!= none
1728 || directories_first
));
1732 obstack_init (&dired_obstack
);
1733 obstack_init (&subdired_obstack
);
1736 if (print_hyperlink
)
1738 file_escape_init ();
1740 hostname
= xgethostname ();
1741 /* The hostname is generally ignored,
1742 so ignore failures obtaining it. */
1748 cwd_file
= xnmalloc (cwd_n_alloc
, sizeof *cwd_file
);
1758 gobble_file (".", directory
, NOT_AN_INODE_NUMBER
, true, "");
1760 queue_directory (".", NULL
, true);
1764 gobble_file (argv
[i
++], unknown
, NOT_AN_INODE_NUMBER
, true, "");
1770 if (!immediate_dirs
)
1771 extract_dirs_from_files (NULL
, true);
1772 /* 'cwd_n_used' might be zero now. */
1775 /* In the following if/else blocks, it is sufficient to test 'pending_dirs'
1776 (and not pending_dirs->name) because there may be no markers in the queue
1777 at this point. A marker may be enqueued when extract_dirs_from_files is
1778 called with a non-empty string or via print_dir. */
1781 print_current_files ();
1783 dired_outbyte ('\n');
1785 else if (n_files
<= 1 && pending_dirs
&& pending_dirs
->next
== 0)
1786 print_dir_name
= false;
1788 while (pending_dirs
)
1790 thispend
= pending_dirs
;
1791 pending_dirs
= pending_dirs
->next
;
1795 if (thispend
->name
== NULL
)
1797 /* thispend->name == NULL means this is a marker entry
1798 indicating we've finished processing the directory.
1799 Use its dev/ino numbers to remove the corresponding
1800 entry from the active_dir_set hash table. */
1801 struct dev_ino di
= dev_ino_pop ();
1802 struct dev_ino
*found
= hash_remove (active_dir_set
, &di
);
1804 assert_matching_dev_ino (thispend
->realname
, di
);
1806 dev_ino_free (found
);
1807 free_pending_ent (thispend
);
1812 print_dir (thispend
->name
, thispend
->realname
,
1813 thispend
->command_line_arg
);
1815 free_pending_ent (thispend
);
1816 print_dir_name
= true;
1819 if (print_with_color
&& used_color
)
1823 /* Skip the restore when it would be a no-op, i.e.,
1824 when left is "\033[" and right is "m". */
1825 if (!(color_indicator
[C_LEFT
].len
== 2
1826 && memcmp (color_indicator
[C_LEFT
].string
, "\033[", 2) == 0
1827 && color_indicator
[C_RIGHT
].len
== 1
1828 && color_indicator
[C_RIGHT
].string
[0] == 'm'))
1829 restore_default_color ();
1835 /* Act on any signals that arrived before the default was restored.
1836 This can process signals out of order, but there doesn't seem to
1837 be an easy way to do them in order, and the order isn't that
1838 important anyway. */
1839 for (j
= stop_signal_count
; j
; j
--)
1841 j
= interrupt_signal
;
1848 /* No need to free these since we're about to exit. */
1849 dired_dump_obstack ("//DIRED//", &dired_obstack
);
1850 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack
);
1851 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1852 quoting_style_args
[get_quoting_style (filename_quoting_options
)]);
1857 assert (hash_get_n_entries (active_dir_set
) == 0);
1858 hash_free (active_dir_set
);
1864 /* Return the line length indicated by the value given by SPEC, or -1
1865 if unsuccessful. 0 means no limit on line length. */
1868 decode_line_length (char const *spec
)
1872 /* Treat too-large values as if they were 0, which is
1873 effectively infinity. */
1874 switch (xstrtoumax (spec
, NULL
, 0, &val
, ""))
1877 return val
<= MIN (PTRDIFF_MAX
, SIZE_MAX
) ? val
: 0;
1879 case LONGINT_OVERFLOW
:
1887 /* Return true if standard output is a tty, caching the result. */
1890 stdout_isatty (void)
1892 static signed char out_tty
= -1;
1894 out_tty
= isatty (STDOUT_FILENO
);
1895 assume (out_tty
== 0 || out_tty
== 1);
1899 /* Set all the option flags according to the switches specified.
1900 Return the index of the first non-option argument. */
1903 decode_switches (int argc
, char **argv
)
1905 char *time_style_option
= NULL
;
1907 /* These variables are false or -1 unless a switch says otherwise. */
1908 bool kibibytes_specified
= false;
1909 int format_opt
= -1;
1910 int hide_control_chars_opt
= -1;
1911 int quoting_style_opt
= -1;
1913 ptrdiff_t tabsize_opt
= -1;
1914 ptrdiff_t width_opt
= -1;
1919 int c
= getopt_long (argc
, argv
,
1920 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1928 ignore_mode
= IGNORE_MINIMAL
;
1932 quoting_style_opt
= escape_quoting_style
;
1936 time_type
= time_ctime
;
1940 immediate_dirs
= true;
1944 /* Same as -a -U -1 --color=none --hyperlink=none,
1945 while disabling -s. */
1946 ignore_mode
= IGNORE_MINIMAL
;
1947 sort_opt
= sort_none
;
1948 if (format_opt
== long_format
)
1950 print_with_color
= false;
1951 print_hyperlink
= false;
1952 print_block_size
= false;
1955 case FILE_TYPE_INDICATOR_OPTION
: /* --file-type */
1956 indicator_style
= file_type
;
1960 format_opt
= long_format
;
1961 print_owner
= false;
1965 file_human_output_opts
= human_output_opts
=
1966 human_autoscale
| human_SI
| human_base_1024
;
1967 file_output_block_size
= output_block_size
= 1;
1975 kibibytes_specified
= true;
1979 format_opt
= long_format
;
1983 format_opt
= with_commas
;
1988 format_opt
= long_format
;
1991 case 'o': /* Just like -l, but don't display group info. */
1992 format_opt
= long_format
;
1993 print_group
= false;
1997 indicator_style
= slash
;
2001 hide_control_chars_opt
= true;
2005 sort_reverse
= true;
2009 print_block_size
= true;
2013 sort_opt
= sort_time
;
2017 time_type
= time_atime
;
2021 sort_opt
= sort_version
;
2025 width_opt
= decode_line_length (optarg
);
2027 die (LS_FAILURE
, 0, "%s: %s", _("invalid line width"),
2032 format_opt
= horizontal
;
2036 ignore_mode
= IGNORE_DOT_AND_DOTDOT
;
2040 add_ignore_pattern ("*~");
2041 add_ignore_pattern (".*~");
2045 format_opt
= many_per_line
;
2056 i
= XARGMATCH ("--classify", optarg
, when_args
, when_types
);
2058 /* Using --classify with no argument is equivalent to using
2059 --classify=always. */
2062 if (i
== when_always
|| (i
== when_if_tty
&& stdout_isatty ()))
2063 indicator_style
= classify
;
2067 case 'G': /* inhibit display of group info */
2068 print_group
= false;
2072 dereference
= DEREF_COMMAND_LINE_ARGUMENTS
;
2075 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
:
2076 dereference
= DEREF_COMMAND_LINE_SYMLINK_TO_DIR
;
2080 add_ignore_pattern (optarg
);
2084 dereference
= DEREF_ALWAYS
;
2088 quoting_style_opt
= literal_quoting_style
;
2092 quoting_style_opt
= c_quoting_style
;
2100 sort_opt
= sort_size
;
2104 tabsize_opt
= xnumtoumax (optarg
, 0, 0, MIN (PTRDIFF_MAX
, SIZE_MAX
),
2105 "", _("invalid tab size"), LS_FAILURE
);
2109 sort_opt
= sort_none
;
2113 sort_opt
= sort_extension
;
2117 /* -1 has no effect after -l. */
2118 if (format_opt
!= long_format
)
2119 format_opt
= one_per_line
;
2123 print_author
= true;
2128 struct ignore_pattern
*hide
= xmalloc (sizeof *hide
);
2129 hide
->pattern
= optarg
;
2130 hide
->next
= hide_patterns
;
2131 hide_patterns
= hide
;
2136 sort_opt
= XARGMATCH ("--sort", optarg
, sort_args
, sort_types
);
2139 case GROUP_DIRECTORIES_FIRST_OPTION
:
2140 directories_first
= true;
2144 time_type
= XARGMATCH ("--time", optarg
, time_args
, time_types
);
2148 format_opt
= XARGMATCH ("--format", optarg
, format_args
,
2152 case FULL_TIME_OPTION
:
2153 format_opt
= long_format
;
2154 time_style_option
= bad_cast ("full-iso");
2161 i
= XARGMATCH ("--color", optarg
, when_args
, when_types
);
2163 /* Using --color with no argument is equivalent to using
2167 print_with_color
= (i
== when_always
2168 || (i
== when_if_tty
&& stdout_isatty ()));
2172 case HYPERLINK_OPTION
:
2176 i
= XARGMATCH ("--hyperlink", optarg
, when_args
, when_types
);
2178 /* Using --hyperlink with no argument is equivalent to using
2179 --hyperlink=always. */
2182 print_hyperlink
= (i
== when_always
2183 || (i
== when_if_tty
&& stdout_isatty ()));
2187 case INDICATOR_STYLE_OPTION
:
2188 indicator_style
= XARGMATCH ("--indicator-style", optarg
,
2189 indicator_style_args
,
2190 indicator_style_types
);
2193 case QUOTING_STYLE_OPTION
:
2194 quoting_style_opt
= XARGMATCH ("--quoting-style", optarg
,
2196 quoting_style_vals
);
2199 case TIME_STYLE_OPTION
:
2200 time_style_option
= optarg
;
2203 case SHOW_CONTROL_CHARS_OPTION
:
2204 hide_control_chars_opt
= false;
2207 case BLOCK_SIZE_OPTION
:
2209 enum strtol_error e
= human_options (optarg
, &human_output_opts
,
2210 &output_block_size
);
2211 if (e
!= LONGINT_OK
)
2212 xstrtol_fatal (e
, oi
, 0, long_options
, optarg
);
2213 file_human_output_opts
= human_output_opts
;
2214 file_output_block_size
= output_block_size
;
2219 file_human_output_opts
= human_output_opts
=
2220 human_autoscale
| human_SI
;
2221 file_output_block_size
= output_block_size
= 1;
2225 print_scontext
= true;
2230 hide_control_chars_opt
= false;
2231 if (format_opt
!= long_format
)
2232 format_opt
= one_per_line
;
2233 print_with_color
= false;
2234 quoting_style_opt
= literal_quoting_style
;
2237 case_GETOPT_HELP_CHAR
;
2239 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
2246 if (! output_block_size
)
2248 char const *ls_block_size
= getenv ("LS_BLOCK_SIZE");
2249 human_options (ls_block_size
,
2250 &human_output_opts
, &output_block_size
);
2251 if (ls_block_size
|| getenv ("BLOCK_SIZE"))
2253 file_human_output_opts
= human_output_opts
;
2254 file_output_block_size
= output_block_size
;
2256 if (kibibytes_specified
)
2258 human_output_opts
= 0;
2259 output_block_size
= 1024;
2263 format
= (0 <= format_opt
? format_opt
2264 : ls_mode
== LS_LS
? (stdout_isatty ()
2265 ? many_per_line
: one_per_line
)
2266 : ls_mode
== LS_MULTI_COL
? many_per_line
2267 : /* ls_mode == LS_LONG_FORMAT */ long_format
);
2269 /* If the line length was not set by a switch but is needed to determine
2270 output, go to the work of obtaining it from the environment. */
2271 ptrdiff_t linelen
= width_opt
;
2272 if (format
== many_per_line
|| format
== horizontal
|| format
== with_commas
2273 || print_with_color
)
2278 /* Suppress bogus warning re comparing ws.ws_col to big integer. */
2279 # if 4 < __GNUC__ + (6 <= __GNUC_MINOR__)
2280 # pragma GCC diagnostic push
2281 # pragma GCC diagnostic ignored "-Wtype-limits"
2284 if (stdout_isatty ()
2285 && 0 <= ioctl (STDOUT_FILENO
, TIOCGWINSZ
, &ws
)
2287 linelen
= ws
.ws_col
<= MIN (PTRDIFF_MAX
, SIZE_MAX
) ? ws
.ws_col
: 0;
2288 # if 4 < __GNUC__ + (6 <= __GNUC_MINOR__)
2289 # pragma GCC diagnostic pop
2295 char const *p
= getenv ("COLUMNS");
2298 linelen
= decode_line_length (p
);
2301 _("ignoring invalid width"
2302 " in environment variable COLUMNS: %s"),
2308 line_length
= linelen
< 0 ? 80 : linelen
;
2310 /* Determine the max possible number of display columns. */
2311 max_idx
= line_length
/ MIN_COLUMN_WIDTH
;
2312 /* Account for first display column not having a separator,
2313 or line_lengths shorter than MIN_COLUMN_WIDTH. */
2314 max_idx
+= line_length
% MIN_COLUMN_WIDTH
!= 0;
2316 if (format
== many_per_line
|| format
== horizontal
|| format
== with_commas
)
2318 if (0 <= tabsize_opt
)
2319 tabsize
= tabsize_opt
;
2323 char const *p
= getenv ("TABSIZE");
2327 if (xstrtoumax (p
, NULL
, 0, &tmp
, "") == LONGINT_OK
2332 _("ignoring invalid tab size"
2333 " in environment variable TABSIZE: %s"),
2339 qmark_funny_chars
= (hide_control_chars_opt
< 0
2340 ? ls_mode
== LS_LS
&& stdout_isatty ()
2341 : hide_control_chars_opt
);
2343 int qs
= quoting_style_opt
;
2345 qs
= getenv_quoting_style ();
2347 qs
= (ls_mode
== LS_LS
2348 ? (stdout_isatty () ? shell_escape_quoting_style
: -1)
2349 : escape_quoting_style
);
2351 set_quoting_style (NULL
, qs
);
2352 qs
= get_quoting_style (NULL
);
2353 align_variable_outer_quotes
2354 = ((format
== long_format
2355 || ((format
== many_per_line
|| format
== horizontal
) && line_length
))
2356 && (qs
== shell_quoting_style
2357 || qs
== shell_escape_quoting_style
2358 || qs
== c_maybe_quoting_style
));
2359 filename_quoting_options
= clone_quoting_options (NULL
);
2360 if (qs
== escape_quoting_style
)
2361 set_char_quoting (filename_quoting_options
, ' ', 1);
2362 if (file_type
<= indicator_style
)
2365 for (p
= &"*=>@|"[indicator_style
- file_type
]; *p
; p
++)
2366 set_char_quoting (filename_quoting_options
, *p
, 1);
2369 dirname_quoting_options
= clone_quoting_options (NULL
);
2370 set_char_quoting (dirname_quoting_options
, ':', 1);
2372 /* --dired is meaningful only with --format=long (-l) and sans --hyperlink.
2373 Otherwise, ignore it. FIXME: warn about this?
2374 Alternatively, make --dired imply --format=long? */
2375 dired
&= (format
== long_format
) & !print_hyperlink
;
2377 if (eolbyte
< dired
)
2378 die (LS_FAILURE
, 0, _("--dired and --zero are incompatible"));
2380 /* If -c or -u is specified and not -l (or any other option that implies -l),
2381 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
2382 The behavior of ls when using either -c or -u but with neither -l nor -t
2383 appears to be unspecified by POSIX. So, with GNU ls, '-u' alone means
2384 sort by atime (this is the one that's not specified by the POSIX spec),
2385 -lu means show atime and sort by name, -lut means show atime and sort
2388 sort_type
= (0 <= sort_opt
? sort_opt
2389 : (format
!= long_format
2390 && (time_type
== time_ctime
|| time_type
== time_atime
2391 || time_type
== time_btime
))
2392 ? sort_time
: sort_name
);
2394 if (format
== long_format
)
2396 char *style
= time_style_option
;
2397 static char const posix_prefix
[] = "posix-";
2400 if (! (style
= getenv ("TIME_STYLE")))
2401 style
= bad_cast ("locale");
2403 while (STREQ_LEN (style
, posix_prefix
, sizeof posix_prefix
- 1))
2405 if (! hard_locale (LC_TIME
))
2407 style
+= sizeof posix_prefix
- 1;
2412 char *p0
= style
+ 1;
2413 char *p1
= strchr (p0
, '\n');
2418 if (strchr (p1
+ 1, '\n'))
2419 die (LS_FAILURE
, 0, _("invalid time style format %s"),
2423 long_time_format
[0] = p0
;
2424 long_time_format
[1] = p1
;
2428 ptrdiff_t res
= argmatch (style
, time_style_args
,
2429 (char const *) time_style_types
,
2430 sizeof (*time_style_types
));
2433 /* This whole block used to be a simple use of XARGMATCH.
2434 but that didn't print the "posix-"-prefixed variants or
2435 the "+"-prefixed format string option upon failure. */
2436 argmatch_invalid ("time style", style
, res
);
2438 /* The following is a manual expansion of argmatch_valid,
2439 but with the added "+ ..." description and the [posix-]
2440 prefixes prepended. Note that this simplification works
2441 only because all four existing time_style_types values
2443 fputs (_("Valid arguments are:\n"), stderr
);
2444 char const *const *p
= time_style_args
;
2446 fprintf (stderr
, " - [posix-]%s\n", *p
++);
2447 fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
2448 " format\n"), stderr
);
2453 case full_iso_time_style
:
2454 long_time_format
[0] = long_time_format
[1] =
2455 "%Y-%m-%d %H:%M:%S.%N %z";
2458 case long_iso_time_style
:
2459 long_time_format
[0] = long_time_format
[1] = "%Y-%m-%d %H:%M";
2462 case iso_time_style
:
2463 long_time_format
[0] = "%Y-%m-%d ";
2464 long_time_format
[1] = "%m-%d %H:%M";
2467 case locale_time_style
:
2468 if (hard_locale (LC_TIME
))
2470 for (int i
= 0; i
< 2; i
++)
2471 long_time_format
[i
] =
2472 dcgettext (NULL
, long_time_format
[i
], LC_TIME
);
2483 /* Parse a string as part of the LS_COLORS variable; this may involve
2484 decoding all kinds of escape characters. If equals_end is set an
2485 unescaped equal sign ends the string, otherwise only a : or \0
2486 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2489 The resulting string is *not* null-terminated, but may contain
2492 Note that both dest and src are char **; on return they point to
2493 the first free byte after the array and the character that ended
2494 the input string, respectively. */
2497 get_funky_string (char **dest
, char const **src
, bool equals_end
,
2498 size_t *output_count
)
2500 char num
; /* For numerical codes */
2501 size_t count
; /* Something to count with */
2503 ST_GND
, ST_BACKSLASH
, ST_OCTAL
, ST_HEX
, ST_CARET
, ST_END
, ST_ERROR
2508 p
= *src
; /* We don't want to double-indirect */
2509 q
= *dest
; /* the whole darn time. */
2511 count
= 0; /* No characters counted in yet. */
2514 state
= ST_GND
; /* Start in ground state. */
2515 while (state
< ST_END
)
2519 case ST_GND
: /* Ground state (no escapes) */
2524 state
= ST_END
; /* End of string */
2527 state
= ST_BACKSLASH
; /* Backslash escape sequence */
2531 state
= ST_CARET
; /* Caret escape */
2537 state
= ST_END
; /* End */
2548 case ST_BACKSLASH
: /* Backslash escaped character */
2559 state
= ST_OCTAL
; /* Octal sequence */
2564 state
= ST_HEX
; /* Hex sequence */
2567 case 'a': /* Bell */
2570 case 'b': /* Backspace */
2573 case 'e': /* Escape */
2576 case 'f': /* Form feed */
2579 case 'n': /* Newline */
2582 case 'r': /* Carriage return */
2588 case 'v': /* Vtab */
2591 case '?': /* Delete */
2594 case '_': /* Space */
2597 case '\0': /* End of string */
2598 state
= ST_ERROR
; /* Error! */
2600 default: /* Escaped character like \ ^ : = */
2604 if (state
== ST_BACKSLASH
)
2613 case ST_OCTAL
: /* Octal sequence */
2614 if (*p
< '0' || *p
> '7')
2621 num
= (num
<< 3) + (*(p
++) - '0');
2624 case ST_HEX
: /* Hex sequence */
2637 num
= (num
<< 4) + (*(p
++) - '0');
2645 num
= (num
<< 4) + (*(p
++) - 'a') + 10;
2653 num
= (num
<< 4) + (*(p
++) - 'A') + 10;
2663 case ST_CARET
: /* Caret escape */
2664 state
= ST_GND
; /* Should be the next state... */
2665 if (*p
>= '@' && *p
<= '~')
2667 *(q
++) = *(p
++) & 037;
2686 *output_count
= count
;
2688 return state
!= ST_ERROR
;
2702 /* Check if the content of TERM is a valid name in dircolors. */
2705 known_term_type (void)
2707 char const *term
= getenv ("TERM");
2708 if (! term
|| ! *term
)
2711 char const *line
= G_line
;
2712 while (line
- G_line
< sizeof (G_line
))
2714 if (STRNCMP_LIT (line
, "TERM ") == 0)
2716 if (fnmatch (line
+ 5, term
, 0) == 0)
2719 line
+= strlen (line
) + 1;
2726 parse_ls_color (void)
2728 char const *p
; /* Pointer to character being parsed */
2729 char *buf
; /* color_buf buffer pointer */
2730 int ind_no
; /* Indicator number */
2731 char label
[3]; /* Indicator label */
2732 struct color_ext_type
*ext
; /* Extension we are working on */
2734 if ((p
= getenv ("LS_COLORS")) == NULL
|| *p
== '\0')
2736 /* LS_COLORS takes precedence, but if that's not set then
2737 honor the COLORTERM and TERM env variables so that
2738 we only go with the internal ANSI color codes if the
2739 former is non empty or the latter is set to a known value. */
2740 char const *colorterm
= getenv ("COLORTERM");
2741 if (! (colorterm
&& *colorterm
) && ! known_term_type ())
2742 print_with_color
= false;
2747 strcpy (label
, "??");
2749 /* This is an overly conservative estimate, but any possible
2750 LS_COLORS string will *not* generate a color_buf longer than
2751 itself, so it is a safe way of allocating a buffer in
2753 buf
= color_buf
= xstrdup (p
);
2755 enum parse_state state
= PS_START
;
2760 case PS_START
: /* First label character */
2768 /* Allocate new extension block and add to head of
2769 linked list (this way a later definition will
2770 override an earlier one, which can be useful for
2771 having terminal-specific defs override global). */
2773 ext
= xmalloc (sizeof *ext
);
2774 ext
->next
= color_ext_list
;
2775 color_ext_list
= ext
;
2778 ext
->ext
.string
= buf
;
2780 state
= (get_funky_string (&buf
, &p
, true, &ext
->ext
.len
)
2785 state
= PS_DONE
; /* Done! */
2788 default: /* Assume it is file type label */
2795 case PS_2
: /* Second label character */
2802 state
= PS_FAIL
; /* Error */
2805 case PS_3
: /* Equal sign after indicator label */
2806 state
= PS_FAIL
; /* Assume failure... */
2807 if (*(p
++) == '=')/* It *should* be... */
2809 for (ind_no
= 0; indicator_name
[ind_no
] != NULL
; ++ind_no
)
2811 if (STREQ (label
, indicator_name
[ind_no
]))
2813 color_indicator
[ind_no
].string
= buf
;
2814 state
= (get_funky_string (&buf
, &p
, false,
2815 &color_indicator
[ind_no
].len
)
2816 ? PS_START
: PS_FAIL
);
2820 if (state
== PS_FAIL
)
2821 error (0, 0, _("unrecognized prefix: %s"), quote (label
));
2825 case PS_4
: /* Equal sign after *.ext */
2828 ext
->seq
.string
= buf
;
2829 state
= (get_funky_string (&buf
, &p
, false, &ext
->seq
.len
)
2830 ? PS_START
: PS_FAIL
);
2845 if (state
== PS_FAIL
)
2847 struct color_ext_type
*e
;
2848 struct color_ext_type
*e2
;
2851 _("unparsable value for LS_COLORS environment variable"));
2853 for (e
= color_ext_list
; e
!= NULL
; /* empty */)
2859 print_with_color
= false;
2862 if (color_indicator
[C_LINK
].len
== 6
2863 && !STRNCMP_LIT (color_indicator
[C_LINK
].string
, "target"))
2864 color_symlink_as_referent
= true;
2867 /* Return the quoting style specified by the environment variable
2868 QUOTING_STYLE if set and valid, -1 otherwise. */
2871 getenv_quoting_style (void)
2873 char const *q_style
= getenv ("QUOTING_STYLE");
2876 int i
= ARGMATCH (q_style
, quoting_style_args
, quoting_style_vals
);
2880 _("ignoring invalid value"
2881 " of environment variable QUOTING_STYLE: %s"),
2885 return quoting_style_vals
[i
];
2888 /* Set the exit status to report a failure. If SERIOUS, it is a
2889 serious failure; otherwise, it is merely a minor problem. */
2892 set_exit_status (bool serious
)
2895 exit_status
= LS_FAILURE
;
2896 else if (exit_status
== EXIT_SUCCESS
)
2897 exit_status
= LS_MINOR_PROBLEM
;
2900 /* Assuming a failure is serious if SERIOUS, use the printf-style
2901 MESSAGE to report the failure to access a file named FILE. Assume
2902 errno is set appropriately for the failure. */
2905 file_failure (bool serious
, char const *message
, char const *file
)
2907 error (0, errno
, message
, quoteaf (file
));
2908 set_exit_status (serious
);
2911 /* Request that the directory named NAME have its contents listed later.
2912 If REALNAME is nonzero, it will be used instead of NAME when the
2913 directory name is printed. This allows symbolic links to directories
2914 to be treated as regular directories but still be listed under their
2915 real names. NAME == NULL is used to insert a marker entry for the
2916 directory named in REALNAME.
2917 If NAME is non-NULL, we use its dev/ino information to save
2918 a call to stat -- when doing a recursive (-R) traversal.
2919 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2922 queue_directory (char const *name
, char const *realname
, bool command_line_arg
)
2924 struct pending
*new = xmalloc (sizeof *new);
2925 new->realname
= realname
? xstrdup (realname
) : NULL
;
2926 new->name
= name
? xstrdup (name
) : NULL
;
2927 new->command_line_arg
= command_line_arg
;
2928 new->next
= pending_dirs
;
2932 /* Read directory NAME, and list the files in it.
2933 If REALNAME is nonzero, print its name instead of NAME;
2934 this is used for symbolic links to directories.
2935 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2938 print_dir (char const *name
, char const *realname
, bool command_line_arg
)
2941 struct dirent
*next
;
2942 uintmax_t total_blocks
= 0;
2943 static bool first
= true;
2946 dirp
= opendir (name
);
2949 file_failure (command_line_arg
, _("cannot open directory %s"), name
);
2955 struct stat dir_stat
;
2956 int fd
= dirfd (dirp
);
2958 /* If dirfd failed, endure the overhead of stat'ing by path */
2960 ? fstat_for_ino (fd
, &dir_stat
)
2961 : stat_for_ino (name
, &dir_stat
)) < 0)
2963 file_failure (command_line_arg
,
2964 _("cannot determine device and inode of %s"), name
);
2969 /* If we've already visited this dev/inode pair, warn that
2970 we've found a loop, and do not process this directory. */
2971 if (visit_dir (dir_stat
.st_dev
, dir_stat
.st_ino
))
2973 error (0, 0, _("%s: not listing already-listed directory"),
2976 set_exit_status (true);
2980 dev_ino_push (dir_stat
.st_dev
, dir_stat
.st_ino
);
2985 if (recursive
|| print_dir_name
)
2988 dired_outbyte ('\n');
2992 char *absolute_name
= NULL
;
2993 if (print_hyperlink
)
2995 absolute_name
= canonicalize_filename_mode (name
, CAN_MISSING
);
2996 if (! absolute_name
)
2997 file_failure (command_line_arg
,
2998 _("error canonicalizing %s"), name
);
3000 quote_name (realname
? realname
: name
, dirname_quoting_options
, -1,
3001 NULL
, true, &subdired_obstack
, absolute_name
);
3003 free (absolute_name
);
3005 dired_outstring (":\n");
3008 /* Read the directory entries, and insert the subfiles into the 'cwd_file'
3013 /* Set errno to zero so we can distinguish between a readdir failure
3014 and when readdir simply finds that there are no more entries. */
3016 next
= readdir (dirp
);
3019 if (! file_ignored (next
->d_name
))
3021 enum filetype type
= unknown
;
3023 #if HAVE_STRUCT_DIRENT_D_TYPE
3024 switch (next
->d_type
)
3026 case DT_BLK
: type
= blockdev
; break;
3027 case DT_CHR
: type
= chardev
; break;
3028 case DT_DIR
: type
= directory
; break;
3029 case DT_FIFO
: type
= fifo
; break;
3030 case DT_LNK
: type
= symbolic_link
; break;
3031 case DT_REG
: type
= normal
; break;
3032 case DT_SOCK
: type
= sock
; break;
3034 case DT_WHT
: type
= whiteout
; break;
3038 total_blocks
+= gobble_file (next
->d_name
, type
,
3039 RELIABLE_D_INO (next
),
3042 /* In this narrow case, print out each name right away, so
3043 ls uses constant memory while processing the entries of
3044 this directory. Useful when there are many (millions)
3045 of entries in a directory. */
3046 if (format
== one_per_line
&& sort_type
== sort_none
3047 && !print_block_size
&& !recursive
)
3049 /* We must call sort_files in spite of
3050 "sort_type == sort_none" for its initialization
3051 of the sorted_file vector. */
3053 print_current_files ();
3058 else if (errno
!= 0)
3060 file_failure (command_line_arg
, _("reading directory %s"), name
);
3061 if (errno
!= EOVERFLOW
)
3067 /* When processing a very large directory, and since we've inhibited
3068 interrupts, this loop would take so long that ls would be annoyingly
3069 uninterruptible. This ensures that it handles signals promptly. */
3073 if (closedir (dirp
) != 0)
3075 file_failure (command_line_arg
, _("closing directory %s"), name
);
3076 /* Don't return; print whatever we got. */
3079 /* Sort the directory contents. */
3082 /* If any member files are subdirectories, perhaps they should have their
3083 contents listed rather than being mentioned here as files. */
3086 extract_dirs_from_files (name
, false);
3088 if (format
== long_format
|| print_block_size
)
3090 char buf
[LONGEST_HUMAN_READABLE
+ 3];
3091 char *p
= human_readable (total_blocks
, buf
+ 1, human_output_opts
,
3092 ST_NBLOCKSIZE
, output_block_size
);
3093 char *pend
= p
+ strlen (p
);
3097 dired_outstring (_("total"));
3098 dired_outbuf (p
, pend
- p
);
3102 print_current_files ();
3105 /* Add 'pattern' to the list of patterns for which files that match are
3109 add_ignore_pattern (char const *pattern
)
3111 struct ignore_pattern
*ignore
;
3113 ignore
= xmalloc (sizeof *ignore
);
3114 ignore
->pattern
= pattern
;
3115 /* Add it to the head of the linked list. */
3116 ignore
->next
= ignore_patterns
;
3117 ignore_patterns
= ignore
;
3120 /* Return true if one of the PATTERNS matches FILE. */
3123 patterns_match (struct ignore_pattern
const *patterns
, char const *file
)
3125 struct ignore_pattern
const *p
;
3126 for (p
= patterns
; p
; p
= p
->next
)
3127 if (fnmatch (p
->pattern
, file
, FNM_PERIOD
) == 0)
3132 /* Return true if FILE should be ignored. */
3135 file_ignored (char const *name
)
3137 return ((ignore_mode
!= IGNORE_MINIMAL
3139 && (ignore_mode
== IGNORE_DEFAULT
|| ! name
[1 + (name
[1] == '.')]))
3140 || (ignore_mode
== IGNORE_DEFAULT
3141 && patterns_match (hide_patterns
, name
))
3142 || patterns_match (ignore_patterns
, name
));
3145 /* POSIX requires that a file size be printed without a sign, even
3146 when negative. Assume the typical case where negative sizes are
3147 actually positive values that have wrapped around. */
3150 unsigned_file_size (off_t size
)
3152 return size
+ (size
< 0) * ((uintmax_t) OFF_T_MAX
- OFF_T_MIN
+ 1);
3156 /* Return true if NAME has a capability (see linux/capability.h) */
3158 has_capability (char const *name
)
3163 cap_t cap_d
= cap_get_file (name
);
3167 result
= cap_to_text (cap_d
, NULL
);
3172 /* check if human-readable capability string is empty */
3173 has_cap
= !!*result
;
3180 has_capability (MAYBE_UNUSED
char const *name
)
3187 /* Enter and remove entries in the table 'cwd_file'. */
3190 free_ent (struct fileinfo
*f
)
3194 free (f
->absolute_name
);
3195 if (f
->scontext
!= UNKNOWN_SECURITY_CONTEXT
)
3197 if (is_smack_enabled ())
3200 freecon (f
->scontext
);
3204 /* Empty the table of files. */
3208 for (size_t i
= 0; i
< cwd_n_used
; i
++)
3210 struct fileinfo
*f
= sorted_file
[i
];
3215 cwd_some_quoted
= false;
3216 any_has_acl
= false;
3217 inode_number_width
= 0;
3218 block_size_width
= 0;
3224 major_device_number_width
= 0;
3225 minor_device_number_width
= 0;
3226 file_size_width
= 0;
3229 /* Return true if ERR implies lack-of-support failure by a
3230 getxattr-calling function like getfilecon or file_has_acl. */
3232 errno_unsupported (int err
)
3234 return (err
== EINVAL
|| err
== ENOSYS
|| is_ENOTSUP (err
));
3237 /* Cache *getfilecon failure, when it's trivial to do so.
3238 Like getfilecon/lgetfilecon, but when F's st_dev says it's doesn't
3239 support getting the security context, fail with ENOTSUP immediately. */
3241 getfilecon_cache (char const *file
, struct fileinfo
*f
, bool deref
)
3243 /* st_dev of the most recently processed device for which we've
3244 found that [l]getfilecon fails indicating lack of support. */
3245 static dev_t unsupported_device
;
3247 if (f
->stat
.st_dev
== unsupported_device
)
3254 if (is_smack_enabled ())
3255 r
= smack_new_label_from_path (file
, "security.SMACK64", deref
,
3260 ? getfilecon (file
, &f
->scontext
)
3261 : lgetfilecon (file
, &f
->scontext
));
3262 if (r
< 0 && errno_unsupported (errno
))
3263 unsupported_device
= f
->stat
.st_dev
;
3267 /* Cache file_has_acl failure, when it's trivial to do.
3268 Like file_has_acl, but when F's st_dev says it's on a file
3269 system lacking ACL support, return 0 with ENOTSUP immediately. */
3271 file_has_acl_cache (char const *file
, struct fileinfo
*f
)
3273 /* st_dev of the most recently processed device for which we've
3274 found that file_has_acl fails indicating lack of support. */
3275 static dev_t unsupported_device
;
3277 if (f
->stat
.st_dev
== unsupported_device
)
3283 /* Zero errno so that we can distinguish between two 0-returning cases:
3284 "has-ACL-support, but only a default ACL" and "no ACL support". */
3286 int n
= file_has_acl (file
, &f
->stat
);
3287 if (n
<= 0 && errno_unsupported (errno
))
3288 unsupported_device
= f
->stat
.st_dev
;
3292 /* Cache has_capability failure, when it's trivial to do.
3293 Like has_capability, but when F's st_dev says it's on a file
3294 system lacking capability support, return 0 with ENOTSUP immediately. */
3296 has_capability_cache (char const *file
, struct fileinfo
*f
)
3298 /* st_dev of the most recently processed device for which we've
3299 found that has_capability fails indicating lack of support. */
3300 static dev_t unsupported_device
;
3302 if (f
->stat
.st_dev
== unsupported_device
)
3308 bool b
= has_capability (file
);
3309 if ( !b
&& errno_unsupported (errno
))
3310 unsupported_device
= f
->stat
.st_dev
;
3315 needs_quoting (char const *name
)
3318 size_t len
= quotearg_buffer (test
, sizeof test
, name
, -1,
3319 filename_quoting_options
);
3320 return *name
!= *test
|| strlen (name
) != len
;
3323 /* Add a file to the current table of files.
3324 Verify that the file exists, and print an error message if it does not.
3325 Return the number of blocks that the file occupies. */
3327 gobble_file (char const *name
, enum filetype type
, ino_t inode
,
3328 bool command_line_arg
, char const *dirname
)
3330 uintmax_t blocks
= 0;
3333 /* An inode value prior to gobble_file necessarily came from readdir,
3334 which is not used for command line arguments. */
3335 assert (! command_line_arg
|| inode
== NOT_AN_INODE_NUMBER
);
3337 if (cwd_n_used
== cwd_n_alloc
)
3339 cwd_file
= xnrealloc (cwd_file
, cwd_n_alloc
, 2 * sizeof *cwd_file
);
3343 f
= &cwd_file
[cwd_n_used
];
3344 memset (f
, '\0', sizeof *f
);
3345 f
->stat
.st_ino
= inode
;
3349 if ((! cwd_some_quoted
) && align_variable_outer_quotes
)
3351 /* Determine if any quoted for padding purposes. */
3352 f
->quoted
= needs_quoting (name
);
3354 cwd_some_quoted
= 1;
3357 if (command_line_arg
3359 || format_needs_stat
3360 /* When coloring a directory (we may know the type from
3361 direct.d_type), we have to stat it in order to indicate
3362 sticky and/or other-writable attributes. */
3363 || (type
== directory
&& print_with_color
3364 && (is_colored (C_OTHER_WRITABLE
)
3365 || is_colored (C_STICKY
)
3366 || is_colored (C_STICKY_OTHER_WRITABLE
)))
3367 /* When dereferencing symlinks, the inode and type must come from
3368 stat, but readdir provides the inode and type of lstat. */
3369 || ((print_inode
|| format_needs_type
)
3370 && (type
== symbolic_link
|| type
== unknown
)
3371 && (dereference
== DEREF_ALWAYS
3372 || color_symlink_as_referent
|| check_symlink_mode
))
3373 /* Command line dereferences are already taken care of by the above
3374 assertion that the inode number is not yet known. */
3375 || (print_inode
&& inode
== NOT_AN_INODE_NUMBER
)
3376 || (format_needs_type
3377 && (type
== unknown
|| command_line_arg
3378 /* --indicator-style=classify (aka -F)
3379 requires that we stat each regular file
3380 to see if it's executable. */
3381 || (type
== normal
&& (indicator_style
== classify
3382 /* This is so that --color ends up
3383 highlighting files with these mode
3384 bits set even when options like -F are
3385 not specified. Note we do a redundant
3386 stat in the very unlikely case where
3387 C_CAP is set but not the others. */
3388 || (print_with_color
3389 && (is_colored (C_EXEC
)
3390 || is_colored (C_SETUID
)
3391 || is_colored (C_SETGID
)
3392 || is_colored (C_CAP
)))
3396 /* Absolute name of this file. */
3401 if (name
[0] == '/' || dirname
[0] == 0)
3402 full_name
= (char *) name
;
3405 full_name
= alloca (strlen (name
) + strlen (dirname
) + 2);
3406 attach (full_name
, dirname
, name
);
3409 if (print_hyperlink
)
3411 f
->absolute_name
= canonicalize_filename_mode (full_name
,
3413 if (! f
->absolute_name
)
3414 file_failure (command_line_arg
,
3415 _("error canonicalizing %s"), full_name
);
3418 switch (dereference
)
3421 err
= do_stat (full_name
, &f
->stat
);
3425 case DEREF_COMMAND_LINE_ARGUMENTS
:
3426 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR
:
3427 if (command_line_arg
)
3430 err
= do_stat (full_name
, &f
->stat
);
3433 if (dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
3436 need_lstat
= (err
< 0
3438 : ! S_ISDIR (f
->stat
.st_mode
));
3442 /* stat failed because of ENOENT, maybe indicating a dangling
3443 symlink. Or stat succeeded, FULL_NAME does not refer to a
3444 directory, and --dereference-command-line-symlink-to-dir is
3445 in effect. Fall through so that we call lstat instead. */
3449 default: /* DEREF_NEVER */
3450 err
= do_lstat (full_name
, &f
->stat
);
3457 /* Failure to stat a command line argument leads to
3458 an exit status of 2. For other files, stat failure
3459 provokes an exit status of 1. */
3460 file_failure (command_line_arg
,
3461 _("cannot access %s"), full_name
);
3463 f
->scontext
= UNKNOWN_SECURITY_CONTEXT
;
3465 if (command_line_arg
)
3468 f
->name
= xstrdup (name
);
3476 /* Note has_capability() adds around 30% runtime to 'ls --color' */
3477 if ((type
== normal
|| S_ISREG (f
->stat
.st_mode
))
3478 && print_with_color
&& is_colored (C_CAP
))
3479 f
->has_capability
= has_capability_cache (full_name
, f
);
3481 if (format
== long_format
|| print_scontext
)
3483 bool have_scontext
= false;
3484 bool have_acl
= false;
3485 int attr_len
= getfilecon_cache (full_name
, f
, do_deref
);
3486 err
= (attr_len
< 0);
3490 if (is_smack_enabled ())
3491 have_scontext
= ! STREQ ("_", f
->scontext
);
3493 have_scontext
= ! STREQ ("unlabeled", f
->scontext
);
3497 f
->scontext
= UNKNOWN_SECURITY_CONTEXT
;
3499 /* When requesting security context information, don't make
3500 ls fail just because the file (even a command line argument)
3501 isn't on the right type of file system. I.e., a getfilecon
3502 failure isn't in the same class as a stat failure. */
3503 if (is_ENOTSUP (errno
) || errno
== ENODATA
)
3507 if (err
== 0 && format
== long_format
)
3509 int n
= file_has_acl_cache (full_name
, f
);
3514 f
->acl_type
= (!have_scontext
&& !have_acl
3516 : (have_scontext
&& !have_acl
3517 ? ACL_T_LSM_CONTEXT_ONLY
3519 any_has_acl
|= f
->acl_type
!= ACL_T_NONE
;
3522 error (0, errno
, "%s", quotef (full_name
));
3525 if (S_ISLNK (f
->stat
.st_mode
)
3526 && (format
== long_format
|| check_symlink_mode
))
3528 struct stat linkstats
;
3530 get_link_name (full_name
, f
, command_line_arg
);
3531 char *linkname
= make_link_name (full_name
, f
->linkname
);
3533 /* Use the slower quoting path for this entry, though
3534 don't update CWD_SOME_QUOTED since alignment not affected. */
3535 if (linkname
&& f
->quoted
== 0 && needs_quoting (f
->linkname
))
3538 /* Avoid following symbolic links when possible, ie, when
3539 they won't be traced and when no indicator is needed. */
3541 && (file_type
<= indicator_style
|| check_symlink_mode
)
3542 && stat_for_mode (linkname
, &linkstats
) == 0)
3545 f
->linkmode
= linkstats
.st_mode
;
3550 if (S_ISLNK (f
->stat
.st_mode
))
3551 f
->filetype
= symbolic_link
;
3552 else if (S_ISDIR (f
->stat
.st_mode
))
3554 if (command_line_arg
&& !immediate_dirs
)
3555 f
->filetype
= arg_directory
;
3557 f
->filetype
= directory
;
3560 f
->filetype
= normal
;
3562 blocks
= ST_NBLOCKS (f
->stat
);
3563 if (format
== long_format
|| print_block_size
)
3565 char buf
[LONGEST_HUMAN_READABLE
+ 1];
3566 int len
= mbswidth (human_readable (blocks
, buf
, human_output_opts
,
3567 ST_NBLOCKSIZE
, output_block_size
),
3569 if (block_size_width
< len
)
3570 block_size_width
= len
;
3573 if (format
== long_format
)
3577 int len
= format_user_width (f
->stat
.st_uid
);
3578 if (owner_width
< len
)
3584 int len
= format_group_width (f
->stat
.st_gid
);
3585 if (group_width
< len
)
3591 int len
= format_user_width (f
->stat
.st_author
);
3592 if (author_width
< len
)
3599 int len
= strlen (f
->scontext
);
3600 if (scontext_width
< len
)
3601 scontext_width
= len
;
3604 if (format
== long_format
)
3606 char b
[INT_BUFSIZE_BOUND (uintmax_t)];
3607 int b_len
= strlen (umaxtostr (f
->stat
.st_nlink
, b
));
3608 if (nlink_width
< b_len
)
3609 nlink_width
= b_len
;
3611 if (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
))
3613 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
3614 int len
= strlen (umaxtostr (major (f
->stat
.st_rdev
), buf
));
3615 if (major_device_number_width
< len
)
3616 major_device_number_width
= len
;
3617 len
= strlen (umaxtostr (minor (f
->stat
.st_rdev
), buf
));
3618 if (minor_device_number_width
< len
)
3619 minor_device_number_width
= len
;
3620 len
= major_device_number_width
+ 2 + minor_device_number_width
;
3621 if (file_size_width
< len
)
3622 file_size_width
= len
;
3626 char buf
[LONGEST_HUMAN_READABLE
+ 1];
3627 uintmax_t size
= unsigned_file_size (f
->stat
.st_size
);
3628 int len
= mbswidth (human_readable (size
, buf
,
3629 file_human_output_opts
,
3630 1, file_output_block_size
),
3632 if (file_size_width
< len
)
3633 file_size_width
= len
;
3640 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
3641 int len
= strlen (umaxtostr (f
->stat
.st_ino
, buf
));
3642 if (inode_number_width
< len
)
3643 inode_number_width
= len
;
3646 f
->name
= xstrdup (name
);
3652 /* Return true if F refers to a directory. */
3654 is_directory (const struct fileinfo
*f
)
3656 return f
->filetype
== directory
|| f
->filetype
== arg_directory
;
3659 /* Return true if F refers to a (symlinked) directory. */
3661 is_linked_directory (const struct fileinfo
*f
)
3663 return f
->filetype
== directory
|| f
->filetype
== arg_directory
3664 || S_ISDIR (f
->linkmode
);
3667 /* Put the name of the file that FILENAME is a symbolic link to
3668 into the LINKNAME field of 'f'. COMMAND_LINE_ARG indicates whether
3669 FILENAME is a command-line argument. */
3672 get_link_name (char const *filename
, struct fileinfo
*f
, bool command_line_arg
)
3674 f
->linkname
= areadlink_with_size (filename
, f
->stat
.st_size
);
3675 if (f
->linkname
== NULL
)
3676 file_failure (command_line_arg
, _("cannot read symbolic link %s"),
3680 /* If LINKNAME is a relative name and NAME contains one or more
3681 leading directories, return LINKNAME with those directories
3682 prepended; otherwise, return a copy of LINKNAME.
3683 If LINKNAME is NULL, return NULL. */
3686 make_link_name (char const *name
, char const *linkname
)
3691 if (IS_ABSOLUTE_FILE_NAME (linkname
))
3692 return xstrdup (linkname
);
3694 /* The link is to a relative name. Prepend any leading directory
3695 in 'name' to the link name. */
3696 size_t prefix_len
= dir_len (name
);
3697 if (prefix_len
== 0)
3698 return xstrdup (linkname
);
3700 char *p
= xmalloc (prefix_len
+ 1 + strlen (linkname
) + 1);
3702 /* PREFIX_LEN usually specifies a string not ending in slash.
3703 In that case, extend it by one, since the next byte *is* a slash.
3704 Otherwise, the prefix is "/", so leave the length unchanged. */
3705 if ( ! ISSLASH (name
[prefix_len
- 1]))
3708 stpcpy (stpncpy (p
, name
, prefix_len
), linkname
);
3712 /* Return true if the last component of NAME is '.' or '..'
3713 This is so we don't try to recurse on '././././. ...' */
3716 basename_is_dot_or_dotdot (char const *name
)
3718 char const *base
= last_component (name
);
3719 return dot_or_dotdot (base
);
3722 /* Remove any entries from CWD_FILE that are for directories,
3723 and queue them to be listed as directories instead.
3724 DIRNAME is the prefix to prepend to each dirname
3725 to make it correct relative to ls's working dir;
3726 if it is null, no prefix is needed and "." and ".." should not be ignored.
3727 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3728 This is desirable when processing directories recursively. */
3731 extract_dirs_from_files (char const *dirname
, bool command_line_arg
)
3735 bool ignore_dot_and_dot_dot
= (dirname
!= NULL
);
3737 if (dirname
&& LOOP_DETECT
)
3739 /* Insert a marker entry first. When we dequeue this marker entry,
3740 we'll know that DIRNAME has been processed and may be removed
3741 from the set of active directories. */
3742 queue_directory (NULL
, dirname
, false);
3745 /* Queue the directories last one first, because queueing reverses the
3747 for (i
= cwd_n_used
; i
-- != 0; )
3749 struct fileinfo
*f
= sorted_file
[i
];
3751 if (is_directory (f
)
3752 && (! ignore_dot_and_dot_dot
3753 || ! basename_is_dot_or_dotdot (f
->name
)))
3755 if (!dirname
|| f
->name
[0] == '/')
3756 queue_directory (f
->name
, f
->linkname
, command_line_arg
);
3759 char *name
= file_name_concat (dirname
, f
->name
, NULL
);
3760 queue_directory (name
, f
->linkname
, command_line_arg
);
3763 if (f
->filetype
== arg_directory
)
3768 /* Now delete the directories from the table, compacting all the remaining
3771 for (i
= 0, j
= 0; i
< cwd_n_used
; i
++)
3773 struct fileinfo
*f
= sorted_file
[i
];
3775 j
+= (f
->filetype
!= arg_directory
);
3780 /* Use strcoll to compare strings in this locale. If an error occurs,
3781 report an error and longjmp to failed_strcoll. */
3783 static jmp_buf failed_strcoll
;
3786 xstrcoll (char const *a
, char const *b
)
3790 diff
= strcoll (a
, b
);
3793 error (0, errno
, _("cannot compare file names %s and %s"),
3794 quote_n (0, a
), quote_n (1, b
));
3795 set_exit_status (false);
3796 longjmp (failed_strcoll
, 1);
3801 /* Comparison routines for sorting the files. */
3803 typedef void const *V
;
3804 typedef int (*qsortFunc
)(V a
, V b
);
3806 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants. */
3808 dirfirst_check (struct fileinfo
const *a
, struct fileinfo
const *b
,
3811 int diff
= is_linked_directory (b
) - is_linked_directory (a
);
3812 return diff
? diff
: cmp (a
, b
);
3815 /* Define the 8 different sort function variants required for each sortkey.
3816 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3817 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3818 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3819 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3820 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3821 /* direct, non-dirfirst versions */ \
3822 static int xstrcoll_##key_name (V a, V b) \
3823 { return key_cmp_func (a, b, xstrcoll); } \
3824 ATTRIBUTE_PURE static int strcmp_##key_name (V a, V b) \
3825 { return key_cmp_func (a, b, strcmp); } \
3827 /* reverse, non-dirfirst versions */ \
3828 static int rev_xstrcoll_##key_name (V a, V b) \
3829 { return key_cmp_func (b, a, xstrcoll); } \
3830 ATTRIBUTE_PURE static int rev_strcmp_##key_name (V a, V b) \
3831 { return key_cmp_func (b, a, strcmp); } \
3833 /* direct, dirfirst versions */ \
3834 static int xstrcoll_df_##key_name (V a, V b) \
3835 { return dirfirst_check (a, b, xstrcoll_##key_name); } \
3836 ATTRIBUTE_PURE static int strcmp_df_##key_name (V a, V b) \
3837 { return dirfirst_check (a, b, strcmp_##key_name); } \
3839 /* reverse, dirfirst versions */ \
3840 static int rev_xstrcoll_df_##key_name (V a, V b) \
3841 { return dirfirst_check (a, b, rev_xstrcoll_##key_name); } \
3842 ATTRIBUTE_PURE static int rev_strcmp_df_##key_name (V a, V b) \
3843 { return dirfirst_check (a, b, rev_strcmp_##key_name); }
3846 cmp_ctime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3847 int (*cmp
) (char const *, char const *))
3849 int diff
= timespec_cmp (get_stat_ctime (&b
->stat
),
3850 get_stat_ctime (&a
->stat
));
3851 return diff
? diff
: cmp (a
->name
, b
->name
);
3855 cmp_mtime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3856 int (*cmp
) (char const *, char const *))
3858 int diff
= timespec_cmp (get_stat_mtime (&b
->stat
),
3859 get_stat_mtime (&a
->stat
));
3860 return diff
? diff
: cmp (a
->name
, b
->name
);
3864 cmp_atime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3865 int (*cmp
) (char const *, char const *))
3867 int diff
= timespec_cmp (get_stat_atime (&b
->stat
),
3868 get_stat_atime (&a
->stat
));
3869 return diff
? diff
: cmp (a
->name
, b
->name
);
3873 cmp_btime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3874 int (*cmp
) (char const *, char const *))
3876 int diff
= timespec_cmp (get_stat_btime (&b
->stat
),
3877 get_stat_btime (&a
->stat
));
3878 return diff
? diff
: cmp (a
->name
, b
->name
);
3882 off_cmp (off_t a
, off_t b
)
3884 return a
< b
? -1 : a
> b
;
3888 cmp_size (struct fileinfo
const *a
, struct fileinfo
const *b
,
3889 int (*cmp
) (char const *, char const *))
3891 int diff
= off_cmp (b
->stat
.st_size
, a
->stat
.st_size
);
3892 return diff
? diff
: cmp (a
->name
, b
->name
);
3896 cmp_name (struct fileinfo
const *a
, struct fileinfo
const *b
,
3897 int (*cmp
) (char const *, char const *))
3899 return cmp (a
->name
, b
->name
);
3902 /* Compare file extensions. Files with no extension are 'smallest'.
3903 If extensions are the same, compare by file names instead. */
3906 cmp_extension (struct fileinfo
const *a
, struct fileinfo
const *b
,
3907 int (*cmp
) (char const *, char const *))
3909 char const *base1
= strrchr (a
->name
, '.');
3910 char const *base2
= strrchr (b
->name
, '.');
3911 int diff
= cmp (base1
? base1
: "", base2
? base2
: "");
3912 return diff
? diff
: cmp (a
->name
, b
->name
);
3915 /* Return the (cached) screen width,
3916 for the NAME associated with the passed fileinfo F. */
3919 fileinfo_name_width (struct fileinfo
const *f
)
3923 : quote_name_width (f
->name
, filename_quoting_options
, f
->quoted
);
3927 cmp_width (struct fileinfo
const *a
, struct fileinfo
const *b
,
3928 int (*cmp
) (char const *, char const *))
3930 int diff
= fileinfo_name_width (a
) - fileinfo_name_width (b
);
3931 return diff
? diff
: cmp (a
->name
, b
->name
);
3934 DEFINE_SORT_FUNCTIONS (ctime
, cmp_ctime
)
3935 DEFINE_SORT_FUNCTIONS (mtime
, cmp_mtime
)
3936 DEFINE_SORT_FUNCTIONS (atime
, cmp_atime
)
3937 DEFINE_SORT_FUNCTIONS (btime
, cmp_btime
)
3938 DEFINE_SORT_FUNCTIONS (size
, cmp_size
)
3939 DEFINE_SORT_FUNCTIONS (name
, cmp_name
)
3940 DEFINE_SORT_FUNCTIONS (extension
, cmp_extension
)
3941 DEFINE_SORT_FUNCTIONS (width
, cmp_width
)
3943 /* Compare file versions.
3944 Unlike all other compare functions above, cmp_version depends only
3945 on filevercmp, which does not fail (even for locale reasons), and does not
3946 need a secondary sort key. See lib/filevercmp.h for function description.
3948 All the other sort options, in fact, need xstrcoll and strcmp variants,
3949 because they all use a string comparison (either as the primary or secondary
3950 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3951 locale reasons. Lastly, filevercmp is ALWAYS available with gnulib. */
3953 cmp_version (struct fileinfo
const *a
, struct fileinfo
const *b
)
3955 return filevercmp (a
->name
, b
->name
);
3959 xstrcoll_version (V a
, V b
)
3961 return cmp_version (a
, b
);
3964 rev_xstrcoll_version (V a
, V b
)
3966 return cmp_version (b
, a
);
3969 xstrcoll_df_version (V a
, V b
)
3971 return dirfirst_check (a
, b
, xstrcoll_version
);
3974 rev_xstrcoll_df_version (V a
, V b
)
3976 return dirfirst_check (a
, b
, rev_xstrcoll_version
);
3980 /* We have 2^3 different variants for each sort-key function
3981 (for 3 independent sort modes).
3982 The function pointers stored in this array must be dereferenced as:
3984 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3986 Note that the order in which sort keys are listed in the function pointer
3987 array below is defined by the order of the elements in the time_type and
3990 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3993 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3994 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3997 { strcmp_##key_name, strcmp_df_##key_name }, \
3998 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
4002 static qsortFunc
const sort_functions
[][2][2][2] =
4004 LIST_SORTFUNCTION_VARIANTS (name
),
4005 LIST_SORTFUNCTION_VARIANTS (extension
),
4006 LIST_SORTFUNCTION_VARIANTS (width
),
4007 LIST_SORTFUNCTION_VARIANTS (size
),
4011 { xstrcoll_version
, xstrcoll_df_version
},
4012 { rev_xstrcoll_version
, rev_xstrcoll_df_version
},
4015 /* We use NULL for the strcmp variants of version comparison
4016 since as explained in cmp_version definition, version comparison
4017 does not rely on xstrcoll, so it will never longjmp, and never
4018 need to try the strcmp fallback. */
4025 /* last are time sort functions */
4026 LIST_SORTFUNCTION_VARIANTS (mtime
),
4027 LIST_SORTFUNCTION_VARIANTS (ctime
),
4028 LIST_SORTFUNCTION_VARIANTS (atime
),
4029 LIST_SORTFUNCTION_VARIANTS (btime
)
4032 /* The number of sort keys is calculated as the sum of
4033 the number of elements in the sort_type enum (i.e., sort_numtypes)
4034 -2 because neither sort_time nor sort_none use entries themselves
4035 the number of elements in the time_type enum (i.e., time_numtypes)
4036 This is because when sort_type==sort_time, we have up to
4037 time_numtypes possible sort keys.
4039 This line verifies at compile-time that the array of sort functions has been
4040 initialized for all possible sort keys. */
4041 verify (ARRAY_CARDINALITY (sort_functions
)
4042 == sort_numtypes
- 2 + time_numtypes
);
4044 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
4047 initialize_ordering_vector (void)
4049 for (size_t i
= 0; i
< cwd_n_used
; i
++)
4050 sorted_file
[i
] = &cwd_file
[i
];
4053 /* Cache values based on attributes global to all files. */
4056 update_current_files_info (void)
4058 /* Cache screen width of name, if needed multiple times. */
4059 if (sort_type
== sort_width
4060 || (line_length
&& (format
== many_per_line
|| format
== horizontal
)))
4063 for (i
= 0; i
< cwd_n_used
; i
++)
4065 struct fileinfo
*f
= sorted_file
[i
];
4066 f
->width
= fileinfo_name_width (f
);
4071 /* Sort the files now in the table. */
4078 if (sorted_file_alloc
< cwd_n_used
+ cwd_n_used
/ 2)
4081 sorted_file
= xnmalloc (cwd_n_used
, 3 * sizeof *sorted_file
);
4082 sorted_file_alloc
= 3 * cwd_n_used
;
4085 initialize_ordering_vector ();
4087 update_current_files_info ();
4089 if (sort_type
== sort_none
)
4092 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
4093 ignore strcoll failures, as a failing strcoll might be a
4094 comparison function that is not a total order, and if we ignored
4095 the failure this might cause qsort to dump core. */
4097 if (! setjmp (failed_strcoll
))
4098 use_strcmp
= false; /* strcoll() succeeded */
4102 assert (sort_type
!= sort_version
);
4103 initialize_ordering_vector ();
4106 /* When sort_type == sort_time, use time_type as subindex. */
4107 mpsort ((void const **) sorted_file
, cwd_n_used
,
4108 sort_functions
[sort_type
+ (sort_type
== sort_time
? time_type
: 0)]
4109 [use_strcmp
][sort_reverse
]
4110 [directories_first
]);
4113 /* List all the files now in the table. */
4116 print_current_files (void)
4123 for (i
= 0; i
< cwd_n_used
; i
++)
4125 print_file_name_and_frills (sorted_file
[i
], 0);
4132 print_with_separator (' ');
4134 print_many_per_line ();
4139 print_with_separator (' ');
4141 print_horizontal ();
4145 print_with_separator (',');
4149 for (i
= 0; i
< cwd_n_used
; i
++)
4151 set_normal_color ();
4152 print_long_format (sorted_file
[i
]);
4153 dired_outbyte (eolbyte
);
4159 /* Replace the first %b with precomputed aligned month names.
4160 Note on glibc-2.7 at least, this speeds up the whole 'ls -lU'
4161 process by around 17%, compared to letting strftime() handle the %b. */
4164 align_nstrftime (char *buf
, size_t size
, bool recent
, struct tm
const *tm
,
4165 timezone_t tz
, int ns
)
4167 char const *nfmt
= (use_abformat
4168 ? abformat
[recent
][tm
->tm_mon
]
4169 : long_time_format
[recent
]);
4170 return nstrftime (buf
, size
, nfmt
, tm
, tz
, ns
);
4173 /* Return the expected number of columns in a long-format timestamp,
4174 or zero if it cannot be calculated. */
4177 long_time_expected_width (void)
4179 static int width
= -1;
4185 char buf
[TIME_STAMP_LEN_MAXIMUM
+ 1];
4187 /* In case you're wondering if localtime_rz can fail with an input time_t
4188 value of 0, let's just say it's very unlikely, but not inconceivable.
4189 The TZ environment variable would have to specify a time zone that
4190 is 2**31-1900 years or more ahead of UTC. This could happen only on
4191 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
4192 However, this is not possible with Solaris 10 or glibc-2.3.5, since
4193 their implementations limit the offset to 167:59 and 24:00, resp. */
4194 if (localtime_rz (localtz
, &epoch
, &tm
))
4196 size_t len
= align_nstrftime (buf
, sizeof buf
, false,
4199 width
= mbsnwidth (buf
, len
, 0);
4209 /* Print the user or group name NAME, with numeric id ID, using a
4210 print width of WIDTH columns. */
4213 format_user_or_group (char const *name
, uintmax_t id
, int width
)
4217 int width_gap
= width
- mbswidth (name
, 0);
4218 int pad
= MAX (0, width_gap
);
4219 dired_outstring (name
);
4222 dired_outbyte (' ');
4226 dired_pos
+= printf ("%*"PRIuMAX
" ", width
, id
);
4229 /* Print the name or id of the user with id U, using a print width of
4233 format_user (uid_t u
, int width
, bool stat_ok
)
4235 format_user_or_group (! stat_ok
? "?" :
4236 (numeric_ids
? NULL
: getuser (u
)), u
, width
);
4239 /* Likewise, for groups. */
4242 format_group (gid_t g
, int width
, bool stat_ok
)
4244 format_user_or_group (! stat_ok
? "?" :
4245 (numeric_ids
? NULL
: getgroup (g
)), g
, width
);
4248 /* Return the number of columns that format_user_or_group will print. */
4251 format_user_or_group_width (char const *name
, uintmax_t id
)
4255 int len
= mbswidth (name
, 0);
4256 return MAX (0, len
);
4259 return snprintf (NULL
, 0, "%"PRIuMAX
, id
);
4262 /* Return the number of columns that format_user will print. */
4265 format_user_width (uid_t u
)
4267 return format_user_or_group_width (numeric_ids
? NULL
: getuser (u
), u
);
4270 /* Likewise, for groups. */
4273 format_group_width (gid_t g
)
4275 return format_user_or_group_width (numeric_ids
? NULL
: getgroup (g
), g
);
4278 /* Return a pointer to a formatted version of F->stat.st_ino,
4279 possibly using buffer, BUF, of length BUFLEN, which must be at least
4280 INT_BUFSIZE_BOUND (uintmax_t) bytes. */
4282 format_inode (char *buf
, size_t buflen
, const struct fileinfo
*f
)
4284 assert (INT_BUFSIZE_BOUND (uintmax_t) <= buflen
);
4285 return (f
->stat_ok
&& f
->stat
.st_ino
!= NOT_AN_INODE_NUMBER
4286 ? umaxtostr (f
->stat
.st_ino
, buf
)
4290 /* Print information about F in long format. */
4292 print_long_format (const struct fileinfo
*f
)
4296 [LONGEST_HUMAN_READABLE
+ 1 /* inode */
4297 + LONGEST_HUMAN_READABLE
+ 1 /* size in blocks */
4298 + sizeof (modebuf
) - 1 + 1 /* mode string */
4299 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
4300 + LONGEST_HUMAN_READABLE
+ 2 /* major device number */
4301 + LONGEST_HUMAN_READABLE
+ 1 /* minor device number */
4302 + TIME_STAMP_LEN_MAXIMUM
+ 1 /* max length of time/date */
4306 struct timespec when_timespec
;
4307 struct tm when_local
;
4308 bool btime_ok
= true;
4310 /* Compute the mode string, except remove the trailing space if no
4311 file in this directory has an ACL or security context. */
4313 filemodestring (&f
->stat
, modebuf
);
4316 modebuf
[0] = filetype_letter
[f
->filetype
];
4317 memset (modebuf
+ 1, '?', 10);
4322 else if (f
->acl_type
== ACL_T_LSM_CONTEXT_ONLY
)
4324 else if (f
->acl_type
== ACL_T_YES
)
4330 when_timespec
= get_stat_ctime (&f
->stat
);
4333 when_timespec
= get_stat_mtime (&f
->stat
);
4336 when_timespec
= get_stat_atime (&f
->stat
);
4339 when_timespec
= get_stat_btime (&f
->stat
);
4340 if (when_timespec
.tv_sec
== -1 && when_timespec
.tv_nsec
== -1)
4351 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4352 p
+= sprintf (p
, "%*s ", inode_number_width
,
4353 format_inode (hbuf
, sizeof hbuf
, f
));
4356 if (print_block_size
)
4358 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
4359 char const *blocks
=
4362 : human_readable (ST_NBLOCKS (f
->stat
), hbuf
, human_output_opts
,
4363 ST_NBLOCKSIZE
, output_block_size
));
4365 for (pad
= block_size_width
- mbswidth (blocks
, 0); 0 < pad
; pad
--)
4367 while ((*p
++ = *blocks
++))
4372 /* The last byte of the mode string is the POSIX
4373 "optional alternate access method flag". */
4375 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4376 p
+= sprintf (p
, "%s %*s ", modebuf
, nlink_width
,
4377 ! f
->stat_ok
? "?" : umaxtostr (f
->stat
.st_nlink
, hbuf
));
4382 if (print_owner
|| print_group
|| print_author
|| print_scontext
)
4384 dired_outbuf (buf
, p
- buf
);
4387 format_user (f
->stat
.st_uid
, owner_width
, f
->stat_ok
);
4390 format_group (f
->stat
.st_gid
, group_width
, f
->stat_ok
);
4393 format_user (f
->stat
.st_author
, author_width
, f
->stat_ok
);
4396 format_user_or_group (f
->scontext
, 0, scontext_width
);
4402 && (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
)))
4404 char majorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4405 char minorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4406 int blanks_width
= (file_size_width
4407 - (major_device_number_width
+ 2
4408 + minor_device_number_width
));
4409 p
+= sprintf (p
, "%*s, %*s ",
4410 major_device_number_width
+ MAX (0, blanks_width
),
4411 umaxtostr (major (f
->stat
.st_rdev
), majorbuf
),
4412 minor_device_number_width
,
4413 umaxtostr (minor (f
->stat
.st_rdev
), minorbuf
));
4417 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
4421 : human_readable (unsigned_file_size (f
->stat
.st_size
),
4422 hbuf
, file_human_output_opts
, 1,
4423 file_output_block_size
));
4425 for (pad
= file_size_width
- mbswidth (size
, 0); 0 < pad
; pad
--)
4427 while ((*p
++ = *size
++))
4435 if (f
->stat_ok
&& btime_ok
4436 && localtime_rz (localtz
, &when_timespec
.tv_sec
, &when_local
))
4438 struct timespec six_months_ago
;
4441 /* If the file appears to be in the future, update the current
4442 time, in case the file happens to have been modified since
4443 the last time we checked the clock. */
4444 if (timespec_cmp (current_time
, when_timespec
) < 0)
4445 gettime (¤t_time
);
4447 /* Consider a time to be recent if it is within the past six months.
4448 A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952 seconds
4449 on the average. Write this value as an integer constant to
4450 avoid floating point hassles. */
4451 six_months_ago
.tv_sec
= current_time
.tv_sec
- 31556952 / 2;
4452 six_months_ago
.tv_nsec
= current_time
.tv_nsec
;
4454 recent
= (timespec_cmp (six_months_ago
, when_timespec
) < 0
4455 && timespec_cmp (when_timespec
, current_time
) < 0);
4457 /* We assume here that all time zones are offset from UTC by a
4458 whole number of seconds. */
4459 s
= align_nstrftime (p
, TIME_STAMP_LEN_MAXIMUM
+ 1, recent
,
4460 &when_local
, localtz
, when_timespec
.tv_nsec
);
4470 /* The time cannot be converted using the desired format, so
4471 print it as a huge integer number of seconds. */
4472 char hbuf
[INT_BUFSIZE_BOUND (intmax_t)];
4473 p
+= sprintf (p
, "%*s ", long_time_expected_width (),
4474 (! f
->stat_ok
|| ! btime_ok
4476 : timetostr (when_timespec
.tv_sec
, hbuf
)));
4477 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
4480 dired_outbuf (buf
, p
- buf
);
4481 size_t w
= print_name_with_quoting (f
, false, &dired_obstack
, p
- buf
);
4483 if (f
->filetype
== symbolic_link
)
4487 dired_outstring (" -> ");
4488 print_name_with_quoting (f
, true, NULL
, (p
- buf
) + w
+ 4);
4489 if (indicator_style
!= none
)
4490 print_type_indicator (true, f
->linkmode
, unknown
);
4493 else if (indicator_style
!= none
)
4494 print_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
4497 /* Write to *BUF a quoted representation of the file name NAME, if non-NULL,
4498 using OPTIONS to control quoting. *BUF is set to NAME if no quoting
4499 is required. *BUF is allocated if more space required (and the original
4500 *BUF is not deallocated).
4501 Store the number of screen columns occupied by NAME's quoted
4502 representation into WIDTH, if non-NULL.
4503 Store into PAD whether an initial space is needed for padding.
4504 Return the number of bytes in *BUF. */
4507 quote_name_buf (char **inbuf
, size_t bufsize
, char *name
,
4508 struct quoting_options
const *options
,
4509 int needs_general_quoting
, size_t *width
, bool *pad
)
4512 size_t displayed_width
IF_LINT ( = 0);
4516 enum quoting_style qs
= get_quoting_style (options
);
4517 bool needs_further_quoting
= qmark_funny_chars
4518 && (qs
== shell_quoting_style
4519 || qs
== shell_always_quoting_style
4520 || qs
== literal_quoting_style
);
4522 if (needs_general_quoting
!= 0)
4524 len
= quotearg_buffer (buf
, bufsize
, name
, -1, options
);
4527 buf
= xmalloc (len
+ 1);
4528 quotearg_buffer (buf
, len
+ 1, name
, -1, options
);
4531 quoted
= (*name
!= *buf
) || strlen (name
) != len
;
4533 else if (needs_further_quoting
)
4535 len
= strlen (name
);
4537 buf
= xmalloc (len
+ 1);
4538 memcpy (buf
, name
, len
+ 1);
4544 len
= strlen (name
);
4549 if (needs_further_quoting
)
4553 char const *p
= buf
;
4554 char const *plimit
= buf
+ len
;
4556 displayed_width
= 0;
4561 case ' ': case '!': case '"': case '#': case '%':
4562 case '&': case '\'': case '(': case ')': case '*':
4563 case '+': case ',': case '-': case '.': case '/':
4564 case '0': case '1': case '2': case '3': case '4':
4565 case '5': case '6': case '7': case '8': case '9':
4566 case ':': case ';': case '<': case '=': case '>':
4568 case 'A': case 'B': case 'C': case 'D': case 'E':
4569 case 'F': case 'G': case 'H': case 'I': case 'J':
4570 case 'K': case 'L': case 'M': case 'N': case 'O':
4571 case 'P': case 'Q': case 'R': case 'S': case 'T':
4572 case 'U': case 'V': case 'W': case 'X': case 'Y':
4574 case '[': case '\\': case ']': case '^': case '_':
4575 case 'a': case 'b': case 'c': case 'd': case 'e':
4576 case 'f': case 'g': case 'h': case 'i': case 'j':
4577 case 'k': case 'l': case 'm': case 'n': case 'o':
4578 case 'p': case 'q': case 'r': case 's': case 't':
4579 case 'u': case 'v': case 'w': case 'x': case 'y':
4580 case 'z': case '{': case '|': case '}': case '~':
4581 /* These characters are printable ASCII characters. */
4583 displayed_width
+= 1;
4586 /* If we have a multibyte sequence, copy it until we
4587 reach its end, replacing each non-printable multibyte
4588 character with a single question mark. */
4590 mbstate_t mbstate
= { 0, };
4597 bytes
= mbrtowc (&wc
, p
, plimit
- p
, &mbstate
);
4599 if (bytes
== (size_t) -1)
4601 /* An invalid multibyte sequence was
4602 encountered. Skip one input byte, and
4603 put a question mark. */
4606 displayed_width
+= 1;
4610 if (bytes
== (size_t) -2)
4612 /* An incomplete multibyte character
4613 at the end. Replace it entirely with
4617 displayed_width
+= 1;
4622 /* A null wide character was encountered. */
4628 /* A printable multibyte character.
4630 for (; bytes
> 0; --bytes
)
4632 displayed_width
+= w
;
4636 /* An unprintable multibyte character.
4637 Replace it entirely with a question
4641 displayed_width
+= 1;
4644 while (! mbsinit (&mbstate
));
4649 /* The buffer may have shrunk. */
4655 char const *plimit
= buf
+ len
;
4659 if (! isprint (to_uchar (*p
)))
4663 displayed_width
= len
;
4666 else if (width
!= NULL
)
4669 displayed_width
= mbsnwidth (buf
, len
, 0);
4672 char const *p
= buf
;
4673 char const *plimit
= buf
+ len
;
4675 displayed_width
= 0;
4678 if (isprint (to_uchar (*p
)))
4685 /* Set padding to better align quoted items,
4686 and also give a visual indication that quotes are
4687 not actually part of the name. */
4688 *pad
= (align_variable_outer_quotes
&& cwd_some_quoted
&& ! quoted
);
4691 *width
= displayed_width
;
4699 quote_name_width (char const *name
, struct quoting_options
const *options
,
4700 int needs_general_quoting
)
4702 char smallbuf
[BUFSIZ
];
4703 char *buf
= smallbuf
;
4707 quote_name_buf (&buf
, sizeof smallbuf
, (char *) name
, options
,
4708 needs_general_quoting
, &width
, &pad
);
4710 if (buf
!= smallbuf
&& buf
!= name
)
4718 /* %XX escape any input out of range as defined in RFC3986,
4719 and also if PATH, convert all path separators to '/'. */
4721 file_escape (char const *str
, bool path
)
4723 char *esc
= xnmalloc (3, strlen (str
) + 1);
4727 if (path
&& ISSLASH (*str
))
4732 else if (RFC3986
[to_uchar (*str
)])
4735 p
+= sprintf (p
, "%%%02x", to_uchar (*str
++));
4742 quote_name (char const *name
, struct quoting_options
const *options
,
4743 int needs_general_quoting
, const struct bin_str
*color
,
4744 bool allow_pad
, struct obstack
*stack
, char const *absolute_name
)
4746 char smallbuf
[BUFSIZ
];
4747 char *buf
= smallbuf
;
4751 len
= quote_name_buf (&buf
, sizeof smallbuf
, (char *) name
, options
,
4752 needs_general_quoting
, NULL
, &pad
);
4754 if (pad
&& allow_pad
)
4755 dired_outbyte (' ');
4758 print_color_indicator (color
);
4760 /* If we're padding, then don't include the outer quotes in
4761 the --hyperlink, to improve the alignment of those links. */
4762 bool skip_quotes
= false;
4766 if (align_variable_outer_quotes
&& cwd_some_quoted
&& ! pad
)
4771 char *h
= file_escape (hostname
, /* path= */ false);
4772 char *n
= file_escape (absolute_name
, /* path= */ true);
4773 /* TODO: It would be good to be able to define parameters
4774 to give hints to the terminal as how best to render the URI.
4775 For example since ls is outputting a dense block of URIs
4776 it would be best to not underline by default, and only
4777 do so upon hover etc. */
4778 printf ("\033]8;;file://%s%s%s\a", h
, *n
== '/' ? "" : "/", n
);
4784 push_current_dired_pos (stack
);
4786 fwrite (buf
+ skip_quotes
, 1, len
- (skip_quotes
* 2), stdout
);
4791 push_current_dired_pos (stack
);
4795 fputs ("\033]8;;\a", stdout
);
4797 putchar (*(buf
+ len
- 1));
4800 if (buf
!= smallbuf
&& buf
!= name
)
4807 print_name_with_quoting (const struct fileinfo
*f
,
4808 bool symlink_target
,
4809 struct obstack
*stack
,
4812 char const *name
= symlink_target
? f
->linkname
: f
->name
;
4814 const struct bin_str
*color
= print_with_color
?
4815 get_color_indicator (f
, symlink_target
) : NULL
;
4817 bool used_color_this_time
= (print_with_color
4818 && (color
|| is_colored (C_NORM
)));
4820 size_t len
= quote_name (name
, filename_quoting_options
, f
->quoted
,
4821 color
, !symlink_target
, stack
, f
->absolute_name
);
4824 if (used_color_this_time
)
4826 prep_non_filename_text ();
4828 /* We use the byte length rather than display width here as
4829 an optimization to avoid accurately calculating the width,
4830 because we only output the clear to EOL sequence if the name
4831 _might_ wrap to the next line. This may output a sequence
4832 unnecessarily in multi-byte locales for example,
4833 but in that case it's inconsequential to the output. */
4835 && (start_col
/ line_length
!= (start_col
+ len
- 1) / line_length
))
4836 put_indicator (&color_indicator
[C_CLR_TO_EOL
]);
4843 prep_non_filename_text (void)
4845 if (color_indicator
[C_END
].string
!= NULL
)
4846 put_indicator (&color_indicator
[C_END
]);
4849 put_indicator (&color_indicator
[C_LEFT
]);
4850 put_indicator (&color_indicator
[C_RESET
]);
4851 put_indicator (&color_indicator
[C_RIGHT
]);
4855 /* Print the file name of 'f' with appropriate quoting.
4856 Also print file size, inode number, and filetype indicator character,
4857 as requested by switches. */
4860 print_file_name_and_frills (const struct fileinfo
*f
, size_t start_col
)
4862 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
4864 set_normal_color ();
4867 printf ("%*s ", format
== with_commas
? 0 : inode_number_width
,
4868 format_inode (buf
, sizeof buf
, f
));
4870 if (print_block_size
)
4871 printf ("%*s ", format
== with_commas
? 0 : block_size_width
,
4873 : human_readable (ST_NBLOCKS (f
->stat
), buf
, human_output_opts
,
4874 ST_NBLOCKSIZE
, output_block_size
));
4877 printf ("%*s ", format
== with_commas
? 0 : scontext_width
, f
->scontext
);
4879 size_t width
= print_name_with_quoting (f
, false, NULL
, start_col
);
4881 if (indicator_style
!= none
)
4882 width
+= print_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
4887 /* Given these arguments describing a file, return the single-byte
4888 type indicator, or 0. */
4890 get_type_indicator (bool stat_ok
, mode_t mode
, enum filetype type
)
4894 if (stat_ok
? S_ISREG (mode
) : type
== normal
)
4896 if (stat_ok
&& indicator_style
== classify
&& (mode
& S_IXUGO
))
4903 if (stat_ok
? S_ISDIR (mode
) : type
== directory
|| type
== arg_directory
)
4905 else if (indicator_style
== slash
)
4907 else if (stat_ok
? S_ISLNK (mode
) : type
== symbolic_link
)
4909 else if (stat_ok
? S_ISFIFO (mode
) : type
== fifo
)
4911 else if (stat_ok
? S_ISSOCK (mode
) : type
== sock
)
4913 else if (stat_ok
&& S_ISDOOR (mode
))
4922 print_type_indicator (bool stat_ok
, mode_t mode
, enum filetype type
)
4924 char c
= get_type_indicator (stat_ok
, mode
, type
);
4930 /* Returns if color sequence was printed. */
4932 print_color_indicator (const struct bin_str
*ind
)
4936 /* Need to reset so not dealing with attribute combinations */
4937 if (is_colored (C_NORM
))
4938 restore_default_color ();
4939 put_indicator (&color_indicator
[C_LEFT
]);
4940 put_indicator (ind
);
4941 put_indicator (&color_indicator
[C_RIGHT
]);
4947 /* Returns color indicator or NULL if none. */
4949 static const struct bin_str
*
4950 get_color_indicator (const struct fileinfo
*f
, bool symlink_target
)
4952 enum indicator_no type
;
4953 struct color_ext_type
*ext
; /* Color extension */
4954 size_t len
; /* Length of name */
4963 linkok
= f
->linkok
? 0 : -1;
4968 mode
= file_or_link_mode (f
);
4972 /* Is this a nonexistent file? If so, linkok == -1. */
4974 if (linkok
== -1 && is_colored (C_MISSING
))
4976 else if (!f
->stat_ok
)
4978 static enum indicator_no filetype_indicator
[] = FILETYPE_INDICATORS
;
4979 type
= filetype_indicator
[f
->filetype
];
4987 if ((mode
& S_ISUID
) != 0 && is_colored (C_SETUID
))
4989 else if ((mode
& S_ISGID
) != 0 && is_colored (C_SETGID
))
4991 else if (is_colored (C_CAP
) && f
->has_capability
)
4993 else if ((mode
& S_IXUGO
) != 0 && is_colored (C_EXEC
))
4995 else if ((1 < f
->stat
.st_nlink
) && is_colored (C_MULTIHARDLINK
))
4996 type
= C_MULTIHARDLINK
;
4998 else if (S_ISDIR (mode
))
5002 if ((mode
& S_ISVTX
) && (mode
& S_IWOTH
)
5003 && is_colored (C_STICKY_OTHER_WRITABLE
))
5004 type
= C_STICKY_OTHER_WRITABLE
;
5005 else if ((mode
& S_IWOTH
) != 0 && is_colored (C_OTHER_WRITABLE
))
5006 type
= C_OTHER_WRITABLE
;
5007 else if ((mode
& S_ISVTX
) != 0 && is_colored (C_STICKY
))
5010 else if (S_ISLNK (mode
))
5012 else if (S_ISFIFO (mode
))
5014 else if (S_ISSOCK (mode
))
5016 else if (S_ISBLK (mode
))
5018 else if (S_ISCHR (mode
))
5020 else if (S_ISDOOR (mode
))
5024 /* Classify a file of some other type as C_ORPHAN. */
5029 /* Check the file's suffix only if still classified as C_FILE. */
5033 /* Test if NAME has a recognized suffix. */
5035 len
= strlen (name
);
5036 name
+= len
; /* Pointer to final \0. */
5037 for (ext
= color_ext_list
; ext
!= NULL
; ext
= ext
->next
)
5039 if (ext
->ext
.len
<= len
5040 && c_strncasecmp (name
- ext
->ext
.len
, ext
->ext
.string
,
5046 /* Adjust the color for orphaned symlinks. */
5047 if (type
== C_LINK
&& !linkok
)
5049 if (color_symlink_as_referent
|| is_colored (C_ORPHAN
))
5053 const struct bin_str
*const s
5054 = ext
? &(ext
->seq
) : &color_indicator
[type
];
5056 return s
->string
? s
: NULL
;
5059 /* Output a color indicator (which may contain nulls). */
5061 put_indicator (const struct bin_str
*ind
)
5067 /* If the standard output is a controlling terminal, watch out
5068 for signals, so that the colors can be restored to the
5069 default state if "ls" is suspended or interrupted. */
5071 if (0 <= tcgetpgrp (STDOUT_FILENO
))
5074 prep_non_filename_text ();
5077 fwrite (ind
->string
, ind
->len
, 1, stdout
);
5081 length_of_file_name_and_frills (const struct fileinfo
*f
)
5084 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
5087 len
+= 1 + (format
== with_commas
5088 ? strlen (umaxtostr (f
->stat
.st_ino
, buf
))
5089 : inode_number_width
);
5091 if (print_block_size
)
5092 len
+= 1 + (format
== with_commas
5093 ? strlen (! f
->stat_ok
? "?"
5094 : human_readable (ST_NBLOCKS (f
->stat
), buf
,
5095 human_output_opts
, ST_NBLOCKSIZE
,
5097 : block_size_width
);
5100 len
+= 1 + (format
== with_commas
? strlen (f
->scontext
) : scontext_width
);
5102 len
+= fileinfo_name_width (f
);
5104 if (indicator_style
!= none
)
5106 char c
= get_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
5114 print_many_per_line (void)
5116 size_t row
; /* Current row. */
5117 size_t cols
= calculate_columns (true);
5118 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
5120 /* Calculate the number of rows that will be in each column except possibly
5121 for a short column on the right. */
5122 size_t rows
= cwd_n_used
/ cols
+ (cwd_n_used
% cols
!= 0);
5124 for (row
= 0; row
< rows
; row
++)
5127 size_t filesno
= row
;
5130 /* Print the next row. */
5133 struct fileinfo
const *f
= sorted_file
[filesno
];
5134 size_t name_length
= length_of_file_name_and_frills (f
);
5135 size_t max_name_length
= line_fmt
->col_arr
[col
++];
5136 print_file_name_and_frills (f
, pos
);
5139 if (filesno
>= cwd_n_used
)
5142 indent (pos
+ name_length
, pos
+ max_name_length
);
5143 pos
+= max_name_length
;
5150 print_horizontal (void)
5154 size_t cols
= calculate_columns (false);
5155 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
5156 struct fileinfo
const *f
= sorted_file
[0];
5157 size_t name_length
= length_of_file_name_and_frills (f
);
5158 size_t max_name_length
= line_fmt
->col_arr
[0];
5160 /* Print first entry. */
5161 print_file_name_and_frills (f
, 0);
5164 for (filesno
= 1; filesno
< cwd_n_used
; ++filesno
)
5166 size_t col
= filesno
% cols
;
5175 indent (pos
+ name_length
, pos
+ max_name_length
);
5176 pos
+= max_name_length
;
5179 f
= sorted_file
[filesno
];
5180 print_file_name_and_frills (f
, pos
);
5182 name_length
= length_of_file_name_and_frills (f
);
5183 max_name_length
= line_fmt
->col_arr
[col
];
5188 /* Output name + SEP + ' '. */
5191 print_with_separator (char sep
)
5196 for (filesno
= 0; filesno
< cwd_n_used
; filesno
++)
5198 struct fileinfo
const *f
= sorted_file
[filesno
];
5199 size_t len
= line_length
? length_of_file_name_and_frills (f
) : 0;
5206 || ((pos
+ len
+ 2 < line_length
)
5207 && (pos
<= SIZE_MAX
- len
- 2)))
5215 separator
= eolbyte
;
5219 putchar (separator
);
5222 print_file_name_and_frills (f
, pos
);
5228 /* Assuming cursor is at position FROM, indent up to position TO.
5229 Use a TAB character instead of two or more spaces whenever possible. */
5232 indent (size_t from
, size_t to
)
5236 if (tabsize
!= 0 && to
/ tabsize
> (from
+ 1) / tabsize
)
5239 from
+= tabsize
- from
% tabsize
;
5249 /* Put DIRNAME/NAME into DEST, handling '.' and '/' properly. */
5250 /* FIXME: maybe remove this function someday. See about using a
5251 non-malloc'ing version of file_name_concat. */
5254 attach (char *dest
, char const *dirname
, char const *name
)
5256 char const *dirnamep
= dirname
;
5258 /* Copy dirname if it is not ".". */
5259 if (dirname
[0] != '.' || dirname
[1] != 0)
5262 *dest
++ = *dirnamep
++;
5263 /* Add '/' if 'dirname' doesn't already end with it. */
5264 if (dirnamep
> dirname
&& dirnamep
[-1] != '/')
5272 /* Allocate enough column info suitable for the current number of
5273 files and display columns, and initialize the info to represent the
5274 narrowest possible columns. */
5277 init_column_info (size_t max_cols
)
5281 /* Currently allocated columns in column_info. */
5282 static size_t column_info_alloc
;
5284 if (column_info_alloc
< max_cols
)
5286 size_t new_column_info_alloc
;
5289 if (!max_idx
|| max_cols
< max_idx
/ 2)
5291 /* The number of columns is far less than the display width
5292 allows. Grow the allocation, but only so that it's
5293 double the current requirements. If the display is
5294 extremely wide, this avoids allocating a lot of memory
5295 that is never needed. */
5296 column_info
= xnrealloc (column_info
, max_cols
,
5297 2 * sizeof *column_info
);
5298 new_column_info_alloc
= 2 * max_cols
;
5302 column_info
= xnrealloc (column_info
, max_idx
, sizeof *column_info
);
5303 new_column_info_alloc
= max_idx
;
5306 /* Allocate the new size_t objects by computing the triangle
5307 formula n * (n + 1) / 2, except that we don't need to
5308 allocate the part of the triangle that we've already
5309 allocated. Check for address arithmetic overflow. */
5311 size_t column_info_growth
= new_column_info_alloc
- column_info_alloc
;
5312 size_t s
= column_info_alloc
+ 1 + new_column_info_alloc
;
5313 size_t t
= s
* column_info_growth
;
5314 if (s
< new_column_info_alloc
|| t
/ column_info_growth
!= s
)
5316 p
= xnmalloc (t
/ 2, sizeof *p
);
5319 /* Grow the triangle by parceling out the cells just allocated. */
5320 for (i
= column_info_alloc
; i
< new_column_info_alloc
; i
++)
5322 column_info
[i
].col_arr
= p
;
5326 column_info_alloc
= new_column_info_alloc
;
5329 for (i
= 0; i
< max_cols
; ++i
)
5333 column_info
[i
].valid_len
= true;
5334 column_info
[i
].line_len
= (i
+ 1) * MIN_COLUMN_WIDTH
;
5335 for (j
= 0; j
<= i
; ++j
)
5336 column_info
[i
].col_arr
[j
] = MIN_COLUMN_WIDTH
;
5340 /* Calculate the number of columns needed to represent the current set
5341 of files in the current display width. */
5344 calculate_columns (bool by_columns
)
5346 size_t filesno
; /* Index into cwd_file. */
5347 size_t cols
; /* Number of files across. */
5349 /* Normally the maximum number of columns is determined by the
5350 screen width. But if few files are available this might limit it
5352 size_t max_cols
= 0 < max_idx
&& max_idx
< cwd_n_used
? max_idx
: cwd_n_used
;
5354 init_column_info (max_cols
);
5356 /* Compute the maximum number of possible columns. */
5357 for (filesno
= 0; filesno
< cwd_n_used
; ++filesno
)
5359 struct fileinfo
const *f
= sorted_file
[filesno
];
5360 size_t name_length
= length_of_file_name_and_frills (f
);
5362 for (size_t i
= 0; i
< max_cols
; ++i
)
5364 if (column_info
[i
].valid_len
)
5366 size_t idx
= (by_columns
5367 ? filesno
/ ((cwd_n_used
+ i
) / (i
+ 1))
5368 : filesno
% (i
+ 1));
5369 size_t real_length
= name_length
+ (idx
== i
? 0 : 2);
5371 if (column_info
[i
].col_arr
[idx
] < real_length
)
5373 column_info
[i
].line_len
+= (real_length
5374 - column_info
[i
].col_arr
[idx
]);
5375 column_info
[i
].col_arr
[idx
] = real_length
;
5376 column_info
[i
].valid_len
= (column_info
[i
].line_len
5383 /* Find maximum allowed columns. */
5384 for (cols
= max_cols
; 1 < cols
; --cols
)
5386 if (column_info
[cols
- 1].valid_len
)
5396 if (status
!= EXIT_SUCCESS
)
5400 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name
);
5402 List information about the FILEs (the current directory by default).\n\
5403 Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n\
5406 emit_mandatory_arg_note ();
5409 -a, --all do not ignore entries starting with .\n\
5410 -A, --almost-all do not list implied . and ..\n\
5411 --author with -l, print the author of each file\n\
5412 -b, --escape print C-style escapes for nongraphic characters\n\
5415 --block-size=SIZE with -l, scale sizes by SIZE when printing them;\n\
5416 e.g., '--block-size=M'; see SIZE format below\n\
5419 -B, --ignore-backups do not list implied entries ending with ~\n\
5420 -c with -lt: sort by, and show, ctime (time of last\n\
5421 modification of file status information);\n\
5422 with -l: show ctime and sort by name;\n\
5423 otherwise: sort by ctime, newest first\n\
5426 -C list entries by columns\n\
5427 --color[=WHEN] color the output WHEN; more info below\n\
5428 -d, --directory list directories themselves, not their contents\n\
5429 -D, --dired generate output designed for Emacs' dired mode\n\
5432 -f list all entries in directory order\n\
5433 -F, --classify[=WHEN] append indicator (one of */=>@|) to entries WHEN\n\
5434 --file-type likewise, except do not append '*'\n\
5435 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
5436 single-column -1, verbose -l, vertical -C\n\
5437 --full-time like -l --time-style=full-iso\n\
5440 -g like -l, but do not list owner\n\
5443 --group-directories-first\n\
5444 group directories before files;\n\
5445 can be augmented with a --sort option, but any\n\
5446 use of --sort=none (-U) disables grouping\n\
5449 -G, --no-group in a long listing, don't print group names\n\
5452 -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc.\n\
5453 --si likewise, but use powers of 1000 not 1024\n\
5456 -H, --dereference-command-line\n\
5457 follow symbolic links listed on the command line\n\
5458 --dereference-command-line-symlink-to-dir\n\
5459 follow each command line symbolic link\n\
5460 that points to a directory\n\
5461 --hide=PATTERN do not list implied entries matching shell PATTERN\
5463 (overridden by -a or -A)\n\
5466 --hyperlink[=WHEN] hyperlink file names WHEN\n\
5469 --indicator-style=WORD append indicator with style WORD to entry names:\
5471 none (default), slash (-p),\n\
5472 file-type (--file-type), classify (-F)\n\
5473 -i, --inode print the index number of each file\n\
5474 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\
5478 -k, --kibibytes default to 1024-byte blocks for file system usage;\
5480 used only with -s and per directory totals\n\
5483 -l use a long listing format\n\
5484 -L, --dereference when showing file information for a symbolic\n\
5485 link, show information for the file the link\n\
5486 references rather than for the link itself\n\
5487 -m fill width with a comma separated list of entries\
5491 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
5492 -N, --literal print entry names without quoting\n\
5493 -o like -l, but do not list group information\n\
5494 -p, --indicator-style=slash\n\
5495 append / indicator to directories\n\
5498 -q, --hide-control-chars print ? instead of nongraphic characters\n\
5499 --show-control-chars show nongraphic characters as-is (the default,\n\
5500 unless program is 'ls' and output is a terminal)\
5502 -Q, --quote-name enclose entry names in double quotes\n\
5503 --quoting-style=WORD use quoting style WORD for entry names:\n\
5504 literal, locale, shell, shell-always,\n\
5505 shell-escape, shell-escape-always, c, escape\n\
5506 (overrides QUOTING_STYLE environment variable)\n\
5509 -r, --reverse reverse order while sorting\n\
5510 -R, --recursive list subdirectories recursively\n\
5511 -s, --size print the allocated size of each file, in blocks\n\
5514 -S sort by file size, largest first\n\
5515 --sort=WORD sort by WORD instead of name: none (-U), size (-S)\
5517 time (-t), version (-v), extension (-X), width\n\
5518 --time=WORD change the default of using modification times;\n\
5519 access time (-u): atime, access, use;\n\
5520 change time (-c): ctime, status;\n\
5521 birth time: birth, creation;\n\
5522 with -l, WORD determines which time to show;\n\
5523 with --sort=time, sort by WORD (newest first)\n\
5526 --time-style=TIME_STYLE time/date format with -l; see TIME_STYLE below\n\
5529 -t sort by time, newest first; see --time\n\
5530 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
5533 -u with -lt: sort by, and show, access time;\n\
5534 with -l: show access time and sort by name;\n\
5535 otherwise: sort by access time, newest first\n\
5536 -U do not sort; list entries in directory order\n\
5537 -v natural sort of (version) numbers within text\n\
5540 -w, --width=COLS set output width to COLS. 0 means no limit\n\
5541 -x list entries by lines instead of by columns\n\
5542 -X sort alphabetically by entry extension\n\
5543 -Z, --context print any security context of each file\n\
5544 --zero end each output line with NUL, not newline\n\
5545 -1 list one file per line\n\
5547 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
5548 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
5552 The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT.\n\
5553 FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2,\n\
5554 then FORMAT1 applies to non-recent files and FORMAT2 to recent files.\n\
5555 TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale.\n\
5556 Also the TIME_STYLE environment variable sets the default style to use.\n\
5560 The WHEN argument defaults to 'always' and can also be 'auto' or 'never'.\n\
5564 Using color to distinguish file types is disabled both by default and\n\
5565 with --color=never. With --color=auto, ls emits color codes only when\n\
5566 standard output is connected to a terminal. The LS_COLORS environment\n\
5567 variable can change the settings. Use the dircolors command to set it.\n\
5573 1 if minor problems (e.g., cannot access subdirectory),\n\
5574 2 if serious trouble (e.g., cannot access command-line argument).\n\
5576 emit_ancillary_info (PROGRAM_NAME
);