1 /* 'dir', 'vdir' and 'ls' directory listing programs for GNU.
2 Copyright (C) 1985-2023 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>
57 #include <selinux/selinux.h>
60 #if HAVE_LANGINFO_CODESET
61 # include <langinfo.h>
64 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
67 # define SA_NOCLDSTOP 0
68 # define sigprocmask(How, Set, Oset) /* empty */
70 # if ! HAVE_SIGINTERRUPT
71 # define siginterrupt(sig, flag) /* empty */
75 /* NonStop circa 2011 lacks both SA_RESTART and siginterrupt, so don't
76 restart syscalls after a signal handler fires. This may cause
77 colors to get messed up on the screen if 'ls' is interrupted, but
78 that's the best we can do on such a platform. */
89 #include "c-strcase.h"
91 #include "filenamecat.h"
92 #include "hard-locale.h"
96 #include "filevercmp.h"
104 #include "stat-size.h"
105 #include "stat-time.h"
106 #include "strftime.h"
107 #include "xdectoint.h"
109 #include "xstrtol-error.h"
110 #include "areadlink.h"
111 #include "dircolors.h"
112 #include "xgethostname.h"
114 #include "canonicalize.h"
117 /* Include <sys/capability.h> last to avoid a clash of <sys/types.h>
118 include guards with some premature versions of libcap.
119 For more details, see <https://bugzilla.redhat.com/483548>. */
121 # include <sys/capability.h>
124 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
125 : (ls_mode == LS_MULTI_COL \
129 proper_name ("Richard M. Stallman"), \
130 proper_name ("David MacKenzie")
132 #define obstack_chunk_alloc malloc
133 #define obstack_chunk_free free
135 /* Unix-based readdir implementations have historically returned a dirent.d_ino
136 value that is sometimes not equal to the stat-obtained st_ino value for
137 that same entry. This error occurs for a readdir entry that refers
138 to a mount point. readdir's error is to return the inode number of
139 the underlying directory -- one that typically cannot be stat'ed, as
140 long as a file system is mounted on that directory. RELIABLE_D_INO
141 encapsulates whether we can use the more efficient approach of relying
142 on readdir-supplied d_ino values, or whether we must incur the cost of
143 calling stat or lstat to obtain each guaranteed-valid inode number. */
145 #ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
146 # define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
149 #if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
150 # define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
152 # define RELIABLE_D_INO(dp) D_INO (dp)
155 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
156 # define st_author st_uid
173 /* Display letters and indicators for each filetype.
174 Keep these in sync with enum filetype. */
175 static char const filetype_letter
[] = "?pcdb-lswd";
177 /* Ensure that filetype and filetype_letter have the same
178 number of elements. */
179 static_assert (sizeof filetype_letter
- 1 == arg_directory
+ 1);
181 #define FILETYPE_INDICATORS \
183 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
184 C_LINK, C_SOCK, C_FILE, C_DIR \
190 ACL_T_LSM_CONTEXT_ONLY
,
199 /* For symbolic link, name of the file linked to, otherwise zero. */
202 /* For terminal hyperlinks. */
207 enum filetype filetype
;
209 /* For symbolic link and long listing, st_mode of file linked to, otherwise
213 /* security context. */
218 /* For symbolic link and color printing, true if linked-to file
219 exists, otherwise false. */
222 /* For long listings, true if the file has an access control list,
223 or a security context. */
224 enum acl_type acl_type
;
226 /* For color listings, true if a regular file has capability info. */
229 /* Whether file name needs quoting. tri-state with -1 == unknown. */
232 /* Cached screen width (including quoting). */
236 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
238 /* Null is a valid character in a color indicator (think about Epson
239 printers, for example) so we have to use a length/buffer string
244 size_t len
; /* Number of bytes */
245 char const *string
; /* Pointer to the same */
249 # define tcgetpgrp(Fd) 0
252 static size_t quote_name (char const *name
,
253 struct quoting_options
const *options
,
254 int needs_general_quoting
,
255 const struct bin_str
*color
,
256 bool allow_pad
, struct obstack
*stack
,
257 char const *absolute_name
);
258 static size_t quote_name_buf (char **inbuf
, size_t bufsize
, char *name
,
259 struct quoting_options
const *options
,
260 int needs_general_quoting
, size_t *width
,
262 static int decode_switches (int argc
, char **argv
);
263 static bool file_ignored (char const *name
);
264 static uintmax_t gobble_file (char const *name
, enum filetype type
,
265 ino_t inode
, bool command_line_arg
,
266 char const *dirname
);
267 static const struct bin_str
* get_color_indicator (const struct fileinfo
*f
,
268 bool symlink_target
);
269 static bool print_color_indicator (const struct bin_str
*ind
);
270 static void put_indicator (const struct bin_str
*ind
);
271 static void add_ignore_pattern (char const *pattern
);
272 static void attach (char *dest
, char const *dirname
, char const *name
);
273 static void clear_files (void);
274 static void extract_dirs_from_files (char const *dirname
,
275 bool command_line_arg
);
276 static void get_link_name (char const *filename
, struct fileinfo
*f
,
277 bool command_line_arg
);
278 static void indent (size_t from
, size_t to
);
279 static size_t calculate_columns (bool by_columns
);
280 static void print_current_files (void);
281 static void print_dir (char const *name
, char const *realname
,
282 bool command_line_arg
);
283 static size_t print_file_name_and_frills (const struct fileinfo
*f
,
285 static void print_horizontal (void);
286 static int format_user_width (uid_t u
);
287 static int format_group_width (gid_t g
);
288 static void print_long_format (const struct fileinfo
*f
);
289 static void print_many_per_line (void);
290 static size_t print_name_with_quoting (const struct fileinfo
*f
,
292 struct obstack
*stack
,
294 static void prep_non_filename_text (void);
295 static bool print_type_indicator (bool stat_ok
, mode_t mode
,
297 static void print_with_separator (char sep
);
298 static void queue_directory (char const *name
, char const *realname
,
299 bool command_line_arg
);
300 static void sort_files (void);
301 static void parse_ls_color (void);
303 static int getenv_quoting_style (void);
305 static size_t quote_name_width (char const *name
,
306 struct quoting_options
const *options
,
307 int needs_general_quoting
);
309 /* Initial size of hash table.
310 Most hierarchies are likely to be shallower than this. */
311 enum { INITIAL_TABLE_SIZE
= 30 };
313 /* The set of 'active' directories, from the current command-line argument
314 to the level in the hierarchy at which files are being listed.
315 A directory is represented by its device and inode numbers (struct dev_ino).
316 A directory is added to this set when ls begins listing it or its
317 entries, and it is removed from the set just after ls has finished
318 processing it. This set is used solely to detect loops, e.g., with
319 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
320 static Hash_table
*active_dir_set
;
322 #define LOOP_DETECT (!!active_dir_set)
324 /* The table of files in the current directory:
326 'cwd_file' points to a vector of 'struct fileinfo', one per file.
327 'cwd_n_alloc' is the number of elements space has been allocated for.
328 'cwd_n_used' is the number actually in use. */
330 /* Address of block containing the files that are described. */
331 static struct fileinfo
*cwd_file
;
333 /* Length of block that 'cwd_file' points to, measured in files. */
334 static size_t cwd_n_alloc
;
336 /* Index of first unused slot in 'cwd_file'. */
337 static size_t cwd_n_used
;
339 /* Whether files needs may need padding due to quoting. */
340 static bool cwd_some_quoted
;
342 /* Whether quoting style _may_ add outer quotes,
343 and whether aligning those is useful. */
344 static bool align_variable_outer_quotes
;
346 /* Vector of pointers to files, in proper sorted order, and the number
347 of entries allocated for it. */
348 static void **sorted_file
;
349 static size_t sorted_file_alloc
;
351 /* When true, in a color listing, color each symlink name according to the
352 type of file it points to. Otherwise, color them according to the 'ln'
353 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
354 regardless. This is set when 'ln=target' appears in LS_COLORS. */
356 static bool color_symlink_as_referent
;
358 static char const *hostname
;
360 /* Mode of appropriate file for coloring. */
362 file_or_link_mode (struct fileinfo
const *file
)
364 return (color_symlink_as_referent
&& file
->linkok
365 ? file
->linkmode
: file
->stat
.st_mode
);
369 /* Record of one pending directory waiting to be listed. */
374 /* If the directory is actually the file pointed to by a symbolic link we
375 were told to list, 'realname' will contain the name of the symbolic
376 link, otherwise zero. */
378 bool command_line_arg
;
379 struct pending
*next
;
382 static struct pending
*pending_dirs
;
384 /* Current time in seconds and nanoseconds since 1970, updated as
385 needed when deciding whether a file is recent. */
387 static struct timespec current_time
;
389 static bool print_scontext
;
390 static char UNKNOWN_SECURITY_CONTEXT
[] = "?";
392 /* Whether any of the files has an ACL. This affects the width of the
395 static bool any_has_acl
;
397 /* The number of columns to use for columns containing inode numbers,
398 block sizes, link counts, owners, groups, authors, major device
399 numbers, minor device numbers, and file sizes, respectively. */
401 static int inode_number_width
;
402 static int block_size_width
;
403 static int nlink_width
;
404 static int scontext_width
;
405 static int owner_width
;
406 static int group_width
;
407 static int author_width
;
408 static int major_device_number_width
;
409 static int minor_device_number_width
;
410 static int file_size_width
;
414 /* long_format for lots of info, one per line.
415 one_per_line for just names, one per line.
416 many_per_line for just names, many per line, sorted vertically.
417 horizontal for just names, many per line, sorted horizontally.
418 with_commas for just names, many per line, separated by commas.
420 -l (and other options that imply -l), -1, -C, -x and -m control
425 long_format
, /* -l and other options that imply -l */
426 one_per_line
, /* -1 */
427 many_per_line
, /* -C */
432 static enum format format
;
434 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
435 ISO-style timestamps, though shorter than 'full-iso'. 'iso' uses shorter
436 ISO-style timestamps. 'locale' uses locale-dependent timestamps. */
439 full_iso_time_style
, /* --time-style=full-iso */
440 long_iso_time_style
, /* --time-style=long-iso */
441 iso_time_style
, /* --time-style=iso */
442 locale_time_style
/* --time-style=locale */
445 static char const *const time_style_args
[] =
447 "full-iso", "long-iso", "iso", "locale", nullptr
449 static enum time_style
const time_style_types
[] =
451 full_iso_time_style
, long_iso_time_style
, iso_time_style
,
454 ARGMATCH_VERIFY (time_style_args
, time_style_types
);
456 /* Type of time to print or sort by. Controlled by -c and -u.
457 The values of each item of this enum are important since they are
458 used as indices in the sort functions array (see sort_files()). */
462 time_mtime
= 0, /* default */
465 time_btime
, /* birth time */
466 time_numtypes
/* the number of elements of this enum */
469 static enum time_type time_type
;
471 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
472 The values of each item of this enum are important since they are
473 used as indices in the sort functions array (see sort_files()). */
477 sort_name
= 0, /* default */
478 sort_extension
, /* -X */
481 sort_version
, /* -v */
482 sort_time
, /* -t; must be second to last */
483 sort_none
, /* -U; must be last */
484 sort_numtypes
/* the number of elements of this enum */
487 static enum sort_type sort_type
;
489 /* Direction of sort.
490 false means highest first if numeric,
491 lowest first if alphabetic;
492 these are the defaults.
493 true means the opposite order in each case. -r */
495 static bool sort_reverse
;
497 /* True means to display owner information. -g turns this off. */
499 static bool print_owner
= true;
501 /* True means to display author information. */
503 static bool print_author
;
505 /* True means to display group information. -G and -o turn this off. */
507 static bool print_group
= true;
509 /* True means print the user and group id's as numbers rather
512 static bool numeric_ids
;
514 /* True means mention the size in blocks of each file. -s */
516 static bool print_block_size
;
518 /* Human-readable options for output, when printing block counts. */
519 static int human_output_opts
;
521 /* The units to use when printing block counts. */
522 static uintmax_t output_block_size
;
524 /* Likewise, but for file sizes. */
525 static int file_human_output_opts
;
526 static uintmax_t file_output_block_size
= 1;
528 /* Follow the output with a special string. Using this format,
529 Emacs' dired mode starts up twice as fast, and can handle all
530 strange characters in file names. */
533 /* 'none' means don't mention the type of files.
534 'slash' means mention directories only, with a '/'.
535 'file_type' means mention file types.
536 'classify' means mention file types and mark executables.
538 Controlled by -F, -p, and --indicator-style. */
542 none
= 0, /* --indicator-style=none (default) */
543 slash
, /* -p, --indicator-style=slash */
544 file_type
, /* --indicator-style=file-type */
545 classify
/* -F, --indicator-style=classify */
548 static enum indicator_style indicator_style
;
550 /* Names of indicator styles. */
551 static char const *const indicator_style_args
[] =
553 "none", "slash", "file-type", "classify", nullptr
555 static enum indicator_style
const indicator_style_types
[] =
557 none
, slash
, file_type
, classify
559 ARGMATCH_VERIFY (indicator_style_args
, indicator_style_types
);
561 /* True means use colors to mark types. Also define the different
562 colors as well as the stuff for the LS_COLORS environment variable.
563 The LS_COLORS variable is now in a termcap-like format. */
565 static bool print_with_color
;
567 static bool print_hyperlink
;
569 /* Whether we used any colors in the output so far. If so, we will
570 need to restore the default color later. If not, we will need to
571 call prep_non_filename_text before using color for the first time. */
573 static bool used_color
= false;
577 when_never
, /* 0: default or --color=never */
578 when_always
, /* 1: --color=always */
579 when_if_tty
/* 2: --color=tty */
582 enum Dereference_symlink
584 DEREF_UNDEFINED
= 0, /* default */
586 DEREF_COMMAND_LINE_ARGUMENTS
, /* -H */
587 DEREF_COMMAND_LINE_SYMLINK_TO_DIR
, /* the default, in certain cases */
588 DEREF_ALWAYS
/* -L */
593 C_LEFT
, C_RIGHT
, C_END
, C_RESET
, C_NORM
, C_FILE
, C_DIR
, C_LINK
,
595 C_BLK
, C_CHR
, C_MISSING
, C_ORPHAN
, C_EXEC
, C_DOOR
, C_SETUID
, C_SETGID
,
596 C_STICKY
, C_OTHER_WRITABLE
, C_STICKY_OTHER_WRITABLE
, C_CAP
, C_MULTIHARDLINK
,
600 static char const *const indicator_name
[]=
602 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
603 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
604 "ow", "tw", "ca", "mh", "cl", nullptr
607 struct color_ext_type
609 struct bin_str ext
; /* The extension we're looking for */
610 struct bin_str seq
; /* The sequence to output when we do */
611 bool exact_match
; /* Whether to compare case insensitively */
612 struct color_ext_type
*next
; /* Next in list */
615 static struct bin_str color_indicator
[] =
617 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
618 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
619 { 0, nullptr }, /* ec: End color (replaces lc+rs+rc) */
620 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
621 { 0, nullptr }, /* no: Normal */
622 { 0, nullptr }, /* fi: File: default */
623 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
624 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
625 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
626 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
627 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
628 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
629 { 0, nullptr }, /* mi: Missing file: undefined */
630 { 0, nullptr }, /* or: Orphaned symlink: undefined */
631 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
632 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
633 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
634 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
635 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
636 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
637 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
638 { 0, nullptr }, /* ca: disabled by default */
639 { 0, nullptr }, /* mh: disabled by default */
640 { LEN_STR_PAIR ("\033[K") }, /* cl: clear to end of line */
643 /* A list mapping file extensions to corresponding display sequence. */
644 static struct color_ext_type
*color_ext_list
= nullptr;
646 /* Buffer for color sequences */
647 static char *color_buf
;
649 /* True means to check for orphaned symbolic link, for displaying
650 colors, or to group symlink to directories with other dirs. */
652 static bool check_symlink_mode
;
654 /* True means mention the inode number of each file. -i */
656 static bool print_inode
;
658 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
659 other options that imply -l), and -L. */
661 static enum Dereference_symlink dereference
;
663 /* True means when a directory is found, display info on its
666 static bool recursive
;
668 /* True means when an argument is a directory name, display info
671 static bool immediate_dirs
;
673 /* True means that directories are grouped before files. */
675 static bool directories_first
;
677 /* Which files to ignore. */
681 /* Ignore files whose names start with '.', and files specified by
682 --hide and --ignore. */
685 /* Ignore '.', '..', and files specified by --ignore. */
686 IGNORE_DOT_AND_DOTDOT
,
688 /* Ignore only files specified by --ignore. */
692 /* A linked list of shell-style globbing patterns. If a non-argument
693 file name matches any of these patterns, it is ignored.
694 Controlled by -I. Multiple -I options accumulate.
695 The -B option adds '*~' and '.*~' to this list. */
697 struct ignore_pattern
700 struct ignore_pattern
*next
;
703 static struct ignore_pattern
*ignore_patterns
;
705 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
706 variable itself to be ignored. */
707 static struct ignore_pattern
*hide_patterns
;
709 /* True means output nongraphic chars in file names as '?'.
710 (-q, --hide-control-chars)
711 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
712 independent. The algorithm is: first, obey the quoting style to get a
713 string representing the file name; then, if qmark_funny_chars is set,
714 replace all nonprintable chars in that string with '?'. It's necessary
715 to replace nonprintable chars even in quoted strings, because we don't
716 want to mess up the terminal if control chars get sent to it, and some
717 quoting methods pass through control chars as-is. */
718 static bool qmark_funny_chars
;
720 /* Quoting options for file and dir name output. */
722 static struct quoting_options
*filename_quoting_options
;
723 static struct quoting_options
*dirname_quoting_options
;
725 /* The number of chars per hardware tab stop. Setting this to zero
726 inhibits the use of TAB characters for separating columns. -T */
727 static size_t tabsize
;
729 /* True means print each directory name before listing it. */
731 static bool print_dir_name
;
733 /* The line length to use for breaking lines in many-per-line format.
734 Can be set with -w. If zero, there is no limit. */
736 static size_t line_length
;
738 /* The local time zone rules, as per the TZ environment variable. */
740 static timezone_t localtz
;
742 /* If true, the file listing format requires that stat be called on
745 static bool format_needs_stat
;
747 /* Similar to 'format_needs_stat', but set if only the file type is
750 static bool format_needs_type
;
752 /* An arbitrary limit on the number of bytes in a printed timestamp.
753 This is set to a relatively small value to avoid the need to worry
754 about denial-of-service attacks on servers that run "ls" on behalf
755 of remote clients. 1000 bytes should be enough for any practical
758 enum { TIME_STAMP_LEN_MAXIMUM
= MAX (1000, INT_STRLEN_BOUND (time_t)) };
760 /* strftime formats for non-recent and recent files, respectively, in
763 static char const *long_time_format
[2] =
765 /* strftime format for non-recent files (older than 6 months), in
766 -l output. This should contain the year, month and day (at
767 least), in an order that is understood by people in your
768 locale's territory. Please try to keep the number of used
769 screen columns small, because many people work in windows with
770 only 80 columns. But make this as wide as the other string
771 below, for recent files. */
772 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
773 so be wary of using variable width fields from the locale.
774 Note %b is handled specially by ls and aligned correctly.
775 Note also that specifying a width as in %5b is erroneous as strftime
776 will count bytes rather than characters in multibyte locales. */
778 /* strftime format for recent files (younger than 6 months), in -l
779 output. This should contain the month, day and time (at
780 least), in an order that is understood by people in your
781 locale's territory. Please try to keep the number of used
782 screen columns small, because many people work in windows with
783 only 80 columns. But make this as wide as the other string
784 above, for non-recent files. */
785 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
786 so be wary of using variable width fields from the locale.
787 Note %b is handled specially by ls and aligned correctly.
788 Note also that specifying a width as in %5b is erroneous as strftime
789 will count bytes rather than characters in multibyte locales. */
793 /* The set of signals that are caught. */
795 static sigset_t caught_signals
;
797 /* If nonzero, the value of the pending fatal signal. */
799 static sig_atomic_t volatile interrupt_signal
;
801 /* A count of the number of pending stop signals that have been received. */
803 static sig_atomic_t volatile stop_signal_count
;
805 /* Desired exit status. */
807 static int exit_status
;
812 /* "ls" had a minor problem. E.g., while processing a directory,
813 ls obtained the name of an entry via readdir, yet was later
814 unable to stat that name. This happens when listing a directory
815 in which entries are actively being removed or renamed. */
816 LS_MINOR_PROBLEM
= 1,
818 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
819 option or failure to stat a command line argument. */
823 /* For long options that have no equivalent short option, use a
824 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
827 AUTHOR_OPTION
= CHAR_MAX
+ 1,
830 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
,
831 FILE_TYPE_INDICATOR_OPTION
,
834 GROUP_DIRECTORIES_FIRST_OPTION
,
837 INDICATOR_STYLE_OPTION
,
838 QUOTING_STYLE_OPTION
,
839 SHOW_CONTROL_CHARS_OPTION
,
847 static struct option
const long_options
[] =
849 {"all", no_argument
, nullptr, 'a'},
850 {"escape", no_argument
, nullptr, 'b'},
851 {"directory", no_argument
, nullptr, 'd'},
852 {"dired", no_argument
, nullptr, 'D'},
853 {"full-time", no_argument
, nullptr, FULL_TIME_OPTION
},
854 {"group-directories-first", no_argument
, nullptr,
855 GROUP_DIRECTORIES_FIRST_OPTION
},
856 {"human-readable", no_argument
, nullptr, 'h'},
857 {"inode", no_argument
, nullptr, 'i'},
858 {"kibibytes", no_argument
, nullptr, 'k'},
859 {"numeric-uid-gid", no_argument
, nullptr, 'n'},
860 {"no-group", no_argument
, nullptr, 'G'},
861 {"hide-control-chars", no_argument
, nullptr, 'q'},
862 {"reverse", no_argument
, nullptr, 'r'},
863 {"size", no_argument
, nullptr, 's'},
864 {"width", required_argument
, nullptr, 'w'},
865 {"almost-all", no_argument
, nullptr, 'A'},
866 {"ignore-backups", no_argument
, nullptr, 'B'},
867 {"classify", optional_argument
, nullptr, 'F'},
868 {"file-type", no_argument
, nullptr, FILE_TYPE_INDICATOR_OPTION
},
869 {"si", no_argument
, nullptr, SI_OPTION
},
870 {"dereference-command-line", no_argument
, nullptr, 'H'},
871 {"dereference-command-line-symlink-to-dir", no_argument
, nullptr,
872 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
},
873 {"hide", required_argument
, nullptr, HIDE_OPTION
},
874 {"ignore", required_argument
, nullptr, 'I'},
875 {"indicator-style", required_argument
, nullptr, INDICATOR_STYLE_OPTION
},
876 {"dereference", no_argument
, nullptr, 'L'},
877 {"literal", no_argument
, nullptr, 'N'},
878 {"quote-name", no_argument
, nullptr, 'Q'},
879 {"quoting-style", required_argument
, nullptr, QUOTING_STYLE_OPTION
},
880 {"recursive", no_argument
, nullptr, 'R'},
881 {"format", required_argument
, nullptr, FORMAT_OPTION
},
882 {"show-control-chars", no_argument
, nullptr, SHOW_CONTROL_CHARS_OPTION
},
883 {"sort", required_argument
, nullptr, SORT_OPTION
},
884 {"tabsize", required_argument
, nullptr, 'T'},
885 {"time", required_argument
, nullptr, TIME_OPTION
},
886 {"time-style", required_argument
, nullptr, TIME_STYLE_OPTION
},
887 {"zero", no_argument
, nullptr, ZERO_OPTION
},
888 {"color", optional_argument
, nullptr, COLOR_OPTION
},
889 {"hyperlink", optional_argument
, nullptr, HYPERLINK_OPTION
},
890 {"block-size", required_argument
, nullptr, BLOCK_SIZE_OPTION
},
891 {"context", no_argument
, 0, 'Z'},
892 {"author", no_argument
, nullptr, AUTHOR_OPTION
},
893 {GETOPT_HELP_OPTION_DECL
},
894 {GETOPT_VERSION_OPTION_DECL
},
895 {nullptr, 0, nullptr, 0}
898 static char const *const format_args
[] =
900 "verbose", "long", "commas", "horizontal", "across",
901 "vertical", "single-column", nullptr
903 static enum format
const format_types
[] =
905 long_format
, long_format
, with_commas
, horizontal
, horizontal
,
906 many_per_line
, one_per_line
908 ARGMATCH_VERIFY (format_args
, format_types
);
910 static char const *const sort_args
[] =
912 "none", "time", "size", "extension", "version", "width", nullptr
914 static enum sort_type
const sort_types
[] =
916 sort_none
, sort_time
, sort_size
, sort_extension
, sort_version
, sort_width
918 ARGMATCH_VERIFY (sort_args
, sort_types
);
920 static char const *const time_args
[] =
922 "atime", "access", "use",
924 "mtime", "modification",
928 static enum time_type
const time_types
[] =
930 time_atime
, time_atime
, time_atime
,
931 time_ctime
, time_ctime
,
932 time_mtime
, time_mtime
,
933 time_btime
, time_btime
,
935 ARGMATCH_VERIFY (time_args
, time_types
);
937 static char const *const when_args
[] =
939 /* force and none are for compatibility with another color-ls version */
940 "always", "yes", "force",
941 "never", "no", "none",
942 "auto", "tty", "if-tty", nullptr
944 static enum when_type
const when_types
[] =
946 when_always
, when_always
, when_always
,
947 when_never
, when_never
, when_never
,
948 when_if_tty
, when_if_tty
, when_if_tty
950 ARGMATCH_VERIFY (when_args
, when_types
);
952 /* Information about filling a column. */
960 /* Array with information about column fullness. */
961 static struct column_info
*column_info
;
963 /* Maximum number of columns ever possible for this display. */
964 static size_t max_idx
;
966 /* The minimum width of a column is 3: 1 character for the name and 2
967 for the separating white space. */
968 enum { MIN_COLUMN_WIDTH
= 3 };
971 /* This zero-based index is for the --dired option. It is incremented
972 for each byte of output generated by this program so that the beginning
973 and ending indices (in that output) of every file name can be recorded
974 and later output themselves. */
975 static off_t dired_pos
;
978 dired_outbyte (char c
)
984 /* Output the buffer S, of length S_LEN, and increment DIRED_POS by S_LEN. */
986 dired_outbuf (char const *s
, size_t s_len
)
989 fwrite (s
, sizeof *s
, s_len
, stdout
);
992 /* Output the string S, and increment DIRED_POS by its length. */
994 dired_outstring (char const *s
)
996 dired_outbuf (s
, strlen (s
));
1003 dired_outstring (" ");
1006 /* With --dired, store pairs of beginning and ending indices of file names. */
1007 static struct obstack dired_obstack
;
1009 /* With --dired, store pairs of beginning and ending indices of any
1010 directory names that appear as headers (just before 'total' line)
1011 for lists of directory entries. Such directory names are seen when
1012 listing hierarchies using -R and when a directory is listed with at
1013 least one other command line argument. */
1014 static struct obstack subdired_obstack
;
1016 /* Save the current index on the specified obstack, OBS. */
1018 push_current_dired_pos (struct obstack
*obs
)
1021 obstack_grow (obs
, &dired_pos
, sizeof dired_pos
);
1024 /* With -R, this stack is used to help detect directory cycles.
1025 The device/inode pairs on this stack mirror the pairs in the
1026 active_dir_set hash table. */
1027 static struct obstack dev_ino_obstack
;
1029 /* Push a pair onto the device/inode stack. */
1031 dev_ino_push (dev_t dev
, ino_t ino
)
1035 int dev_ino_size
= sizeof *di
;
1036 obstack_blank (&dev_ino_obstack
, dev_ino_size
);
1037 vdi
= obstack_next_free (&dev_ino_obstack
);
1044 /* Pop a dev/ino struct off the global dev_ino_obstack
1045 and return that struct. */
1046 static struct dev_ino
1051 int dev_ino_size
= sizeof *di
;
1052 affirm (dev_ino_size
<= obstack_object_size (&dev_ino_obstack
));
1053 obstack_blank_fast (&dev_ino_obstack
, -dev_ino_size
);
1054 vdi
= obstack_next_free (&dev_ino_obstack
);
1060 assert_matching_dev_ino (char const *name
, struct dev_ino di
)
1062 MAYBE_UNUSED
struct stat sb
;
1063 assure (0 <= stat (name
, &sb
));
1064 assure (sb
.st_dev
== di
.st_dev
);
1065 assure (sb
.st_ino
== di
.st_ino
);
1068 static char eolbyte
= '\n';
1070 /* Write to standard output PREFIX, followed by the quoting style and
1071 a space-separated list of the integers stored in OS all on one line. */
1074 dired_dump_obstack (char const *prefix
, struct obstack
*os
)
1078 n_pos
= obstack_object_size (os
) / sizeof (dired_pos
);
1081 off_t
*pos
= obstack_finish (os
);
1082 fputs (prefix
, stdout
);
1083 for (size_t i
= 0; i
< n_pos
; i
++)
1085 intmax_t p
= pos
[i
];
1086 printf (" %"PRIdMAX
, p
);
1092 /* Return the platform birthtime member of the stat structure,
1093 or fallback to the mtime member, which we have populated
1094 from the statx structure or reset to an invalid timestamp
1095 where birth time is not supported. */
1096 static struct timespec
1097 get_stat_btime (struct stat
const *st
)
1099 struct timespec btimespec
;
1101 #if HAVE_STATX && defined STATX_INO
1102 btimespec
= get_stat_mtime (st
);
1104 btimespec
= get_stat_birthtime (st
);
1110 #if HAVE_STATX && defined STATX_INO
1113 time_type_to_statx (void)
1133 calc_req_mask (void)
1135 unsigned int mask
= STATX_MODE
;
1140 if (print_block_size
)
1141 mask
|= STATX_BLOCKS
;
1143 if (format
== long_format
) {
1144 mask
|= STATX_NLINK
| STATX_SIZE
| time_type_to_statx ();
1145 if (print_owner
|| print_author
)
1156 case sort_extension
:
1160 mask
|= time_type_to_statx ();
1173 do_statx (int fd
, char const *name
, struct stat
*st
, int flags
,
1177 bool want_btime
= mask
& STATX_BTIME
;
1178 int ret
= statx (fd
, name
, flags
| AT_NO_AUTOMOUNT
, mask
, &stx
);
1181 statx_to_stat (&stx
, st
);
1182 /* Since we only need one timestamp type,
1183 store birth time in st_mtim. */
1186 if (stx
.stx_mask
& STATX_BTIME
)
1187 st
->st_mtim
= statx_timestamp_to_timespec (stx
.stx_btime
);
1189 st
->st_mtim
.tv_sec
= st
->st_mtim
.tv_nsec
= -1;
1197 do_stat (char const *name
, struct stat
*st
)
1199 return do_statx (AT_FDCWD
, name
, st
, 0, calc_req_mask ());
1203 do_lstat (char const *name
, struct stat
*st
)
1205 return do_statx (AT_FDCWD
, name
, st
, AT_SYMLINK_NOFOLLOW
, calc_req_mask ());
1209 stat_for_mode (char const *name
, struct stat
*st
)
1211 return do_statx (AT_FDCWD
, name
, st
, 0, STATX_MODE
);
1214 /* dev+ino should be static, so no need to sync with backing store */
1216 stat_for_ino (char const *name
, struct stat
*st
)
1218 return do_statx (AT_FDCWD
, name
, st
, 0, STATX_INO
);
1222 fstat_for_ino (int fd
, struct stat
*st
)
1224 return do_statx (fd
, "", st
, AT_EMPTY_PATH
, STATX_INO
);
1228 do_stat (char const *name
, struct stat
*st
)
1230 return stat (name
, st
);
1234 do_lstat (char const *name
, struct stat
*st
)
1236 return lstat (name
, st
);
1240 stat_for_mode (char const *name
, struct stat
*st
)
1242 return stat (name
, st
);
1246 stat_for_ino (char const *name
, struct stat
*st
)
1248 return stat (name
, st
);
1252 fstat_for_ino (int fd
, struct stat
*st
)
1254 return fstat (fd
, st
);
1258 /* Return the address of the first plain %b spec in FMT, or nullptr if
1259 there is no such spec. %5b etc. do not match, so that user
1260 widths/flags are honored. */
1264 first_percent_b (char const *fmt
)
1270 case 'b': return fmt
;
1271 case '%': fmt
++; break;
1276 static char RFC3986
[256];
1278 file_escape_init (void)
1280 for (int i
= 0; i
< 256; i
++)
1281 RFC3986
[i
] |= c_isalnum (i
) || i
== '~' || i
== '-' || i
== '.' || i
== '_';
1284 enum { MBSWIDTH_FLAGS
= MBSW_REJECT_INVALID
| MBSW_REJECT_UNPRINTABLE
};
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 /* abformat[RECENT][MON] is the format to use for timestamps with
1295 recentness RECENT and month MON. */
1296 enum { ABFORMAT_SIZE
= 128 };
1297 static char abformat
[2][12][ABFORMAT_SIZE
];
1298 /* True if precomputed formats should be used. This can be false if
1299 nl_langinfo fails, if a format or month abbreviation is unusually
1300 long, or if a month abbreviation contains '%'. */
1301 static bool use_abformat
;
1303 /* Store into ABMON the abbreviated month names, suitably aligned.
1304 Return true if successful. */
1307 abmon_init (char abmon
[12][ABFORMAT_SIZE
])
1309 #ifndef HAVE_NL_LANGINFO
1312 int max_mon_width
= 0;
1316 for (int i
= 0; i
< 12; i
++)
1318 char const *abbr
= nl_langinfo (ABMON_1
+ i
);
1319 mon_len
[i
] = strnlen (abbr
, ABFORMAT_SIZE
);
1320 if (mon_len
[i
] == ABFORMAT_SIZE
)
1322 if (strchr (abbr
, '%'))
1324 mon_width
[i
] = mbswidth (strcpy (abmon
[i
], abbr
), MBSWIDTH_FLAGS
);
1325 if (mon_width
[i
] < 0)
1327 max_mon_width
= MAX (max_mon_width
, mon_width
[i
]);
1330 for (int i
= 0; i
< 12; i
++)
1332 int fill
= max_mon_width
- mon_width
[i
];
1333 if (ABFORMAT_SIZE
- mon_len
[i
] <= fill
)
1335 bool align_left
= !isdigit (to_uchar (abmon
[i
][0]));
1338 fill_offset
= mon_len
[i
];
1341 memmove (abmon
[i
] + fill
, abmon
[i
], mon_len
[i
]);
1344 memset (abmon
[i
] + fill_offset
, ' ', fill
);
1345 abmon
[i
][mon_len
[i
] + fill
] = '\0';
1352 /* Initialize ABFORMAT and USE_ABFORMAT. */
1355 abformat_init (void)
1358 for (int recent
= 0; recent
< 2; recent
++)
1359 pb
[recent
] = first_percent_b (long_time_format
[recent
]);
1360 if (! (pb
[0] || pb
[1]))
1363 char abmon
[12][ABFORMAT_SIZE
];
1364 if (! abmon_init (abmon
))
1367 for (int recent
= 0; recent
< 2; recent
++)
1369 char const *fmt
= long_time_format
[recent
];
1370 for (int i
= 0; i
< 12; i
++)
1372 char *nfmt
= abformat
[recent
][i
];
1376 nbytes
= snprintf (nfmt
, ABFORMAT_SIZE
, "%s", fmt
);
1379 if (! (pb
[recent
] - fmt
<= MIN (ABFORMAT_SIZE
, INT_MAX
)))
1381 int prefix_len
= pb
[recent
] - fmt
;
1382 nbytes
= snprintf (nfmt
, ABFORMAT_SIZE
, "%.*s%s%s",
1383 prefix_len
, fmt
, abmon
[i
], pb
[recent
] + 2);
1386 if (! (0 <= nbytes
&& nbytes
< ABFORMAT_SIZE
))
1391 use_abformat
= true;
1395 dev_ino_hash (void const *x
, size_t table_size
)
1397 struct dev_ino
const *p
= x
;
1398 return (uintmax_t) p
->st_ino
% table_size
;
1402 dev_ino_compare (void const *x
, void const *y
)
1404 struct dev_ino
const *a
= x
;
1405 struct dev_ino
const *b
= y
;
1406 return SAME_INODE (*a
, *b
) ? true : false;
1410 dev_ino_free (void *x
)
1415 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1416 active directories. Return true if there is already a matching
1417 entry in the table. */
1420 visit_dir (dev_t dev
, ino_t ino
)
1422 struct dev_ino
*ent
;
1423 struct dev_ino
*ent_from_table
;
1426 ent
= xmalloc (sizeof *ent
);
1430 /* Attempt to insert this entry into the table. */
1431 ent_from_table
= hash_insert (active_dir_set
, ent
);
1433 if (ent_from_table
== nullptr)
1435 /* Insertion failed due to lack of memory. */
1439 found_match
= (ent_from_table
!= ent
);
1443 /* ent was not inserted, so free it. */
1451 free_pending_ent (struct pending
*p
)
1459 is_colored (enum indicator_no type
)
1461 size_t len
= color_indicator
[type
].len
;
1462 char const *s
= color_indicator
[type
].string
;
1464 || (len
== 1 && STRNCMP_LIT (s
, "0") == 0)
1465 || (len
== 2 && STRNCMP_LIT (s
, "00") == 0));
1469 restore_default_color (void)
1471 put_indicator (&color_indicator
[C_LEFT
]);
1472 put_indicator (&color_indicator
[C_RIGHT
]);
1476 set_normal_color (void)
1478 if (print_with_color
&& is_colored (C_NORM
))
1480 put_indicator (&color_indicator
[C_LEFT
]);
1481 put_indicator (&color_indicator
[C_NORM
]);
1482 put_indicator (&color_indicator
[C_RIGHT
]);
1486 /* An ordinary signal was received; arrange for the program to exit. */
1489 sighandler (int sig
)
1492 signal (sig
, SIG_IGN
);
1493 if (! interrupt_signal
)
1494 interrupt_signal
= sig
;
1497 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1500 stophandler (int sig
)
1503 signal (sig
, stophandler
);
1504 if (! interrupt_signal
)
1505 stop_signal_count
++;
1508 /* Process any pending signals. If signals are caught, this function
1509 should be called periodically. Ideally there should never be an
1510 unbounded amount of time when signals are not being processed.
1511 Signal handling can restore the default colors, so callers must
1512 immediately change colors after invoking this function. */
1515 process_signals (void)
1517 while (interrupt_signal
|| stop_signal_count
)
1524 restore_default_color ();
1527 sigprocmask (SIG_BLOCK
, &caught_signals
, &oldset
);
1529 /* Reload interrupt_signal and stop_signal_count, in case a new
1530 signal was handled before sigprocmask took effect. */
1531 sig
= interrupt_signal
;
1532 stops
= stop_signal_count
;
1534 /* SIGTSTP is special, since the application can receive that signal
1535 more than once. In this case, don't set the signal handler to the
1536 default. Instead, just raise the uncatchable SIGSTOP. */
1539 stop_signal_count
= stops
- 1;
1543 signal (sig
, SIG_DFL
);
1545 /* Exit or suspend the program. */
1547 sigprocmask (SIG_SETMASK
, &oldset
, nullptr);
1549 /* If execution reaches here, then the program has been
1550 continued (after being suspended). */
1554 /* Setup signal handlers if INIT is true,
1555 otherwise restore to the default. */
1558 signal_setup (bool init
)
1560 /* The signals that are trapped, and the number of such signals. */
1561 static int const sig
[] =
1563 /* This one is handled specially. */
1566 /* The usual suspects. */
1567 SIGALRM
, SIGHUP
, SIGINT
, SIGPIPE
, SIGQUIT
, SIGTERM
,
1584 enum { nsigs
= ARRAY_CARDINALITY (sig
) };
1587 static bool caught_sig
[nsigs
];
1595 struct sigaction act
;
1597 sigemptyset (&caught_signals
);
1598 for (j
= 0; j
< nsigs
; j
++)
1600 sigaction (sig
[j
], nullptr, &act
);
1601 if (act
.sa_handler
!= SIG_IGN
)
1602 sigaddset (&caught_signals
, sig
[j
]);
1605 act
.sa_mask
= caught_signals
;
1606 act
.sa_flags
= SA_RESTART
;
1608 for (j
= 0; j
< nsigs
; j
++)
1609 if (sigismember (&caught_signals
, sig
[j
]))
1611 act
.sa_handler
= sig
[j
] == SIGTSTP
? stophandler
: sighandler
;
1612 sigaction (sig
[j
], &act
, nullptr);
1615 for (j
= 0; j
< nsigs
; j
++)
1617 caught_sig
[j
] = (signal (sig
[j
], SIG_IGN
) != SIG_IGN
);
1620 signal (sig
[j
], sig
[j
] == SIGTSTP
? stophandler
: sighandler
);
1621 siginterrupt (sig
[j
], 0);
1629 for (j
= 0; j
< nsigs
; j
++)
1630 if (sigismember (&caught_signals
, sig
[j
]))
1631 signal (sig
[j
], SIG_DFL
);
1633 for (j
= 0; j
< nsigs
; j
++)
1635 signal (sig
[j
], SIG_DFL
);
1643 signal_setup (true);
1647 signal_restore (void)
1649 signal_setup (false);
1653 main (int argc
, char **argv
)
1656 struct pending
*thispend
;
1659 initialize_main (&argc
, &argv
);
1660 set_program_name (argv
[0]);
1661 setlocale (LC_ALL
, "");
1662 bindtextdomain (PACKAGE
, LOCALEDIR
);
1663 textdomain (PACKAGE
);
1665 initialize_exit_failure (LS_FAILURE
);
1666 atexit (close_stdout
);
1668 static_assert (ARRAY_CARDINALITY (color_indicator
) + 1
1669 == ARRAY_CARDINALITY (indicator_name
));
1671 exit_status
= EXIT_SUCCESS
;
1672 print_dir_name
= true;
1673 pending_dirs
= nullptr;
1675 current_time
.tv_sec
= TYPE_MINIMUM (time_t);
1676 current_time
.tv_nsec
= -1;
1678 i
= decode_switches (argc
, argv
);
1680 if (print_with_color
)
1683 /* Test print_with_color again, because the call to parse_ls_color
1684 may have just reset it -- e.g., if LS_COLORS is invalid. */
1686 if (print_with_color
)
1688 /* Don't use TAB characters in output. Some terminal
1689 emulators can't handle the combination of tabs and
1690 color codes on the same line. */
1694 if (directories_first
)
1695 check_symlink_mode
= true;
1696 else if (print_with_color
)
1698 /* Avoid following symbolic links when possible. */
1699 if (is_colored (C_ORPHAN
)
1700 || (is_colored (C_EXEC
) && color_symlink_as_referent
)
1701 || (is_colored (C_MISSING
) && format
== long_format
))
1702 check_symlink_mode
= true;
1705 if (dereference
== DEREF_UNDEFINED
)
1706 dereference
= ((immediate_dirs
1707 || indicator_style
== classify
1708 || format
== long_format
)
1710 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR
);
1712 /* When using -R, initialize a data structure we'll use to
1713 detect any directory cycles. */
1716 active_dir_set
= hash_initialize (INITIAL_TABLE_SIZE
, nullptr,
1720 if (active_dir_set
== nullptr)
1723 obstack_init (&dev_ino_obstack
);
1726 localtz
= tzalloc (getenv ("TZ"));
1728 format_needs_stat
= sort_type
== sort_time
|| sort_type
== sort_size
1729 || format
== long_format
1731 || print_block_size
;
1732 format_needs_type
= (! format_needs_stat
1735 || indicator_style
!= none
1736 || directories_first
));
1740 obstack_init (&dired_obstack
);
1741 obstack_init (&subdired_obstack
);
1744 if (print_hyperlink
)
1746 file_escape_init ();
1748 hostname
= xgethostname ();
1749 /* The hostname is generally ignored,
1750 so ignore failures obtaining it. */
1756 cwd_file
= xnmalloc (cwd_n_alloc
, sizeof *cwd_file
);
1766 gobble_file (".", directory
, NOT_AN_INODE_NUMBER
, true, "");
1768 queue_directory (".", nullptr, true);
1772 gobble_file (argv
[i
++], unknown
, NOT_AN_INODE_NUMBER
, true, "");
1778 if (!immediate_dirs
)
1779 extract_dirs_from_files (nullptr, true);
1780 /* 'cwd_n_used' might be zero now. */
1783 /* In the following if/else blocks, it is sufficient to test 'pending_dirs'
1784 (and not pending_dirs->name) because there may be no markers in the queue
1785 at this point. A marker may be enqueued when extract_dirs_from_files is
1786 called with a non-empty string or via print_dir. */
1789 print_current_files ();
1791 dired_outbyte ('\n');
1793 else if (n_files
<= 1 && pending_dirs
&& pending_dirs
->next
== 0)
1794 print_dir_name
= false;
1796 while (pending_dirs
)
1798 thispend
= pending_dirs
;
1799 pending_dirs
= pending_dirs
->next
;
1803 if (thispend
->name
== nullptr)
1805 /* thispend->name == nullptr means this is a marker entry
1806 indicating we've finished processing the directory.
1807 Use its dev/ino numbers to remove the corresponding
1808 entry from the active_dir_set hash table. */
1809 struct dev_ino di
= dev_ino_pop ();
1810 struct dev_ino
*found
= hash_remove (active_dir_set
, &di
);
1812 assert_matching_dev_ino (thispend
->realname
, di
);
1814 dev_ino_free (found
);
1815 free_pending_ent (thispend
);
1820 print_dir (thispend
->name
, thispend
->realname
,
1821 thispend
->command_line_arg
);
1823 free_pending_ent (thispend
);
1824 print_dir_name
= true;
1827 if (print_with_color
&& used_color
)
1831 /* Skip the restore when it would be a no-op, i.e.,
1832 when left is "\033[" and right is "m". */
1833 if (!(color_indicator
[C_LEFT
].len
== 2
1834 && memcmp (color_indicator
[C_LEFT
].string
, "\033[", 2) == 0
1835 && color_indicator
[C_RIGHT
].len
== 1
1836 && color_indicator
[C_RIGHT
].string
[0] == 'm'))
1837 restore_default_color ();
1843 /* Act on any signals that arrived before the default was restored.
1844 This can process signals out of order, but there doesn't seem to
1845 be an easy way to do them in order, and the order isn't that
1846 important anyway. */
1847 for (j
= stop_signal_count
; j
; j
--)
1849 j
= interrupt_signal
;
1856 /* No need to free these since we're about to exit. */
1857 dired_dump_obstack ("//DIRED//", &dired_obstack
);
1858 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack
);
1859 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1860 quoting_style_args
[get_quoting_style (filename_quoting_options
)]);
1865 assure (hash_get_n_entries (active_dir_set
) == 0);
1866 hash_free (active_dir_set
);
1872 /* Return the line length indicated by the value given by SPEC, or -1
1873 if unsuccessful. 0 means no limit on line length. */
1876 decode_line_length (char const *spec
)
1880 /* Treat too-large values as if they were 0, which is
1881 effectively infinity. */
1882 switch (xstrtoumax (spec
, nullptr, 0, &val
, ""))
1885 return val
<= MIN (PTRDIFF_MAX
, SIZE_MAX
) ? val
: 0;
1887 case LONGINT_OVERFLOW
:
1895 /* Return true if standard output is a tty, caching the result. */
1898 stdout_isatty (void)
1900 static signed char out_tty
= -1;
1902 out_tty
= isatty (STDOUT_FILENO
);
1903 assume (out_tty
== 0 || out_tty
== 1);
1907 /* Set all the option flags according to the switches specified.
1908 Return the index of the first non-option argument. */
1911 decode_switches (int argc
, char **argv
)
1913 char *time_style_option
= nullptr;
1915 /* These variables are false or -1 unless a switch says otherwise. */
1916 bool kibibytes_specified
= false;
1917 int format_opt
= -1;
1918 int hide_control_chars_opt
= -1;
1919 int quoting_style_opt
= -1;
1921 ptrdiff_t tabsize_opt
= -1;
1922 ptrdiff_t width_opt
= -1;
1927 int c
= getopt_long (argc
, argv
,
1928 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1936 ignore_mode
= IGNORE_MINIMAL
;
1940 quoting_style_opt
= escape_quoting_style
;
1944 time_type
= time_ctime
;
1948 immediate_dirs
= true;
1952 /* Same as -a -U -1 --color=none --hyperlink=none,
1953 while disabling -s. */
1954 ignore_mode
= IGNORE_MINIMAL
;
1955 sort_opt
= sort_none
;
1956 if (format_opt
== long_format
)
1958 print_with_color
= false;
1959 print_hyperlink
= false;
1960 print_block_size
= false;
1963 case FILE_TYPE_INDICATOR_OPTION
: /* --file-type */
1964 indicator_style
= file_type
;
1968 format_opt
= long_format
;
1969 print_owner
= false;
1973 file_human_output_opts
= human_output_opts
=
1974 human_autoscale
| human_SI
| human_base_1024
;
1975 file_output_block_size
= output_block_size
= 1;
1983 kibibytes_specified
= true;
1987 format_opt
= long_format
;
1991 format_opt
= with_commas
;
1996 format_opt
= long_format
;
1999 case 'o': /* Just like -l, but don't display group info. */
2000 format_opt
= long_format
;
2001 print_group
= false;
2005 indicator_style
= slash
;
2009 hide_control_chars_opt
= true;
2013 sort_reverse
= true;
2017 print_block_size
= true;
2021 sort_opt
= sort_time
;
2025 time_type
= time_atime
;
2029 sort_opt
= sort_version
;
2033 width_opt
= decode_line_length (optarg
);
2035 error (LS_FAILURE
, 0, "%s: %s", _("invalid line width"),
2040 format_opt
= horizontal
;
2044 ignore_mode
= IGNORE_DOT_AND_DOTDOT
;
2048 add_ignore_pattern ("*~");
2049 add_ignore_pattern (".*~");
2053 format_opt
= many_per_line
;
2064 i
= XARGMATCH ("--classify", optarg
, when_args
, when_types
);
2066 /* Using --classify with no argument is equivalent to using
2067 --classify=always. */
2070 if (i
== when_always
|| (i
== when_if_tty
&& stdout_isatty ()))
2071 indicator_style
= classify
;
2075 case 'G': /* inhibit display of group info */
2076 print_group
= false;
2080 dereference
= DEREF_COMMAND_LINE_ARGUMENTS
;
2083 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
:
2084 dereference
= DEREF_COMMAND_LINE_SYMLINK_TO_DIR
;
2088 add_ignore_pattern (optarg
);
2092 dereference
= DEREF_ALWAYS
;
2096 quoting_style_opt
= literal_quoting_style
;
2100 quoting_style_opt
= c_quoting_style
;
2108 sort_opt
= sort_size
;
2112 tabsize_opt
= xnumtoumax (optarg
, 0, 0, MIN (PTRDIFF_MAX
, SIZE_MAX
),
2113 "", _("invalid tab size"), LS_FAILURE
);
2117 sort_opt
= sort_none
;
2121 sort_opt
= sort_extension
;
2125 /* -1 has no effect after -l. */
2126 if (format_opt
!= long_format
)
2127 format_opt
= one_per_line
;
2131 print_author
= true;
2136 struct ignore_pattern
*hide
= xmalloc (sizeof *hide
);
2137 hide
->pattern
= optarg
;
2138 hide
->next
= hide_patterns
;
2139 hide_patterns
= hide
;
2144 sort_opt
= XARGMATCH ("--sort", optarg
, sort_args
, sort_types
);
2147 case GROUP_DIRECTORIES_FIRST_OPTION
:
2148 directories_first
= true;
2152 time_type
= XARGMATCH ("--time", optarg
, time_args
, time_types
);
2156 format_opt
= XARGMATCH ("--format", optarg
, format_args
,
2160 case FULL_TIME_OPTION
:
2161 format_opt
= long_format
;
2162 time_style_option
= bad_cast ("full-iso");
2169 i
= XARGMATCH ("--color", optarg
, when_args
, when_types
);
2171 /* Using --color with no argument is equivalent to using
2175 print_with_color
= (i
== when_always
2176 || (i
== when_if_tty
&& stdout_isatty ()));
2180 case HYPERLINK_OPTION
:
2184 i
= XARGMATCH ("--hyperlink", optarg
, when_args
, when_types
);
2186 /* Using --hyperlink with no argument is equivalent to using
2187 --hyperlink=always. */
2190 print_hyperlink
= (i
== when_always
2191 || (i
== when_if_tty
&& stdout_isatty ()));
2195 case INDICATOR_STYLE_OPTION
:
2196 indicator_style
= XARGMATCH ("--indicator-style", optarg
,
2197 indicator_style_args
,
2198 indicator_style_types
);
2201 case QUOTING_STYLE_OPTION
:
2202 quoting_style_opt
= XARGMATCH ("--quoting-style", optarg
,
2204 quoting_style_vals
);
2207 case TIME_STYLE_OPTION
:
2208 time_style_option
= optarg
;
2211 case SHOW_CONTROL_CHARS_OPTION
:
2212 hide_control_chars_opt
= false;
2215 case BLOCK_SIZE_OPTION
:
2217 enum strtol_error e
= human_options (optarg
, &human_output_opts
,
2218 &output_block_size
);
2219 if (e
!= LONGINT_OK
)
2220 xstrtol_fatal (e
, oi
, 0, long_options
, optarg
);
2221 file_human_output_opts
= human_output_opts
;
2222 file_output_block_size
= output_block_size
;
2227 file_human_output_opts
= human_output_opts
=
2228 human_autoscale
| human_SI
;
2229 file_output_block_size
= output_block_size
= 1;
2233 print_scontext
= true;
2238 hide_control_chars_opt
= false;
2239 if (format_opt
!= long_format
)
2240 format_opt
= one_per_line
;
2241 print_with_color
= false;
2242 quoting_style_opt
= literal_quoting_style
;
2245 case_GETOPT_HELP_CHAR
;
2247 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
2254 if (! output_block_size
)
2256 char const *ls_block_size
= getenv ("LS_BLOCK_SIZE");
2257 human_options (ls_block_size
,
2258 &human_output_opts
, &output_block_size
);
2259 if (ls_block_size
|| getenv ("BLOCK_SIZE"))
2261 file_human_output_opts
= human_output_opts
;
2262 file_output_block_size
= output_block_size
;
2264 if (kibibytes_specified
)
2266 human_output_opts
= 0;
2267 output_block_size
= 1024;
2271 format
= (0 <= format_opt
? format_opt
2272 : ls_mode
== LS_LS
? (stdout_isatty ()
2273 ? many_per_line
: one_per_line
)
2274 : ls_mode
== LS_MULTI_COL
? many_per_line
2275 : /* ls_mode == LS_LONG_FORMAT */ long_format
);
2277 /* If the line length was not set by a switch but is needed to determine
2278 output, go to the work of obtaining it from the environment. */
2279 ptrdiff_t linelen
= width_opt
;
2280 if (format
== many_per_line
|| format
== horizontal
|| format
== with_commas
2281 || print_with_color
)
2286 /* Suppress bogus warning re comparing ws.ws_col to big integer. */
2287 # if 4 < __GNUC__ + (6 <= __GNUC_MINOR__)
2288 # pragma GCC diagnostic push
2289 # pragma GCC diagnostic ignored "-Wtype-limits"
2292 if (stdout_isatty ()
2293 && 0 <= ioctl (STDOUT_FILENO
, TIOCGWINSZ
, &ws
)
2295 linelen
= ws
.ws_col
<= MIN (PTRDIFF_MAX
, SIZE_MAX
) ? ws
.ws_col
: 0;
2296 # if 4 < __GNUC__ + (6 <= __GNUC_MINOR__)
2297 # pragma GCC diagnostic pop
2303 char const *p
= getenv ("COLUMNS");
2306 linelen
= decode_line_length (p
);
2309 _("ignoring invalid width"
2310 " in environment variable COLUMNS: %s"),
2316 line_length
= linelen
< 0 ? 80 : linelen
;
2318 /* Determine the max possible number of display columns. */
2319 max_idx
= line_length
/ MIN_COLUMN_WIDTH
;
2320 /* Account for first display column not having a separator,
2321 or line_lengths shorter than MIN_COLUMN_WIDTH. */
2322 max_idx
+= line_length
% MIN_COLUMN_WIDTH
!= 0;
2324 if (format
== many_per_line
|| format
== horizontal
|| format
== with_commas
)
2326 if (0 <= tabsize_opt
)
2327 tabsize
= tabsize_opt
;
2331 char const *p
= getenv ("TABSIZE");
2335 if (xstrtoumax (p
, nullptr, 0, &tmp
, "") == LONGINT_OK
2340 _("ignoring invalid tab size"
2341 " in environment variable TABSIZE: %s"),
2347 qmark_funny_chars
= (hide_control_chars_opt
< 0
2348 ? ls_mode
== LS_LS
&& stdout_isatty ()
2349 : hide_control_chars_opt
);
2351 int qs
= quoting_style_opt
;
2353 qs
= getenv_quoting_style ();
2355 qs
= (ls_mode
== LS_LS
2356 ? (stdout_isatty () ? shell_escape_quoting_style
: -1)
2357 : escape_quoting_style
);
2359 set_quoting_style (nullptr, qs
);
2360 qs
= get_quoting_style (nullptr);
2361 align_variable_outer_quotes
2362 = ((format
== long_format
2363 || ((format
== many_per_line
|| format
== horizontal
) && line_length
))
2364 && (qs
== shell_quoting_style
2365 || qs
== shell_escape_quoting_style
2366 || qs
== c_maybe_quoting_style
));
2367 filename_quoting_options
= clone_quoting_options (nullptr);
2368 if (qs
== escape_quoting_style
)
2369 set_char_quoting (filename_quoting_options
, ' ', 1);
2370 if (file_type
<= indicator_style
)
2373 for (p
= &"*=>@|"[indicator_style
- file_type
]; *p
; p
++)
2374 set_char_quoting (filename_quoting_options
, *p
, 1);
2377 dirname_quoting_options
= clone_quoting_options (nullptr);
2378 set_char_quoting (dirname_quoting_options
, ':', 1);
2380 /* --dired is meaningful only with --format=long (-l) and sans --hyperlink.
2381 Otherwise, ignore it. FIXME: warn about this?
2382 Alternatively, make --dired imply --format=long? */
2383 dired
&= (format
== long_format
) & !print_hyperlink
;
2385 if (eolbyte
< dired
)
2386 error (LS_FAILURE
, 0, _("--dired and --zero are incompatible"));
2388 /* If -c or -u is specified and not -l (or any other option that implies -l),
2389 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
2390 The behavior of ls when using either -c or -u but with neither -l nor -t
2391 appears to be unspecified by POSIX. So, with GNU ls, '-u' alone means
2392 sort by atime (this is the one that's not specified by the POSIX spec),
2393 -lu means show atime and sort by name, -lut means show atime and sort
2396 sort_type
= (0 <= sort_opt
? sort_opt
2397 : (format
!= long_format
2398 && (time_type
== time_ctime
|| time_type
== time_atime
2399 || time_type
== time_btime
))
2400 ? sort_time
: sort_name
);
2402 if (format
== long_format
)
2404 char *style
= time_style_option
;
2405 static char const posix_prefix
[] = "posix-";
2408 if (! (style
= getenv ("TIME_STYLE")))
2409 style
= bad_cast ("locale");
2411 while (STREQ_LEN (style
, posix_prefix
, sizeof posix_prefix
- 1))
2413 if (! hard_locale (LC_TIME
))
2415 style
+= sizeof posix_prefix
- 1;
2420 char *p0
= style
+ 1;
2421 char *p1
= strchr (p0
, '\n');
2426 if (strchr (p1
+ 1, '\n'))
2427 error (LS_FAILURE
, 0, _("invalid time style format %s"),
2431 long_time_format
[0] = p0
;
2432 long_time_format
[1] = p1
;
2436 ptrdiff_t res
= argmatch (style
, time_style_args
,
2437 (char const *) time_style_types
,
2438 sizeof (*time_style_types
));
2441 /* This whole block used to be a simple use of XARGMATCH.
2442 but that didn't print the "posix-"-prefixed variants or
2443 the "+"-prefixed format string option upon failure. */
2444 argmatch_invalid ("time style", style
, res
);
2446 /* The following is a manual expansion of argmatch_valid,
2447 but with the added "+ ..." description and the [posix-]
2448 prefixes prepended. Note that this simplification works
2449 only because all four existing time_style_types values
2451 fputs (_("Valid arguments are:\n"), stderr
);
2452 char const *const *p
= time_style_args
;
2454 fprintf (stderr
, " - [posix-]%s\n", *p
++);
2455 fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
2456 " format\n"), stderr
);
2461 case full_iso_time_style
:
2462 long_time_format
[0] = long_time_format
[1] =
2463 "%Y-%m-%d %H:%M:%S.%N %z";
2466 case long_iso_time_style
:
2467 long_time_format
[0] = long_time_format
[1] = "%Y-%m-%d %H:%M";
2470 case iso_time_style
:
2471 long_time_format
[0] = "%Y-%m-%d ";
2472 long_time_format
[1] = "%m-%d %H:%M";
2475 case locale_time_style
:
2476 if (hard_locale (LC_TIME
))
2478 for (int i
= 0; i
< 2; i
++)
2479 long_time_format
[i
] =
2480 dcgettext (nullptr, long_time_format
[i
], LC_TIME
);
2491 /* Parse a string as part of the LS_COLORS variable; this may involve
2492 decoding all kinds of escape characters. If equals_end is set an
2493 unescaped equal sign ends the string, otherwise only a : or \0
2494 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2497 The resulting string is *not* null-terminated, but may contain
2500 Note that both dest and src are char **; on return they point to
2501 the first free byte after the array and the character that ended
2502 the input string, respectively. */
2505 get_funky_string (char **dest
, char const **src
, bool equals_end
,
2506 size_t *output_count
)
2508 char num
; /* For numerical codes */
2509 size_t count
; /* Something to count with */
2511 ST_GND
, ST_BACKSLASH
, ST_OCTAL
, ST_HEX
, ST_CARET
, ST_END
, ST_ERROR
2516 p
= *src
; /* We don't want to double-indirect */
2517 q
= *dest
; /* the whole darn time. */
2519 count
= 0; /* No characters counted in yet. */
2522 state
= ST_GND
; /* Start in ground state. */
2523 while (state
< ST_END
)
2527 case ST_GND
: /* Ground state (no escapes) */
2532 state
= ST_END
; /* End of string */
2535 state
= ST_BACKSLASH
; /* Backslash escape sequence */
2539 state
= ST_CARET
; /* Caret escape */
2545 state
= ST_END
; /* End */
2556 case ST_BACKSLASH
: /* Backslash escaped character */
2567 state
= ST_OCTAL
; /* Octal sequence */
2572 state
= ST_HEX
; /* Hex sequence */
2575 case 'a': /* Bell */
2578 case 'b': /* Backspace */
2581 case 'e': /* Escape */
2584 case 'f': /* Form feed */
2587 case 'n': /* Newline */
2590 case 'r': /* Carriage return */
2596 case 'v': /* Vtab */
2599 case '?': /* Delete */
2602 case '_': /* Space */
2605 case '\0': /* End of string */
2606 state
= ST_ERROR
; /* Error! */
2608 default: /* Escaped character like \ ^ : = */
2612 if (state
== ST_BACKSLASH
)
2621 case ST_OCTAL
: /* Octal sequence */
2622 if (*p
< '0' || *p
> '7')
2629 num
= (num
<< 3) + (*(p
++) - '0');
2632 case ST_HEX
: /* Hex sequence */
2645 num
= (num
<< 4) + (*(p
++) - '0');
2653 num
= (num
<< 4) + (*(p
++) - 'a') + 10;
2661 num
= (num
<< 4) + (*(p
++) - 'A') + 10;
2671 case ST_CARET
: /* Caret escape */
2672 state
= ST_GND
; /* Should be the next state... */
2673 if (*p
>= '@' && *p
<= '~')
2675 *(q
++) = *(p
++) & 037;
2694 *output_count
= count
;
2696 return state
!= ST_ERROR
;
2710 /* Check if the content of TERM is a valid name in dircolors. */
2713 known_term_type (void)
2715 char const *term
= getenv ("TERM");
2716 if (! term
|| ! *term
)
2719 char const *line
= G_line
;
2720 while (line
- G_line
< sizeof (G_line
))
2722 if (STRNCMP_LIT (line
, "TERM ") == 0)
2724 if (fnmatch (line
+ 5, term
, 0) == 0)
2727 line
+= strlen (line
) + 1;
2734 parse_ls_color (void)
2736 char const *p
; /* Pointer to character being parsed */
2737 char *buf
; /* color_buf buffer pointer */
2738 int ind_no
; /* Indicator number */
2739 char label
[3]; /* Indicator label */
2740 struct color_ext_type
*ext
; /* Extension we are working on */
2742 if ((p
= getenv ("LS_COLORS")) == nullptr || *p
== '\0')
2744 /* LS_COLORS takes precedence, but if that's not set then
2745 honor the COLORTERM and TERM env variables so that
2746 we only go with the internal ANSI color codes if the
2747 former is non empty or the latter is set to a known value. */
2748 char const *colorterm
= getenv ("COLORTERM");
2749 if (! (colorterm
&& *colorterm
) && ! known_term_type ())
2750 print_with_color
= false;
2755 strcpy (label
, "??");
2757 /* This is an overly conservative estimate, but any possible
2758 LS_COLORS string will *not* generate a color_buf longer than
2759 itself, so it is a safe way of allocating a buffer in
2761 buf
= color_buf
= xstrdup (p
);
2763 enum parse_state state
= PS_START
;
2768 case PS_START
: /* First label character */
2776 /* Allocate new extension block and add to head of
2777 linked list (this way a later definition will
2778 override an earlier one, which can be useful for
2779 having terminal-specific defs override global). */
2781 ext
= xmalloc (sizeof *ext
);
2782 ext
->next
= color_ext_list
;
2783 color_ext_list
= ext
;
2784 ext
->exact_match
= false;
2787 ext
->ext
.string
= buf
;
2789 state
= (get_funky_string (&buf
, &p
, true, &ext
->ext
.len
)
2794 state
= PS_DONE
; /* Done! */
2797 default: /* Assume it is file type label */
2804 case PS_2
: /* Second label character */
2811 state
= PS_FAIL
; /* Error */
2814 case PS_3
: /* Equal sign after indicator label */
2815 state
= PS_FAIL
; /* Assume failure... */
2816 if (*(p
++) == '=')/* It *should* be... */
2818 for (ind_no
= 0; indicator_name
[ind_no
] != nullptr; ++ind_no
)
2820 if (STREQ (label
, indicator_name
[ind_no
]))
2822 color_indicator
[ind_no
].string
= buf
;
2823 state
= (get_funky_string (&buf
, &p
, false,
2824 &color_indicator
[ind_no
].len
)
2825 ? PS_START
: PS_FAIL
);
2829 if (state
== PS_FAIL
)
2830 error (0, 0, _("unrecognized prefix: %s"), quote (label
));
2834 case PS_4
: /* Equal sign after *.ext */
2837 ext
->seq
.string
= buf
;
2838 state
= (get_funky_string (&buf
, &p
, false, &ext
->seq
.len
)
2839 ? PS_START
: PS_FAIL
);
2854 if (state
== PS_FAIL
)
2856 struct color_ext_type
*e
;
2857 struct color_ext_type
*e2
;
2860 _("unparsable value for LS_COLORS environment variable"));
2862 for (e
= color_ext_list
; e
!= nullptr; /* empty */)
2868 print_with_color
= false;
2872 /* Postprocess list to set EXACT_MATCH on entries where there are
2873 different cased extensions with separate sequences defined.
2874 Also set ext.len to SIZE_MAX on any entries that can't
2875 match due to precedence, to avoid redundant string compares. */
2876 struct color_ext_type
*e1
;
2878 for (e1
= color_ext_list
; e1
!= nullptr; e1
= e1
->next
)
2880 struct color_ext_type
*e2
;
2881 bool case_ignored
= false;
2883 for (e2
= e1
->next
; e2
!= nullptr; e2
= e2
->next
)
2885 if (e2
->ext
.len
< SIZE_MAX
&& e1
->ext
.len
== e2
->ext
.len
)
2887 if (memcmp (e1
->ext
.string
, e2
->ext
.string
, e1
->ext
.len
) == 0)
2888 e2
->ext
.len
= SIZE_MAX
; /* Ignore */
2889 else if (c_strncasecmp (e1
->ext
.string
, e2
->ext
.string
,
2894 e2
->ext
.len
= SIZE_MAX
; /* Ignore */
2896 else if (e1
->seq
.len
== e2
->seq
.len
2897 && memcmp (e1
->seq
.string
, e2
->seq
.string
,
2900 e2
->ext
.len
= SIZE_MAX
; /* Ignore */
2901 case_ignored
= true; /* Ignore all subsequent */
2905 e1
->exact_match
= true;
2906 e2
->exact_match
= true;
2914 if (color_indicator
[C_LINK
].len
== 6
2915 && !STRNCMP_LIT (color_indicator
[C_LINK
].string
, "target"))
2916 color_symlink_as_referent
= true;
2919 /* Return the quoting style specified by the environment variable
2920 QUOTING_STYLE if set and valid, -1 otherwise. */
2923 getenv_quoting_style (void)
2925 char const *q_style
= getenv ("QUOTING_STYLE");
2928 int i
= ARGMATCH (q_style
, quoting_style_args
, quoting_style_vals
);
2932 _("ignoring invalid value"
2933 " of environment variable QUOTING_STYLE: %s"),
2937 return quoting_style_vals
[i
];
2940 /* Set the exit status to report a failure. If SERIOUS, it is a
2941 serious failure; otherwise, it is merely a minor problem. */
2944 set_exit_status (bool serious
)
2947 exit_status
= LS_FAILURE
;
2948 else if (exit_status
== EXIT_SUCCESS
)
2949 exit_status
= LS_MINOR_PROBLEM
;
2952 /* Assuming a failure is serious if SERIOUS, use the printf-style
2953 MESSAGE to report the failure to access a file named FILE. Assume
2954 errno is set appropriately for the failure. */
2957 file_failure (bool serious
, char const *message
, char const *file
)
2959 error (0, errno
, message
, quoteaf (file
));
2960 set_exit_status (serious
);
2963 /* Request that the directory named NAME have its contents listed later.
2964 If REALNAME is nonzero, it will be used instead of NAME when the
2965 directory name is printed. This allows symbolic links to directories
2966 to be treated as regular directories but still be listed under their
2967 real names. NAME == nullptr is used to insert a marker entry for the
2968 directory named in REALNAME.
2969 If NAME is non-null, we use its dev/ino information to save
2970 a call to stat -- when doing a recursive (-R) traversal.
2971 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2974 queue_directory (char const *name
, char const *realname
, bool command_line_arg
)
2976 struct pending
*new = xmalloc (sizeof *new);
2977 new->realname
= realname
? xstrdup (realname
) : nullptr;
2978 new->name
= name
? xstrdup (name
) : nullptr;
2979 new->command_line_arg
= command_line_arg
;
2980 new->next
= pending_dirs
;
2984 /* Read directory NAME, and list the files in it.
2985 If REALNAME is nonzero, print its name instead of NAME;
2986 this is used for symbolic links to directories.
2987 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2990 print_dir (char const *name
, char const *realname
, bool command_line_arg
)
2993 struct dirent
*next
;
2994 uintmax_t total_blocks
= 0;
2995 static bool first
= true;
2998 dirp
= opendir (name
);
3001 file_failure (command_line_arg
, _("cannot open directory %s"), name
);
3007 struct stat dir_stat
;
3008 int fd
= dirfd (dirp
);
3010 /* If dirfd failed, endure the overhead of stat'ing by path */
3012 ? fstat_for_ino (fd
, &dir_stat
)
3013 : stat_for_ino (name
, &dir_stat
)) < 0)
3015 file_failure (command_line_arg
,
3016 _("cannot determine device and inode of %s"), name
);
3021 /* If we've already visited this dev/inode pair, warn that
3022 we've found a loop, and do not process this directory. */
3023 if (visit_dir (dir_stat
.st_dev
, dir_stat
.st_ino
))
3025 error (0, 0, _("%s: not listing already-listed directory"),
3028 set_exit_status (true);
3032 dev_ino_push (dir_stat
.st_dev
, dir_stat
.st_ino
);
3037 if (recursive
|| print_dir_name
)
3040 dired_outbyte ('\n');
3044 char *absolute_name
= nullptr;
3045 if (print_hyperlink
)
3047 absolute_name
= canonicalize_filename_mode (name
, CAN_MISSING
);
3048 if (! absolute_name
)
3049 file_failure (command_line_arg
,
3050 _("error canonicalizing %s"), name
);
3052 quote_name (realname
? realname
: name
, dirname_quoting_options
, -1,
3053 nullptr, true, &subdired_obstack
, absolute_name
);
3055 free (absolute_name
);
3057 dired_outstring (":\n");
3060 /* Read the directory entries, and insert the subfiles into the 'cwd_file'
3065 /* Set errno to zero so we can distinguish between a readdir failure
3066 and when readdir simply finds that there are no more entries. */
3068 next
= readdir (dirp
);
3071 if (! file_ignored (next
->d_name
))
3073 enum filetype type
= unknown
;
3075 #if HAVE_STRUCT_DIRENT_D_TYPE
3076 switch (next
->d_type
)
3078 case DT_BLK
: type
= blockdev
; break;
3079 case DT_CHR
: type
= chardev
; break;
3080 case DT_DIR
: type
= directory
; break;
3081 case DT_FIFO
: type
= fifo
; break;
3082 case DT_LNK
: type
= symbolic_link
; break;
3083 case DT_REG
: type
= normal
; break;
3084 case DT_SOCK
: type
= sock
; break;
3086 case DT_WHT
: type
= whiteout
; break;
3090 total_blocks
+= gobble_file (next
->d_name
, type
,
3091 RELIABLE_D_INO (next
),
3094 /* In this narrow case, print out each name right away, so
3095 ls uses constant memory while processing the entries of
3096 this directory. Useful when there are many (millions)
3097 of entries in a directory. */
3098 if (format
== one_per_line
&& sort_type
== sort_none
3099 && !print_block_size
&& !recursive
)
3101 /* We must call sort_files in spite of
3102 "sort_type == sort_none" for its initialization
3103 of the sorted_file vector. */
3105 print_current_files ();
3110 else if (errno
!= 0)
3112 file_failure (command_line_arg
, _("reading directory %s"), name
);
3113 if (errno
!= EOVERFLOW
)
3119 /* When processing a very large directory, and since we've inhibited
3120 interrupts, this loop would take so long that ls would be annoyingly
3121 uninterruptible. This ensures that it handles signals promptly. */
3125 if (closedir (dirp
) != 0)
3127 file_failure (command_line_arg
, _("closing directory %s"), name
);
3128 /* Don't return; print whatever we got. */
3131 /* Sort the directory contents. */
3134 /* If any member files are subdirectories, perhaps they should have their
3135 contents listed rather than being mentioned here as files. */
3138 extract_dirs_from_files (name
, false);
3140 if (format
== long_format
|| print_block_size
)
3142 char buf
[LONGEST_HUMAN_READABLE
+ 3];
3143 char *p
= human_readable (total_blocks
, buf
+ 1, human_output_opts
,
3144 ST_NBLOCKSIZE
, output_block_size
);
3145 char *pend
= p
+ strlen (p
);
3149 dired_outstring (_("total"));
3150 dired_outbuf (p
, pend
- p
);
3154 print_current_files ();
3157 /* Add 'pattern' to the list of patterns for which files that match are
3161 add_ignore_pattern (char const *pattern
)
3163 struct ignore_pattern
*ignore
;
3165 ignore
= xmalloc (sizeof *ignore
);
3166 ignore
->pattern
= pattern
;
3167 /* Add it to the head of the linked list. */
3168 ignore
->next
= ignore_patterns
;
3169 ignore_patterns
= ignore
;
3172 /* Return true if one of the PATTERNS matches FILE. */
3175 patterns_match (struct ignore_pattern
const *patterns
, char const *file
)
3177 struct ignore_pattern
const *p
;
3178 for (p
= patterns
; p
; p
= p
->next
)
3179 if (fnmatch (p
->pattern
, file
, FNM_PERIOD
) == 0)
3184 /* Return true if FILE should be ignored. */
3187 file_ignored (char const *name
)
3189 return ((ignore_mode
!= IGNORE_MINIMAL
3191 && (ignore_mode
== IGNORE_DEFAULT
|| ! name
[1 + (name
[1] == '.')]))
3192 || (ignore_mode
== IGNORE_DEFAULT
3193 && patterns_match (hide_patterns
, name
))
3194 || patterns_match (ignore_patterns
, name
));
3197 /* POSIX requires that a file size be printed without a sign, even
3198 when negative. Assume the typical case where negative sizes are
3199 actually positive values that have wrapped around. */
3202 unsigned_file_size (off_t size
)
3204 return size
+ (size
< 0) * ((uintmax_t) OFF_T_MAX
- OFF_T_MIN
+ 1);
3208 /* Return true if NAME has a capability (see linux/capability.h) */
3210 has_capability (char const *name
)
3215 cap_t cap_d
= cap_get_file (name
);
3216 if (cap_d
== nullptr)
3219 result
= cap_to_text (cap_d
, nullptr);
3224 /* check if human-readable capability string is empty */
3225 has_cap
= !!*result
;
3232 has_capability (MAYBE_UNUSED
char const *name
)
3239 /* Enter and remove entries in the table 'cwd_file'. */
3242 free_ent (struct fileinfo
*f
)
3246 free (f
->absolute_name
);
3247 if (f
->scontext
!= UNKNOWN_SECURITY_CONTEXT
)
3249 if (is_smack_enabled ())
3252 freecon (f
->scontext
);
3256 /* Empty the table of files. */
3260 for (size_t i
= 0; i
< cwd_n_used
; i
++)
3262 struct fileinfo
*f
= sorted_file
[i
];
3267 cwd_some_quoted
= false;
3268 any_has_acl
= false;
3269 inode_number_width
= 0;
3270 block_size_width
= 0;
3276 major_device_number_width
= 0;
3277 minor_device_number_width
= 0;
3278 file_size_width
= 0;
3281 /* Return true if ERR implies lack-of-support failure by a
3282 getxattr-calling function like getfilecon or file_has_acl. */
3284 errno_unsupported (int err
)
3286 return (err
== EINVAL
|| err
== ENOSYS
|| is_ENOTSUP (err
));
3289 /* Cache *getfilecon failure, when it's trivial to do so.
3290 Like getfilecon/lgetfilecon, but when F's st_dev says it's doesn't
3291 support getting the security context, fail with ENOTSUP immediately. */
3293 getfilecon_cache (char const *file
, struct fileinfo
*f
, bool deref
)
3295 /* st_dev of the most recently processed device for which we've
3296 found that [l]getfilecon fails indicating lack of support. */
3297 static dev_t unsupported_device
;
3299 if (f
->stat
.st_dev
== unsupported_device
)
3306 if (is_smack_enabled ())
3307 r
= smack_new_label_from_path (file
, "security.SMACK64", deref
,
3312 ? getfilecon (file
, &f
->scontext
)
3313 : lgetfilecon (file
, &f
->scontext
));
3314 if (r
< 0 && errno_unsupported (errno
))
3315 unsupported_device
= f
->stat
.st_dev
;
3319 /* Cache file_has_acl failure, when it's trivial to do.
3320 Like file_has_acl, but when F's st_dev says it's on a file
3321 system lacking ACL support, return 0 with ENOTSUP immediately. */
3323 file_has_acl_cache (char const *file
, struct fileinfo
*f
)
3325 /* st_dev of the most recently processed device for which we've
3326 found that file_has_acl fails indicating lack of support. */
3327 static dev_t unsupported_device
;
3329 if (f
->stat
.st_dev
== unsupported_device
)
3335 /* Zero errno so that we can distinguish between two 0-returning cases:
3336 "has-ACL-support, but only a default ACL" and "no ACL support". */
3338 int n
= file_has_acl (file
, &f
->stat
);
3339 if (n
<= 0 && errno_unsupported (errno
))
3340 unsupported_device
= f
->stat
.st_dev
;
3344 /* Cache has_capability failure, when it's trivial to do.
3345 Like has_capability, but when F's st_dev says it's on a file
3346 system lacking capability support, return 0 with ENOTSUP immediately. */
3348 has_capability_cache (char const *file
, struct fileinfo
*f
)
3350 /* st_dev of the most recently processed device for which we've
3351 found that has_capability fails indicating lack of support. */
3352 static dev_t unsupported_device
;
3354 if (f
->stat
.st_dev
== unsupported_device
)
3360 bool b
= has_capability (file
);
3361 if ( !b
&& errno_unsupported (errno
))
3362 unsupported_device
= f
->stat
.st_dev
;
3367 needs_quoting (char const *name
)
3370 size_t len
= quotearg_buffer (test
, sizeof test
, name
, -1,
3371 filename_quoting_options
);
3372 return *name
!= *test
|| strlen (name
) != len
;
3375 /* Add a file to the current table of files.
3376 Verify that the file exists, and print an error message if it does not.
3377 Return the number of blocks that the file occupies. */
3379 gobble_file (char const *name
, enum filetype type
, ino_t inode
,
3380 bool command_line_arg
, char const *dirname
)
3382 uintmax_t blocks
= 0;
3385 /* An inode value prior to gobble_file necessarily came from readdir,
3386 which is not used for command line arguments. */
3387 affirm (! command_line_arg
|| inode
== NOT_AN_INODE_NUMBER
);
3389 if (cwd_n_used
== cwd_n_alloc
)
3391 cwd_file
= xnrealloc (cwd_file
, cwd_n_alloc
, 2 * sizeof *cwd_file
);
3395 f
= &cwd_file
[cwd_n_used
];
3396 memset (f
, '\0', sizeof *f
);
3397 f
->stat
.st_ino
= inode
;
3401 if ((! cwd_some_quoted
) && align_variable_outer_quotes
)
3403 /* Determine if any quoted for padding purposes. */
3404 f
->quoted
= needs_quoting (name
);
3406 cwd_some_quoted
= 1;
3409 if (command_line_arg
3411 || format_needs_stat
3412 /* When coloring a directory (we may know the type from
3413 direct.d_type), we have to stat it in order to indicate
3414 sticky and/or other-writable attributes. */
3415 || (type
== directory
&& print_with_color
3416 && (is_colored (C_OTHER_WRITABLE
)
3417 || is_colored (C_STICKY
)
3418 || is_colored (C_STICKY_OTHER_WRITABLE
)))
3419 /* When dereferencing symlinks, the inode and type must come from
3420 stat, but readdir provides the inode and type of lstat. */
3421 || ((print_inode
|| format_needs_type
)
3422 && (type
== symbolic_link
|| type
== unknown
)
3423 && (dereference
== DEREF_ALWAYS
3424 || color_symlink_as_referent
|| check_symlink_mode
))
3425 /* Command line dereferences are already taken care of by the above
3426 assertion that the inode number is not yet known. */
3427 || (print_inode
&& inode
== NOT_AN_INODE_NUMBER
)
3428 || (format_needs_type
3429 && (type
== unknown
|| command_line_arg
3430 /* --indicator-style=classify (aka -F)
3431 requires that we stat each regular file
3432 to see if it's executable. */
3433 || (type
== normal
&& (indicator_style
== classify
3434 /* This is so that --color ends up
3435 highlighting files with these mode
3436 bits set even when options like -F are
3437 not specified. Note we do a redundant
3438 stat in the very unlikely case where
3439 C_CAP is set but not the others. */
3440 || (print_with_color
3441 && (is_colored (C_EXEC
)
3442 || is_colored (C_SETUID
)
3443 || is_colored (C_SETGID
)
3444 || is_colored (C_CAP
)))
3448 /* Absolute name of this file. */
3453 if (name
[0] == '/' || dirname
[0] == 0)
3454 full_name
= (char *) name
;
3457 full_name
= alloca (strlen (name
) + strlen (dirname
) + 2);
3458 attach (full_name
, dirname
, name
);
3461 if (print_hyperlink
)
3463 f
->absolute_name
= canonicalize_filename_mode (full_name
,
3465 if (! f
->absolute_name
)
3466 file_failure (command_line_arg
,
3467 _("error canonicalizing %s"), full_name
);
3470 switch (dereference
)
3473 err
= do_stat (full_name
, &f
->stat
);
3477 case DEREF_COMMAND_LINE_ARGUMENTS
:
3478 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR
:
3479 if (command_line_arg
)
3482 err
= do_stat (full_name
, &f
->stat
);
3485 if (dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
3488 need_lstat
= (err
< 0
3489 ? (errno
== ENOENT
|| errno
== ELOOP
)
3490 : ! S_ISDIR (f
->stat
.st_mode
));
3494 /* stat failed because of ENOENT || ELOOP, maybe indicating a
3495 non-traversable symlink. Or stat succeeded,
3496 FULL_NAME does not refer to a directory,
3497 and --dereference-command-line-symlink-to-dir is in effect.
3498 Fall through so that we call lstat instead. */
3502 default: /* DEREF_NEVER */
3503 err
= do_lstat (full_name
, &f
->stat
);
3510 /* Failure to stat a command line argument leads to
3511 an exit status of 2. For other files, stat failure
3512 provokes an exit status of 1. */
3513 file_failure (command_line_arg
,
3514 _("cannot access %s"), full_name
);
3516 f
->scontext
= UNKNOWN_SECURITY_CONTEXT
;
3518 if (command_line_arg
)
3521 f
->name
= xstrdup (name
);
3529 /* Note has_capability() adds around 30% runtime to 'ls --color' */
3530 if ((type
== normal
|| S_ISREG (f
->stat
.st_mode
))
3531 && print_with_color
&& is_colored (C_CAP
))
3532 f
->has_capability
= has_capability_cache (full_name
, f
);
3534 if (format
== long_format
|| print_scontext
)
3536 bool have_scontext
= false;
3537 bool have_acl
= false;
3538 int attr_len
= getfilecon_cache (full_name
, f
, do_deref
);
3539 err
= (attr_len
< 0);
3543 if (is_smack_enabled ())
3544 have_scontext
= ! STREQ ("_", f
->scontext
);
3546 have_scontext
= ! STREQ ("unlabeled", f
->scontext
);
3550 f
->scontext
= UNKNOWN_SECURITY_CONTEXT
;
3552 /* When requesting security context information, don't make
3553 ls fail just because the file (even a command line argument)
3554 isn't on the right type of file system. I.e., a getfilecon
3555 failure isn't in the same class as a stat failure. */
3556 if (is_ENOTSUP (errno
) || errno
== ENODATA
)
3560 if (err
== 0 && format
== long_format
)
3562 int n
= file_has_acl_cache (full_name
, f
);
3567 f
->acl_type
= (!have_scontext
&& !have_acl
3569 : (have_scontext
&& !have_acl
3570 ? ACL_T_LSM_CONTEXT_ONLY
3572 any_has_acl
|= f
->acl_type
!= ACL_T_NONE
;
3575 error (0, errno
, "%s", quotef (full_name
));
3578 if (S_ISLNK (f
->stat
.st_mode
)
3579 && (format
== long_format
|| check_symlink_mode
))
3581 struct stat linkstats
;
3583 get_link_name (full_name
, f
, command_line_arg
);
3585 /* Use the slower quoting path for this entry, though
3586 don't update CWD_SOME_QUOTED since alignment not affected. */
3587 if (f
->linkname
&& f
->quoted
== 0 && needs_quoting (f
->linkname
))
3590 /* Avoid following symbolic links when possible, i.e., when
3591 they won't be traced and when no indicator is needed. */
3593 && (file_type
<= indicator_style
|| check_symlink_mode
)
3594 && stat_for_mode (full_name
, &linkstats
) == 0)
3597 f
->linkmode
= linkstats
.st_mode
;
3601 if (S_ISLNK (f
->stat
.st_mode
))
3602 f
->filetype
= symbolic_link
;
3603 else if (S_ISDIR (f
->stat
.st_mode
))
3605 if (command_line_arg
&& !immediate_dirs
)
3606 f
->filetype
= arg_directory
;
3608 f
->filetype
= directory
;
3611 f
->filetype
= normal
;
3613 blocks
= ST_NBLOCKS (f
->stat
);
3614 if (format
== long_format
|| print_block_size
)
3616 char buf
[LONGEST_HUMAN_READABLE
+ 1];
3617 int len
= mbswidth (human_readable (blocks
, buf
, human_output_opts
,
3618 ST_NBLOCKSIZE
, output_block_size
),
3620 if (block_size_width
< len
)
3621 block_size_width
= len
;
3624 if (format
== long_format
)
3628 int len
= format_user_width (f
->stat
.st_uid
);
3629 if (owner_width
< len
)
3635 int len
= format_group_width (f
->stat
.st_gid
);
3636 if (group_width
< len
)
3642 int len
= format_user_width (f
->stat
.st_author
);
3643 if (author_width
< len
)
3650 int len
= strlen (f
->scontext
);
3651 if (scontext_width
< len
)
3652 scontext_width
= len
;
3655 if (format
== long_format
)
3657 char b
[INT_BUFSIZE_BOUND (uintmax_t)];
3658 int b_len
= strlen (umaxtostr (f
->stat
.st_nlink
, b
));
3659 if (nlink_width
< b_len
)
3660 nlink_width
= b_len
;
3662 if (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
))
3664 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
3665 int len
= strlen (umaxtostr (major (f
->stat
.st_rdev
), buf
));
3666 if (major_device_number_width
< len
)
3667 major_device_number_width
= len
;
3668 len
= strlen (umaxtostr (minor (f
->stat
.st_rdev
), buf
));
3669 if (minor_device_number_width
< len
)
3670 minor_device_number_width
= len
;
3671 len
= major_device_number_width
+ 2 + minor_device_number_width
;
3672 if (file_size_width
< len
)
3673 file_size_width
= len
;
3677 char buf
[LONGEST_HUMAN_READABLE
+ 1];
3678 uintmax_t size
= unsigned_file_size (f
->stat
.st_size
);
3679 int len
= mbswidth (human_readable (size
, buf
,
3680 file_human_output_opts
,
3681 1, file_output_block_size
),
3683 if (file_size_width
< len
)
3684 file_size_width
= len
;
3691 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
3692 int len
= strlen (umaxtostr (f
->stat
.st_ino
, buf
));
3693 if (inode_number_width
< len
)
3694 inode_number_width
= len
;
3697 f
->name
= xstrdup (name
);
3703 /* Return true if F refers to a directory. */
3705 is_directory (const struct fileinfo
*f
)
3707 return f
->filetype
== directory
|| f
->filetype
== arg_directory
;
3710 /* Return true if F refers to a (symlinked) directory. */
3712 is_linked_directory (const struct fileinfo
*f
)
3714 return f
->filetype
== directory
|| f
->filetype
== arg_directory
3715 || S_ISDIR (f
->linkmode
);
3718 /* Put the name of the file that FILENAME is a symbolic link to
3719 into the LINKNAME field of 'f'. COMMAND_LINE_ARG indicates whether
3720 FILENAME is a command-line argument. */
3723 get_link_name (char const *filename
, struct fileinfo
*f
, bool command_line_arg
)
3725 f
->linkname
= areadlink_with_size (filename
, f
->stat
.st_size
);
3726 if (f
->linkname
== nullptr)
3727 file_failure (command_line_arg
, _("cannot read symbolic link %s"),
3731 /* Return true if the last component of NAME is '.' or '..'
3732 This is so we don't try to recurse on '././././. ...' */
3735 basename_is_dot_or_dotdot (char const *name
)
3737 char const *base
= last_component (name
);
3738 return dot_or_dotdot (base
);
3741 /* Remove any entries from CWD_FILE that are for directories,
3742 and queue them to be listed as directories instead.
3743 DIRNAME is the prefix to prepend to each dirname
3744 to make it correct relative to ls's working dir;
3745 if it is null, no prefix is needed and "." and ".." should not be ignored.
3746 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3747 This is desirable when processing directories recursively. */
3750 extract_dirs_from_files (char const *dirname
, bool command_line_arg
)
3754 bool ignore_dot_and_dot_dot
= (dirname
!= nullptr);
3756 if (dirname
&& LOOP_DETECT
)
3758 /* Insert a marker entry first. When we dequeue this marker entry,
3759 we'll know that DIRNAME has been processed and may be removed
3760 from the set of active directories. */
3761 queue_directory (nullptr, dirname
, false);
3764 /* Queue the directories last one first, because queueing reverses the
3766 for (i
= cwd_n_used
; i
-- != 0; )
3768 struct fileinfo
*f
= sorted_file
[i
];
3770 if (is_directory (f
)
3771 && (! ignore_dot_and_dot_dot
3772 || ! basename_is_dot_or_dotdot (f
->name
)))
3774 if (!dirname
|| f
->name
[0] == '/')
3775 queue_directory (f
->name
, f
->linkname
, command_line_arg
);
3778 char *name
= file_name_concat (dirname
, f
->name
, nullptr);
3779 queue_directory (name
, f
->linkname
, command_line_arg
);
3782 if (f
->filetype
== arg_directory
)
3787 /* Now delete the directories from the table, compacting all the remaining
3790 for (i
= 0, j
= 0; i
< cwd_n_used
; i
++)
3792 struct fileinfo
*f
= sorted_file
[i
];
3794 j
+= (f
->filetype
!= arg_directory
);
3799 /* Use strcoll to compare strings in this locale. If an error occurs,
3800 report an error and longjmp to failed_strcoll. */
3802 static jmp_buf failed_strcoll
;
3805 xstrcoll (char const *a
, char const *b
)
3809 diff
= strcoll (a
, b
);
3812 error (0, errno
, _("cannot compare file names %s and %s"),
3813 quote_n (0, a
), quote_n (1, b
));
3814 set_exit_status (false);
3815 longjmp (failed_strcoll
, 1);
3820 /* Comparison routines for sorting the files. */
3822 typedef void const *V
;
3823 typedef int (*qsortFunc
)(V a
, V b
);
3825 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants. */
3827 dirfirst_check (struct fileinfo
const *a
, struct fileinfo
const *b
,
3830 int diff
= is_linked_directory (b
) - is_linked_directory (a
);
3831 return diff
? diff
: cmp (a
, b
);
3834 /* Define the 8 different sort function variants required for each sortkey.
3835 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3836 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3837 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3838 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3839 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3840 /* direct, non-dirfirst versions */ \
3841 static int xstrcoll_##key_name (V a, V b) \
3842 { return key_cmp_func (a, b, xstrcoll); } \
3843 ATTRIBUTE_PURE static int strcmp_##key_name (V a, V b) \
3844 { return key_cmp_func (a, b, strcmp); } \
3846 /* reverse, non-dirfirst versions */ \
3847 static int rev_xstrcoll_##key_name (V a, V b) \
3848 { return key_cmp_func (b, a, xstrcoll); } \
3849 ATTRIBUTE_PURE static int rev_strcmp_##key_name (V a, V b) \
3850 { return key_cmp_func (b, a, strcmp); } \
3852 /* direct, dirfirst versions */ \
3853 static int xstrcoll_df_##key_name (V a, V b) \
3854 { return dirfirst_check (a, b, xstrcoll_##key_name); } \
3855 ATTRIBUTE_PURE static int strcmp_df_##key_name (V a, V b) \
3856 { return dirfirst_check (a, b, strcmp_##key_name); } \
3858 /* reverse, dirfirst versions */ \
3859 static int rev_xstrcoll_df_##key_name (V a, V b) \
3860 { return dirfirst_check (a, b, rev_xstrcoll_##key_name); } \
3861 ATTRIBUTE_PURE static int rev_strcmp_df_##key_name (V a, V b) \
3862 { return dirfirst_check (a, b, rev_strcmp_##key_name); }
3865 cmp_ctime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3866 int (*cmp
) (char const *, char const *))
3868 int diff
= timespec_cmp (get_stat_ctime (&b
->stat
),
3869 get_stat_ctime (&a
->stat
));
3870 return diff
? diff
: cmp (a
->name
, b
->name
);
3874 cmp_mtime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3875 int (*cmp
) (char const *, char const *))
3877 int diff
= timespec_cmp (get_stat_mtime (&b
->stat
),
3878 get_stat_mtime (&a
->stat
));
3879 return diff
? diff
: cmp (a
->name
, b
->name
);
3883 cmp_atime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3884 int (*cmp
) (char const *, char const *))
3886 int diff
= timespec_cmp (get_stat_atime (&b
->stat
),
3887 get_stat_atime (&a
->stat
));
3888 return diff
? diff
: cmp (a
->name
, b
->name
);
3892 cmp_btime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3893 int (*cmp
) (char const *, char const *))
3895 int diff
= timespec_cmp (get_stat_btime (&b
->stat
),
3896 get_stat_btime (&a
->stat
));
3897 return diff
? diff
: cmp (a
->name
, b
->name
);
3901 off_cmp (off_t a
, off_t b
)
3903 return (a
> b
) - (a
< b
);
3907 cmp_size (struct fileinfo
const *a
, struct fileinfo
const *b
,
3908 int (*cmp
) (char const *, char const *))
3910 int diff
= off_cmp (b
->stat
.st_size
, a
->stat
.st_size
);
3911 return diff
? diff
: cmp (a
->name
, b
->name
);
3915 cmp_name (struct fileinfo
const *a
, struct fileinfo
const *b
,
3916 int (*cmp
) (char const *, char const *))
3918 return cmp (a
->name
, b
->name
);
3921 /* Compare file extensions. Files with no extension are 'smallest'.
3922 If extensions are the same, compare by file names instead. */
3925 cmp_extension (struct fileinfo
const *a
, struct fileinfo
const *b
,
3926 int (*cmp
) (char const *, char const *))
3928 char const *base1
= strrchr (a
->name
, '.');
3929 char const *base2
= strrchr (b
->name
, '.');
3930 int diff
= cmp (base1
? base1
: "", base2
? base2
: "");
3931 return diff
? diff
: cmp (a
->name
, b
->name
);
3934 /* Return the (cached) screen width,
3935 for the NAME associated with the passed fileinfo F. */
3938 fileinfo_name_width (struct fileinfo
const *f
)
3942 : quote_name_width (f
->name
, filename_quoting_options
, f
->quoted
);
3946 cmp_width (struct fileinfo
const *a
, struct fileinfo
const *b
,
3947 int (*cmp
) (char const *, char const *))
3949 int diff
= fileinfo_name_width (a
) - fileinfo_name_width (b
);
3950 return diff
? diff
: cmp (a
->name
, b
->name
);
3953 DEFINE_SORT_FUNCTIONS (ctime
, cmp_ctime
)
3954 DEFINE_SORT_FUNCTIONS (mtime
, cmp_mtime
)
3955 DEFINE_SORT_FUNCTIONS (atime
, cmp_atime
)
3956 DEFINE_SORT_FUNCTIONS (btime
, cmp_btime
)
3957 DEFINE_SORT_FUNCTIONS (size
, cmp_size
)
3958 DEFINE_SORT_FUNCTIONS (name
, cmp_name
)
3959 DEFINE_SORT_FUNCTIONS (extension
, cmp_extension
)
3960 DEFINE_SORT_FUNCTIONS (width
, cmp_width
)
3962 /* Compare file versions.
3963 Unlike the other compare functions, cmp_version does not fail
3964 because filevercmp and strcmp do not fail; cmp_version uses strcmp
3965 instead of xstrcoll because filevercmp is locale-independent so
3966 strcmp is its appropriate secondary.
3968 All the other sort options need xstrcoll and strcmp variants,
3969 because they all use xstrcoll (either as the primary or secondary
3970 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3973 cmp_version (struct fileinfo
const *a
, struct fileinfo
const *b
)
3975 int diff
= filevercmp (a
->name
, b
->name
);
3976 return diff
? diff
: strcmp (a
->name
, b
->name
);
3980 xstrcoll_version (V a
, V b
)
3982 return cmp_version (a
, b
);
3985 rev_xstrcoll_version (V a
, V b
)
3987 return cmp_version (b
, a
);
3990 xstrcoll_df_version (V a
, V b
)
3992 return dirfirst_check (a
, b
, xstrcoll_version
);
3995 rev_xstrcoll_df_version (V a
, V b
)
3997 return dirfirst_check (a
, b
, rev_xstrcoll_version
);
4001 /* We have 2^3 different variants for each sort-key function
4002 (for 3 independent sort modes).
4003 The function pointers stored in this array must be dereferenced as:
4005 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
4007 Note that the order in which sort keys are listed in the function pointer
4008 array below is defined by the order of the elements in the time_type and
4011 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
4014 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
4015 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
4018 { strcmp_##key_name, strcmp_df_##key_name }, \
4019 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
4023 static qsortFunc
const sort_functions
[][2][2][2] =
4025 LIST_SORTFUNCTION_VARIANTS (name
),
4026 LIST_SORTFUNCTION_VARIANTS (extension
),
4027 LIST_SORTFUNCTION_VARIANTS (width
),
4028 LIST_SORTFUNCTION_VARIANTS (size
),
4032 { xstrcoll_version
, xstrcoll_df_version
},
4033 { rev_xstrcoll_version
, rev_xstrcoll_df_version
},
4036 /* We use nullptr for the strcmp variants of version comparison
4037 since as explained in cmp_version definition, version comparison
4038 does not rely on xstrcoll, so it will never longjmp, and never
4039 need to try the strcmp fallback. */
4041 { nullptr, nullptr },
4042 { nullptr, nullptr },
4046 /* last are time sort functions */
4047 LIST_SORTFUNCTION_VARIANTS (mtime
),
4048 LIST_SORTFUNCTION_VARIANTS (ctime
),
4049 LIST_SORTFUNCTION_VARIANTS (atime
),
4050 LIST_SORTFUNCTION_VARIANTS (btime
)
4053 /* The number of sort keys is calculated as the sum of
4054 the number of elements in the sort_type enum (i.e., sort_numtypes)
4055 -2 because neither sort_time nor sort_none use entries themselves
4056 the number of elements in the time_type enum (i.e., time_numtypes)
4057 This is because when sort_type==sort_time, we have up to
4058 time_numtypes possible sort keys.
4060 This line verifies at compile-time that the array of sort functions has been
4061 initialized for all possible sort keys. */
4062 static_assert (ARRAY_CARDINALITY (sort_functions
)
4063 == sort_numtypes
- 2 + time_numtypes
);
4065 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
4068 initialize_ordering_vector (void)
4070 for (size_t i
= 0; i
< cwd_n_used
; i
++)
4071 sorted_file
[i
] = &cwd_file
[i
];
4074 /* Cache values based on attributes global to all files. */
4077 update_current_files_info (void)
4079 /* Cache screen width of name, if needed multiple times. */
4080 if (sort_type
== sort_width
4081 || (line_length
&& (format
== many_per_line
|| format
== horizontal
)))
4084 for (i
= 0; i
< cwd_n_used
; i
++)
4086 struct fileinfo
*f
= sorted_file
[i
];
4087 f
->width
= fileinfo_name_width (f
);
4092 /* Sort the files now in the table. */
4099 if (sorted_file_alloc
< cwd_n_used
+ cwd_n_used
/ 2)
4102 sorted_file
= xnmalloc (cwd_n_used
, 3 * sizeof *sorted_file
);
4103 sorted_file_alloc
= 3 * cwd_n_used
;
4106 initialize_ordering_vector ();
4108 update_current_files_info ();
4110 if (sort_type
== sort_none
)
4113 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
4114 ignore strcoll failures, as a failing strcoll might be a
4115 comparison function that is not a total order, and if we ignored
4116 the failure this might cause qsort to dump core. */
4118 if (! setjmp (failed_strcoll
))
4119 use_strcmp
= false; /* strcoll() succeeded */
4123 affirm (sort_type
!= sort_version
);
4124 initialize_ordering_vector ();
4127 /* When sort_type == sort_time, use time_type as subindex. */
4128 mpsort ((void const **) sorted_file
, cwd_n_used
,
4129 sort_functions
[sort_type
+ (sort_type
== sort_time
? time_type
: 0)]
4130 [use_strcmp
][sort_reverse
]
4131 [directories_first
]);
4134 /* List all the files now in the table. */
4137 print_current_files (void)
4144 for (i
= 0; i
< cwd_n_used
; i
++)
4146 print_file_name_and_frills (sorted_file
[i
], 0);
4153 print_with_separator (' ');
4155 print_many_per_line ();
4160 print_with_separator (' ');
4162 print_horizontal ();
4166 print_with_separator (',');
4170 for (i
= 0; i
< cwd_n_used
; i
++)
4172 set_normal_color ();
4173 print_long_format (sorted_file
[i
]);
4174 dired_outbyte (eolbyte
);
4180 /* Replace the first %b with precomputed aligned month names.
4181 Note on glibc-2.7 at least, this speeds up the whole 'ls -lU'
4182 process by around 17%, compared to letting strftime() handle the %b. */
4185 align_nstrftime (char *buf
, size_t size
, bool recent
, struct tm
const *tm
,
4186 timezone_t tz
, int ns
)
4188 char const *nfmt
= (use_abformat
4189 ? abformat
[recent
][tm
->tm_mon
]
4190 : long_time_format
[recent
]);
4191 return nstrftime (buf
, size
, nfmt
, tm
, tz
, ns
);
4194 /* Return the expected number of columns in a long-format timestamp,
4195 or zero if it cannot be calculated. */
4198 long_time_expected_width (void)
4200 static int width
= -1;
4206 char buf
[TIME_STAMP_LEN_MAXIMUM
+ 1];
4208 /* In case you're wondering if localtime_rz can fail with an input time_t
4209 value of 0, let's just say it's very unlikely, but not inconceivable.
4210 The TZ environment variable would have to specify a time zone that
4211 is 2**31-1900 years or more ahead of UTC. This could happen only on
4212 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
4213 However, this is not possible with Solaris 10 or glibc-2.3.5, since
4214 their implementations limit the offset to 167:59 and 24:00, resp. */
4215 if (localtime_rz (localtz
, &epoch
, &tm
))
4217 size_t len
= align_nstrftime (buf
, sizeof buf
, false,
4220 width
= mbsnwidth (buf
, len
, MBSWIDTH_FLAGS
);
4230 /* Print the user or group name NAME, with numeric id ID, using a
4231 print width of WIDTH columns. */
4234 format_user_or_group (char const *name
, uintmax_t id
, int width
)
4238 int name_width
= mbswidth (name
, MBSWIDTH_FLAGS
);
4239 int width_gap
= name_width
< 0 ? 0 : width
- name_width
;
4240 int pad
= MAX (0, width_gap
);
4241 dired_outstring (name
);
4244 dired_outbyte (' ');
4248 dired_pos
+= printf ("%*"PRIuMAX
" ", width
, id
);
4251 /* Print the name or id of the user with id U, using a print width of
4255 format_user (uid_t u
, int width
, bool stat_ok
)
4257 format_user_or_group (! stat_ok
? "?" :
4258 (numeric_ids
? nullptr : getuser (u
)), u
, width
);
4261 /* Likewise, for groups. */
4264 format_group (gid_t g
, int width
, bool stat_ok
)
4266 format_user_or_group (! stat_ok
? "?" :
4267 (numeric_ids
? nullptr : getgroup (g
)), g
, width
);
4270 /* Return the number of columns that format_user_or_group will print,
4271 or -1 if unknown. */
4274 format_user_or_group_width (char const *name
, uintmax_t id
)
4277 ? mbswidth (name
, MBSWIDTH_FLAGS
)
4278 : snprintf (nullptr, 0, "%"PRIuMAX
, id
));
4281 /* Return the number of columns that format_user will print,
4282 or -1 if unknown. */
4285 format_user_width (uid_t u
)
4287 return format_user_or_group_width (numeric_ids
? nullptr : getuser (u
), u
);
4290 /* Likewise, for groups. */
4293 format_group_width (gid_t g
)
4295 return format_user_or_group_width (numeric_ids
? nullptr : getgroup (g
), g
);
4298 /* Return a pointer to a formatted version of F->stat.st_ino,
4299 possibly using buffer, which must be at least
4300 INT_BUFSIZE_BOUND (uintmax_t) bytes. */
4302 format_inode (char buf
[INT_BUFSIZE_BOUND (uintmax_t)],
4303 const struct fileinfo
*f
)
4305 return (f
->stat_ok
&& f
->stat
.st_ino
!= NOT_AN_INODE_NUMBER
4306 ? umaxtostr (f
->stat
.st_ino
, buf
)
4310 /* Print information about F in long format. */
4312 print_long_format (const struct fileinfo
*f
)
4316 [LONGEST_HUMAN_READABLE
+ 1 /* inode */
4317 + LONGEST_HUMAN_READABLE
+ 1 /* size in blocks */
4318 + sizeof (modebuf
) - 1 + 1 /* mode string */
4319 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
4320 + LONGEST_HUMAN_READABLE
+ 2 /* major device number */
4321 + LONGEST_HUMAN_READABLE
+ 1 /* minor device number */
4322 + TIME_STAMP_LEN_MAXIMUM
+ 1 /* max length of time/date */
4326 struct timespec when_timespec
;
4327 struct tm when_local
;
4328 bool btime_ok
= true;
4330 /* Compute the mode string, except remove the trailing space if no
4331 file in this directory has an ACL or security context. */
4333 filemodestring (&f
->stat
, modebuf
);
4336 modebuf
[0] = filetype_letter
[f
->filetype
];
4337 memset (modebuf
+ 1, '?', 10);
4342 else if (f
->acl_type
== ACL_T_LSM_CONTEXT_ONLY
)
4344 else if (f
->acl_type
== ACL_T_YES
)
4350 when_timespec
= get_stat_ctime (&f
->stat
);
4353 when_timespec
= get_stat_mtime (&f
->stat
);
4356 when_timespec
= get_stat_atime (&f
->stat
);
4359 when_timespec
= get_stat_btime (&f
->stat
);
4360 if (when_timespec
.tv_sec
== -1 && when_timespec
.tv_nsec
== -1)
4371 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4372 p
+= sprintf (p
, "%*s ", inode_number_width
, format_inode (hbuf
, f
));
4375 if (print_block_size
)
4377 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
4378 char const *blocks
=
4381 : human_readable (ST_NBLOCKS (f
->stat
), hbuf
, human_output_opts
,
4382 ST_NBLOCKSIZE
, output_block_size
));
4383 int blocks_width
= mbswidth (blocks
, MBSWIDTH_FLAGS
);
4384 for (int pad
= blocks_width
< 0 ? 0 : block_size_width
- blocks_width
;
4387 while ((*p
++ = *blocks
++))
4392 /* The last byte of the mode string is the POSIX
4393 "optional alternate access method flag". */
4395 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4396 p
+= sprintf (p
, "%s %*s ", modebuf
, nlink_width
,
4397 ! f
->stat_ok
? "?" : umaxtostr (f
->stat
.st_nlink
, hbuf
));
4402 if (print_owner
|| print_group
|| print_author
|| print_scontext
)
4404 dired_outbuf (buf
, p
- buf
);
4407 format_user (f
->stat
.st_uid
, owner_width
, f
->stat_ok
);
4410 format_group (f
->stat
.st_gid
, group_width
, f
->stat_ok
);
4413 format_user (f
->stat
.st_author
, author_width
, f
->stat_ok
);
4416 format_user_or_group (f
->scontext
, 0, scontext_width
);
4422 && (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
)))
4424 char majorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4425 char minorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4426 int blanks_width
= (file_size_width
4427 - (major_device_number_width
+ 2
4428 + minor_device_number_width
));
4429 p
+= sprintf (p
, "%*s, %*s ",
4430 major_device_number_width
+ MAX (0, blanks_width
),
4431 umaxtostr (major (f
->stat
.st_rdev
), majorbuf
),
4432 minor_device_number_width
,
4433 umaxtostr (minor (f
->stat
.st_rdev
), minorbuf
));
4437 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
4441 : human_readable (unsigned_file_size (f
->stat
.st_size
),
4442 hbuf
, file_human_output_opts
, 1,
4443 file_output_block_size
));
4444 int size_width
= mbswidth (size
, MBSWIDTH_FLAGS
);
4445 for (int pad
= size_width
< 0 ? 0 : block_size_width
- size_width
;
4448 while ((*p
++ = *size
++))
4456 if (f
->stat_ok
&& btime_ok
4457 && localtime_rz (localtz
, &when_timespec
.tv_sec
, &when_local
))
4459 struct timespec six_months_ago
;
4462 /* If the file appears to be in the future, update the current
4463 time, in case the file happens to have been modified since
4464 the last time we checked the clock. */
4465 if (timespec_cmp (current_time
, when_timespec
) < 0)
4466 gettime (¤t_time
);
4468 /* Consider a time to be recent if it is within the past six months.
4469 A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952 seconds
4470 on the average. Write this value as an integer constant to
4471 avoid floating point hassles. */
4472 six_months_ago
.tv_sec
= current_time
.tv_sec
- 31556952 / 2;
4473 six_months_ago
.tv_nsec
= current_time
.tv_nsec
;
4475 recent
= (timespec_cmp (six_months_ago
, when_timespec
) < 0
4476 && timespec_cmp (when_timespec
, current_time
) < 0);
4478 /* We assume here that all time zones are offset from UTC by a
4479 whole number of seconds. */
4480 s
= align_nstrftime (p
, TIME_STAMP_LEN_MAXIMUM
+ 1, recent
,
4481 &when_local
, localtz
, when_timespec
.tv_nsec
);
4491 /* The time cannot be converted using the desired format, so
4492 print it as a huge integer number of seconds. */
4493 char hbuf
[INT_BUFSIZE_BOUND (intmax_t)];
4494 p
+= sprintf (p
, "%*s ", long_time_expected_width (),
4495 (! f
->stat_ok
|| ! btime_ok
4497 : timetostr (when_timespec
.tv_sec
, hbuf
)));
4498 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
4501 dired_outbuf (buf
, p
- buf
);
4502 size_t w
= print_name_with_quoting (f
, false, &dired_obstack
, p
- buf
);
4504 if (f
->filetype
== symbolic_link
)
4508 dired_outstring (" -> ");
4509 print_name_with_quoting (f
, true, nullptr, (p
- buf
) + w
+ 4);
4510 if (indicator_style
!= none
)
4511 print_type_indicator (true, f
->linkmode
, unknown
);
4514 else if (indicator_style
!= none
)
4515 print_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
4518 /* Write to *BUF a quoted representation of the file name NAME, if non-null,
4519 using OPTIONS to control quoting. *BUF is set to NAME if no quoting
4520 is required. *BUF is allocated if more space required (and the original
4521 *BUF is not deallocated).
4522 Store the number of screen columns occupied by NAME's quoted
4523 representation into WIDTH, if non-null.
4524 Store into PAD whether an initial space is needed for padding.
4525 Return the number of bytes in *BUF. */
4528 quote_name_buf (char **inbuf
, size_t bufsize
, char *name
,
4529 struct quoting_options
const *options
,
4530 int needs_general_quoting
, size_t *width
, bool *pad
)
4533 size_t displayed_width
IF_LINT ( = 0);
4537 enum quoting_style qs
= get_quoting_style (options
);
4538 bool needs_further_quoting
= qmark_funny_chars
4539 && (qs
== shell_quoting_style
4540 || qs
== shell_always_quoting_style
4541 || qs
== literal_quoting_style
);
4543 if (needs_general_quoting
!= 0)
4545 len
= quotearg_buffer (buf
, bufsize
, name
, -1, options
);
4548 buf
= xmalloc (len
+ 1);
4549 quotearg_buffer (buf
, len
+ 1, name
, -1, options
);
4552 quoted
= (*name
!= *buf
) || strlen (name
) != len
;
4554 else if (needs_further_quoting
)
4556 len
= strlen (name
);
4558 buf
= xmalloc (len
+ 1);
4559 memcpy (buf
, name
, len
+ 1);
4565 len
= strlen (name
);
4570 if (needs_further_quoting
)
4574 char const *p
= buf
;
4575 char const *plimit
= buf
+ len
;
4577 displayed_width
= 0;
4582 case ' ': case '!': case '"': case '#': case '%':
4583 case '&': case '\'': case '(': case ')': case '*':
4584 case '+': case ',': case '-': case '.': case '/':
4585 case '0': case '1': case '2': case '3': case '4':
4586 case '5': case '6': case '7': case '8': case '9':
4587 case ':': case ';': case '<': case '=': case '>':
4589 case 'A': case 'B': case 'C': case 'D': case 'E':
4590 case 'F': case 'G': case 'H': case 'I': case 'J':
4591 case 'K': case 'L': case 'M': case 'N': case 'O':
4592 case 'P': case 'Q': case 'R': case 'S': case 'T':
4593 case 'U': case 'V': case 'W': case 'X': case 'Y':
4595 case '[': case '\\': case ']': case '^': case '_':
4596 case 'a': case 'b': case 'c': case 'd': case 'e':
4597 case 'f': case 'g': case 'h': case 'i': case 'j':
4598 case 'k': case 'l': case 'm': case 'n': case 'o':
4599 case 'p': case 'q': case 'r': case 's': case 't':
4600 case 'u': case 'v': case 'w': case 'x': case 'y':
4601 case 'z': case '{': case '|': case '}': case '~':
4602 /* These characters are printable ASCII characters. */
4604 displayed_width
+= 1;
4607 /* If we have a multibyte sequence, copy it until we
4608 reach its end, replacing each non-printable multibyte
4609 character with a single question mark. */
4611 mbstate_t mbstate
= {0};
4618 bytes
= mbrtowc (&wc
, p
, plimit
- p
, &mbstate
);
4620 if (bytes
== (size_t) -1)
4622 /* An invalid multibyte sequence was
4623 encountered. Skip one input byte, and
4624 put a question mark. */
4627 displayed_width
+= 1;
4631 if (bytes
== (size_t) -2)
4633 /* An incomplete multibyte character
4634 at the end. Replace it entirely with
4638 displayed_width
+= 1;
4643 /* A null wide character was encountered. */
4649 /* A printable multibyte character.
4651 for (; bytes
> 0; --bytes
)
4653 displayed_width
+= w
;
4657 /* An nonprintable multibyte character.
4658 Replace it entirely with a question
4662 displayed_width
+= 1;
4665 while (! mbsinit (&mbstate
));
4670 /* The buffer may have shrunk. */
4676 char const *plimit
= buf
+ len
;
4680 if (! isprint (to_uchar (*p
)))
4684 displayed_width
= len
;
4687 else if (width
!= nullptr)
4691 displayed_width
= mbsnwidth (buf
, len
, MBSWIDTH_FLAGS
);
4692 displayed_width
= MAX (0, displayed_width
);
4696 char const *p
= buf
;
4697 char const *plimit
= buf
+ len
;
4699 displayed_width
= 0;
4702 if (isprint (to_uchar (*p
)))
4709 /* Set padding to better align quoted items,
4710 and also give a visual indication that quotes are
4711 not actually part of the name. */
4712 *pad
= (align_variable_outer_quotes
&& cwd_some_quoted
&& ! quoted
);
4714 if (width
!= nullptr)
4715 *width
= displayed_width
;
4723 quote_name_width (char const *name
, struct quoting_options
const *options
,
4724 int needs_general_quoting
)
4726 char smallbuf
[BUFSIZ
];
4727 char *buf
= smallbuf
;
4731 quote_name_buf (&buf
, sizeof smallbuf
, (char *) name
, options
,
4732 needs_general_quoting
, &width
, &pad
);
4734 if (buf
!= smallbuf
&& buf
!= name
)
4742 /* %XX escape any input out of range as defined in RFC3986,
4743 and also if PATH, convert all path separators to '/'. */
4745 file_escape (char const *str
, bool path
)
4747 char *esc
= xnmalloc (3, strlen (str
) + 1);
4751 if (path
&& ISSLASH (*str
))
4756 else if (RFC3986
[to_uchar (*str
)])
4759 p
+= sprintf (p
, "%%%02x", to_uchar (*str
++));
4766 quote_name (char const *name
, struct quoting_options
const *options
,
4767 int needs_general_quoting
, const struct bin_str
*color
,
4768 bool allow_pad
, struct obstack
*stack
, char const *absolute_name
)
4770 char smallbuf
[BUFSIZ
];
4771 char *buf
= smallbuf
;
4775 len
= quote_name_buf (&buf
, sizeof smallbuf
, (char *) name
, options
,
4776 needs_general_quoting
, nullptr, &pad
);
4778 if (pad
&& allow_pad
)
4779 dired_outbyte (' ');
4782 print_color_indicator (color
);
4784 /* If we're padding, then don't include the outer quotes in
4785 the --hyperlink, to improve the alignment of those links. */
4786 bool skip_quotes
= false;
4790 if (align_variable_outer_quotes
&& cwd_some_quoted
&& ! pad
)
4795 char *h
= file_escape (hostname
, /* path= */ false);
4796 char *n
= file_escape (absolute_name
, /* path= */ true);
4797 /* TODO: It would be good to be able to define parameters
4798 to give hints to the terminal as how best to render the URI.
4799 For example since ls is outputting a dense block of URIs
4800 it would be best to not underline by default, and only
4801 do so upon hover etc. */
4802 printf ("\033]8;;file://%s%s%s\a", h
, *n
== '/' ? "" : "/", n
);
4808 push_current_dired_pos (stack
);
4810 fwrite (buf
+ skip_quotes
, 1, len
- (skip_quotes
* 2), stdout
);
4815 push_current_dired_pos (stack
);
4819 fputs ("\033]8;;\a", stdout
);
4821 putchar (*(buf
+ len
- 1));
4824 if (buf
!= smallbuf
&& buf
!= name
)
4831 print_name_with_quoting (const struct fileinfo
*f
,
4832 bool symlink_target
,
4833 struct obstack
*stack
,
4836 char const *name
= symlink_target
? f
->linkname
: f
->name
;
4838 const struct bin_str
*color
4839 = print_with_color
? get_color_indicator (f
, symlink_target
) : nullptr;
4841 bool used_color_this_time
= (print_with_color
4842 && (color
|| is_colored (C_NORM
)));
4844 size_t len
= quote_name (name
, filename_quoting_options
, f
->quoted
,
4845 color
, !symlink_target
, stack
, f
->absolute_name
);
4848 if (used_color_this_time
)
4850 prep_non_filename_text ();
4852 /* We use the byte length rather than display width here as
4853 an optimization to avoid accurately calculating the width,
4854 because we only output the clear to EOL sequence if the name
4855 _might_ wrap to the next line. This may output a sequence
4856 unnecessarily in multi-byte locales for example,
4857 but in that case it's inconsequential to the output. */
4859 && (start_col
/ line_length
!= (start_col
+ len
- 1) / line_length
))
4860 put_indicator (&color_indicator
[C_CLR_TO_EOL
]);
4867 prep_non_filename_text (void)
4869 if (color_indicator
[C_END
].string
!= nullptr)
4870 put_indicator (&color_indicator
[C_END
]);
4873 put_indicator (&color_indicator
[C_LEFT
]);
4874 put_indicator (&color_indicator
[C_RESET
]);
4875 put_indicator (&color_indicator
[C_RIGHT
]);
4879 /* Print the file name of 'f' with appropriate quoting.
4880 Also print file size, inode number, and filetype indicator character,
4881 as requested by switches. */
4884 print_file_name_and_frills (const struct fileinfo
*f
, size_t start_col
)
4886 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
4888 set_normal_color ();
4891 printf ("%*s ", format
== with_commas
? 0 : inode_number_width
,
4892 format_inode (buf
, f
));
4894 if (print_block_size
)
4895 printf ("%*s ", format
== with_commas
? 0 : block_size_width
,
4897 : human_readable (ST_NBLOCKS (f
->stat
), buf
, human_output_opts
,
4898 ST_NBLOCKSIZE
, output_block_size
));
4901 printf ("%*s ", format
== with_commas
? 0 : scontext_width
, f
->scontext
);
4903 size_t width
= print_name_with_quoting (f
, false, nullptr, start_col
);
4905 if (indicator_style
!= none
)
4906 width
+= print_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
4911 /* Given these arguments describing a file, return the single-byte
4912 type indicator, or 0. */
4914 get_type_indicator (bool stat_ok
, mode_t mode
, enum filetype type
)
4918 if (stat_ok
? S_ISREG (mode
) : type
== normal
)
4920 if (stat_ok
&& indicator_style
== classify
&& (mode
& S_IXUGO
))
4927 if (stat_ok
? S_ISDIR (mode
) : type
== directory
|| type
== arg_directory
)
4929 else if (indicator_style
== slash
)
4931 else if (stat_ok
? S_ISLNK (mode
) : type
== symbolic_link
)
4933 else if (stat_ok
? S_ISFIFO (mode
) : type
== fifo
)
4935 else if (stat_ok
? S_ISSOCK (mode
) : type
== sock
)
4937 else if (stat_ok
&& S_ISDOOR (mode
))
4946 print_type_indicator (bool stat_ok
, mode_t mode
, enum filetype type
)
4948 char c
= get_type_indicator (stat_ok
, mode
, type
);
4954 /* Returns if color sequence was printed. */
4956 print_color_indicator (const struct bin_str
*ind
)
4960 /* Need to reset so not dealing with attribute combinations */
4961 if (is_colored (C_NORM
))
4962 restore_default_color ();
4963 put_indicator (&color_indicator
[C_LEFT
]);
4964 put_indicator (ind
);
4965 put_indicator (&color_indicator
[C_RIGHT
]);
4968 return ind
!= nullptr;
4971 /* Returns color indicator or nullptr if none. */
4973 static const struct bin_str
*
4974 get_color_indicator (const struct fileinfo
*f
, bool symlink_target
)
4976 enum indicator_no type
;
4977 struct color_ext_type
*ext
; /* Color extension */
4978 size_t len
; /* Length of name */
4987 linkok
= f
->linkok
? 0 : -1;
4992 mode
= file_or_link_mode (f
);
4996 /* Is this a nonexistent file? If so, linkok == -1. */
4998 if (linkok
== -1 && is_colored (C_MISSING
))
5000 else if (!f
->stat_ok
)
5002 static enum indicator_no filetype_indicator
[] = FILETYPE_INDICATORS
;
5003 type
= filetype_indicator
[f
->filetype
];
5011 if ((mode
& S_ISUID
) != 0 && is_colored (C_SETUID
))
5013 else if ((mode
& S_ISGID
) != 0 && is_colored (C_SETGID
))
5015 else if (is_colored (C_CAP
) && f
->has_capability
)
5017 else if ((mode
& S_IXUGO
) != 0 && is_colored (C_EXEC
))
5019 else if ((1 < f
->stat
.st_nlink
) && is_colored (C_MULTIHARDLINK
))
5020 type
= C_MULTIHARDLINK
;
5022 else if (S_ISDIR (mode
))
5026 if ((mode
& S_ISVTX
) && (mode
& S_IWOTH
)
5027 && is_colored (C_STICKY_OTHER_WRITABLE
))
5028 type
= C_STICKY_OTHER_WRITABLE
;
5029 else if ((mode
& S_IWOTH
) != 0 && is_colored (C_OTHER_WRITABLE
))
5030 type
= C_OTHER_WRITABLE
;
5031 else if ((mode
& S_ISVTX
) != 0 && is_colored (C_STICKY
))
5034 else if (S_ISLNK (mode
))
5036 else if (S_ISFIFO (mode
))
5038 else if (S_ISSOCK (mode
))
5040 else if (S_ISBLK (mode
))
5042 else if (S_ISCHR (mode
))
5044 else if (S_ISDOOR (mode
))
5048 /* Classify a file of some other type as C_ORPHAN. */
5053 /* Check the file's suffix only if still classified as C_FILE. */
5057 /* Test if NAME has a recognized suffix. */
5059 len
= strlen (name
);
5060 name
+= len
; /* Pointer to final \0. */
5061 for (ext
= color_ext_list
; ext
!= nullptr; ext
= ext
->next
)
5063 if (ext
->ext
.len
<= len
)
5065 if (ext
->exact_match
)
5067 if (STREQ_LEN (name
- ext
->ext
.len
, ext
->ext
.string
,
5073 if (c_strncasecmp (name
- ext
->ext
.len
, ext
->ext
.string
,
5081 /* Adjust the color for orphaned symlinks. */
5082 if (type
== C_LINK
&& !linkok
)
5084 if (color_symlink_as_referent
|| is_colored (C_ORPHAN
))
5088 const struct bin_str
*const s
5089 = ext
? &(ext
->seq
) : &color_indicator
[type
];
5091 return s
->string
? s
: nullptr;
5094 /* Output a color indicator (which may contain nulls). */
5096 put_indicator (const struct bin_str
*ind
)
5102 /* If the standard output is a controlling terminal, watch out
5103 for signals, so that the colors can be restored to the
5104 default state if "ls" is suspended or interrupted. */
5106 if (0 <= tcgetpgrp (STDOUT_FILENO
))
5109 prep_non_filename_text ();
5112 fwrite (ind
->string
, ind
->len
, 1, stdout
);
5116 length_of_file_name_and_frills (const struct fileinfo
*f
)
5119 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
5122 len
+= 1 + (format
== with_commas
5123 ? strlen (umaxtostr (f
->stat
.st_ino
, buf
))
5124 : inode_number_width
);
5126 if (print_block_size
)
5127 len
+= 1 + (format
== with_commas
5128 ? strlen (! f
->stat_ok
? "?"
5129 : human_readable (ST_NBLOCKS (f
->stat
), buf
,
5130 human_output_opts
, ST_NBLOCKSIZE
,
5132 : block_size_width
);
5135 len
+= 1 + (format
== with_commas
? strlen (f
->scontext
) : scontext_width
);
5137 len
+= fileinfo_name_width (f
);
5139 if (indicator_style
!= none
)
5141 char c
= get_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
5149 print_many_per_line (void)
5151 size_t row
; /* Current row. */
5152 size_t cols
= calculate_columns (true);
5153 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
5155 /* Calculate the number of rows that will be in each column except possibly
5156 for a short column on the right. */
5157 size_t rows
= cwd_n_used
/ cols
+ (cwd_n_used
% cols
!= 0);
5159 for (row
= 0; row
< rows
; row
++)
5162 size_t filesno
= row
;
5165 /* Print the next row. */
5168 struct fileinfo
const *f
= sorted_file
[filesno
];
5169 size_t name_length
= length_of_file_name_and_frills (f
);
5170 size_t max_name_length
= line_fmt
->col_arr
[col
++];
5171 print_file_name_and_frills (f
, pos
);
5174 if (filesno
>= cwd_n_used
)
5177 indent (pos
+ name_length
, pos
+ max_name_length
);
5178 pos
+= max_name_length
;
5185 print_horizontal (void)
5189 size_t cols
= calculate_columns (false);
5190 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
5191 struct fileinfo
const *f
= sorted_file
[0];
5192 size_t name_length
= length_of_file_name_and_frills (f
);
5193 size_t max_name_length
= line_fmt
->col_arr
[0];
5195 /* Print first entry. */
5196 print_file_name_and_frills (f
, 0);
5199 for (filesno
= 1; filesno
< cwd_n_used
; ++filesno
)
5201 size_t col
= filesno
% cols
;
5210 indent (pos
+ name_length
, pos
+ max_name_length
);
5211 pos
+= max_name_length
;
5214 f
= sorted_file
[filesno
];
5215 print_file_name_and_frills (f
, pos
);
5217 name_length
= length_of_file_name_and_frills (f
);
5218 max_name_length
= line_fmt
->col_arr
[col
];
5223 /* Output name + SEP + ' '. */
5226 print_with_separator (char sep
)
5231 for (filesno
= 0; filesno
< cwd_n_used
; filesno
++)
5233 struct fileinfo
const *f
= sorted_file
[filesno
];
5234 size_t len
= line_length
? length_of_file_name_and_frills (f
) : 0;
5241 || ((pos
+ len
+ 2 < line_length
)
5242 && (pos
<= SIZE_MAX
- len
- 2)))
5250 separator
= eolbyte
;
5254 putchar (separator
);
5257 print_file_name_and_frills (f
, pos
);
5263 /* Assuming cursor is at position FROM, indent up to position TO.
5264 Use a TAB character instead of two or more spaces whenever possible. */
5267 indent (size_t from
, size_t to
)
5271 if (tabsize
!= 0 && to
/ tabsize
> (from
+ 1) / tabsize
)
5274 from
+= tabsize
- from
% tabsize
;
5284 /* Put DIRNAME/NAME into DEST, handling '.' and '/' properly. */
5285 /* FIXME: maybe remove this function someday. See about using a
5286 non-malloc'ing version of file_name_concat. */
5289 attach (char *dest
, char const *dirname
, char const *name
)
5291 char const *dirnamep
= dirname
;
5293 /* Copy dirname if it is not ".". */
5294 if (dirname
[0] != '.' || dirname
[1] != 0)
5297 *dest
++ = *dirnamep
++;
5298 /* Add '/' if 'dirname' doesn't already end with it. */
5299 if (dirnamep
> dirname
&& dirnamep
[-1] != '/')
5307 /* Allocate enough column info suitable for the current number of
5308 files and display columns, and initialize the info to represent the
5309 narrowest possible columns. */
5312 init_column_info (size_t max_cols
)
5316 /* Currently allocated columns in column_info. */
5317 static size_t column_info_alloc
;
5319 if (column_info_alloc
< max_cols
)
5321 size_t new_column_info_alloc
;
5324 if (!max_idx
|| max_cols
< max_idx
/ 2)
5326 /* The number of columns is far less than the display width
5327 allows. Grow the allocation, but only so that it's
5328 double the current requirements. If the display is
5329 extremely wide, this avoids allocating a lot of memory
5330 that is never needed. */
5331 column_info
= xnrealloc (column_info
, max_cols
,
5332 2 * sizeof *column_info
);
5333 new_column_info_alloc
= 2 * max_cols
;
5337 column_info
= xnrealloc (column_info
, max_idx
, sizeof *column_info
);
5338 new_column_info_alloc
= max_idx
;
5341 /* Allocate the new size_t objects by computing the triangle
5342 formula n * (n + 1) / 2, except that we don't need to
5343 allocate the part of the triangle that we've already
5344 allocated. Check for address arithmetic overflow. */
5346 size_t column_info_growth
= new_column_info_alloc
- column_info_alloc
;
5347 size_t s
= column_info_alloc
+ 1 + new_column_info_alloc
;
5348 size_t t
= s
* column_info_growth
;
5349 if (s
< new_column_info_alloc
|| t
/ column_info_growth
!= s
)
5351 p
= xnmalloc (t
/ 2, sizeof *p
);
5354 /* Grow the triangle by parceling out the cells just allocated. */
5355 for (i
= column_info_alloc
; i
< new_column_info_alloc
; i
++)
5357 column_info
[i
].col_arr
= p
;
5361 column_info_alloc
= new_column_info_alloc
;
5364 for (i
= 0; i
< max_cols
; ++i
)
5368 column_info
[i
].valid_len
= true;
5369 column_info
[i
].line_len
= (i
+ 1) * MIN_COLUMN_WIDTH
;
5370 for (j
= 0; j
<= i
; ++j
)
5371 column_info
[i
].col_arr
[j
] = MIN_COLUMN_WIDTH
;
5375 /* Calculate the number of columns needed to represent the current set
5376 of files in the current display width. */
5379 calculate_columns (bool by_columns
)
5381 size_t filesno
; /* Index into cwd_file. */
5382 size_t cols
; /* Number of files across. */
5384 /* Normally the maximum number of columns is determined by the
5385 screen width. But if few files are available this might limit it
5387 size_t max_cols
= 0 < max_idx
&& max_idx
< cwd_n_used
? max_idx
: cwd_n_used
;
5389 init_column_info (max_cols
);
5391 /* Compute the maximum number of possible columns. */
5392 for (filesno
= 0; filesno
< cwd_n_used
; ++filesno
)
5394 struct fileinfo
const *f
= sorted_file
[filesno
];
5395 size_t name_length
= length_of_file_name_and_frills (f
);
5397 for (size_t i
= 0; i
< max_cols
; ++i
)
5399 if (column_info
[i
].valid_len
)
5401 size_t idx
= (by_columns
5402 ? filesno
/ ((cwd_n_used
+ i
) / (i
+ 1))
5403 : filesno
% (i
+ 1));
5404 size_t real_length
= name_length
+ (idx
== i
? 0 : 2);
5406 if (column_info
[i
].col_arr
[idx
] < real_length
)
5408 column_info
[i
].line_len
+= (real_length
5409 - column_info
[i
].col_arr
[idx
]);
5410 column_info
[i
].col_arr
[idx
] = real_length
;
5411 column_info
[i
].valid_len
= (column_info
[i
].line_len
5418 /* Find maximum allowed columns. */
5419 for (cols
= max_cols
; 1 < cols
; --cols
)
5421 if (column_info
[cols
- 1].valid_len
)
5431 if (status
!= EXIT_SUCCESS
)
5435 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name
);
5437 List information about the FILEs (the current directory by default).\n\
5438 Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n\
5441 emit_mandatory_arg_note ();
5444 -a, --all do not ignore entries starting with .\n\
5445 -A, --almost-all do not list implied . and ..\n\
5446 --author with -l, print the author of each file\n\
5447 -b, --escape print C-style escapes for nongraphic characters\n\
5450 --block-size=SIZE with -l, scale sizes by SIZE when printing them;\n\
5451 e.g., '--block-size=M'; see SIZE format below\n\
5455 -B, --ignore-backups do not list implied entries ending with ~\n\
5458 -c with -lt: sort by, and show, ctime (time of last\n\
5459 change of file status information);\n\
5460 with -l: show ctime and sort by name;\n\
5461 otherwise: sort by ctime, newest first\n\
5465 -C list entries by columns\n\
5466 --color[=WHEN] color the output WHEN; more info below\n\
5467 -d, --directory list directories themselves, not their contents\n\
5468 -D, --dired generate output designed for Emacs' dired mode\n\
5471 -f list all entries in directory order\n\
5472 -F, --classify[=WHEN] append indicator (one of */=>@|) to entries WHEN\n\
5473 --file-type likewise, except do not append '*'\n\
5476 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
5477 single-column -1, verbose -l, vertical -C\n\
5481 --full-time like -l --time-style=full-iso\n\
5484 -g like -l, but do not list owner\n\
5487 --group-directories-first\n\
5488 group directories before files;\n\
5489 can be augmented with a --sort option, but any\n\
5490 use of --sort=none (-U) disables grouping\n\
5494 -G, --no-group in a long listing, don't print group names\n\
5497 -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc.\n\
5498 --si likewise, but use powers of 1000 not 1024\n\
5501 -H, --dereference-command-line\n\
5502 follow symbolic links listed on the command line\n\
5505 --dereference-command-line-symlink-to-dir\n\
5506 follow each command line symbolic link\n\
5507 that points to a directory\n\
5511 --hide=PATTERN do not list implied entries matching shell PATTERN\
5513 (overridden by -a or -A)\n\
5517 --hyperlink[=WHEN] hyperlink file names WHEN\n\
5520 --indicator-style=WORD\n\
5521 append indicator with style WORD to entry names:\n\
5522 none (default), slash (-p),\n\
5523 file-type (--file-type), classify (-F)\n\
5527 -i, --inode print the index number of each file\n\
5528 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\
5532 -k, --kibibytes default to 1024-byte blocks for file system usage;\
5534 used only with -s and per directory totals\n\
5538 -l use a long listing format\n\
5541 -L, --dereference when showing file information for a symbolic\n\
5542 link, show information for the file the link\n\
5543 references rather than for the link itself\n\
5547 -m fill width with a comma separated list of entries\
5551 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
5552 -N, --literal print entry names without quoting\n\
5553 -o like -l, but do not list group information\n\
5554 -p, --indicator-style=slash\n\
5555 append / indicator to directories\n\
5558 -q, --hide-control-chars print ? instead of nongraphic characters\n\
5561 --show-control-chars show nongraphic characters as-is (the default,\n\
5562 unless program is 'ls' and output is a terminal)\
5567 -Q, --quote-name enclose entry names in double quotes\n\
5570 --quoting-style=WORD use quoting style WORD for entry names:\n\
5571 literal, locale, shell, shell-always,\n\
5572 shell-escape, shell-escape-always, c, escape\n\
5573 (overrides QUOTING_STYLE environment variable)\n\
5577 -r, --reverse reverse order while sorting\n\
5578 -R, --recursive list subdirectories recursively\n\
5579 -s, --size print the allocated size of each file, in blocks\n\
5582 -S sort by file size, largest first\n\
5585 --sort=WORD sort by WORD instead of name: none (-U), size (-S)\
5587 time (-t), version (-v), extension (-X), width\n\
5591 --time=WORD select which timestamp used to display or sort;\n\
5592 access time (-u): atime, access, use;\n\
5593 metadata change time (-c): ctime, status;\n\
5594 modified time (default): mtime, modification;\n\
5595 birth time: birth, creation;\n\
5596 with -l, WORD determines which time to show;\n\
5597 with --sort=time, sort by WORD (newest first)\n\
5601 --time-style=TIME_STYLE\n\
5602 time/date format with -l; see TIME_STYLE below\n\
5605 -t sort by time, newest first; see --time\n\
5606 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
5609 -u with -lt: sort by, and show, access time;\n\
5610 with -l: show access time and sort by name;\n\
5611 otherwise: sort by access time, newest first\n\
5615 -U do not sort; list entries in directory order\n\
5618 -v natural sort of (version) numbers within text\n\
5621 -w, --width=COLS set output width to COLS. 0 means no limit\n\
5622 -x list entries by lines instead of by columns\n\
5623 -X sort alphabetically by entry extension\n\
5624 -Z, --context print any security context of each file\n\
5625 --zero end each output line with NUL, not newline\n\
5626 -1 list one file per line\n\
5628 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
5629 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
5633 The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT.\n\
5634 FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2,\n\
5635 then FORMAT1 applies to non-recent files and FORMAT2 to recent files.\n\
5636 TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale.\n\
5637 Also the TIME_STYLE environment variable sets the default style to use.\n\
5641 The WHEN argument defaults to 'always' and can also be 'auto' or 'never'.\n\
5645 Using color to distinguish file types is disabled both by default and\n\
5646 with --color=never. With --color=auto, ls emits color codes only when\n\
5647 standard output is connected to a terminal. The LS_COLORS environment\n\
5648 variable can change the settings. Use the dircolors(1) command to set it.\n\
5654 1 if minor problems (e.g., cannot access subdirectory),\n\
5655 2 if serious trouble (e.g., cannot access command-line argument).\n\
5657 emit_ancillary_info (PROGRAM_NAME
);