1 /* 'dir', 'vdir' and 'ls' directory listing programs for GNU.
2 Copyright (C) 1985-2024 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>. */
40 #include <sys/types.h>
46 #include <sys/ioctl.h>
48 #ifdef WINSIZE_IN_PTEM
49 # include <sys/stream.h>
50 # include <sys/ptem.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"
103 #include "stat-size.h"
104 #include "stat-time.h"
105 #include "strftime.h"
106 #include "xdectoint.h"
108 #include "xstrtol-error.h"
109 #include "areadlink.h"
110 #include "dircolors.h"
111 #include "xgethostname.h"
113 #include "canonicalize.h"
116 /* Include <sys/capability.h> last to avoid a clash of <sys/types.h>
117 include guards with some premature versions of libcap.
118 For more details, see <https://bugzilla.redhat.com/483548>. */
120 # include <sys/capability.h>
123 #if HAVE_LINUX_XATTR_H
124 # include <linux/xattr.h>
127 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
128 : (ls_mode == LS_MULTI_COL \
132 proper_name ("Richard M. Stallman"), \
133 proper_name ("David MacKenzie")
135 #define obstack_chunk_alloc malloc
136 #define obstack_chunk_free free
138 /* Unix-based readdir implementations have historically returned a dirent.d_ino
139 value that is sometimes not equal to the stat-obtained st_ino value for
140 that same entry. This error occurs for a readdir entry that refers
141 to a mount point. readdir's error is to return the inode number of
142 the underlying directory -- one that typically cannot be stat'ed, as
143 long as a file system is mounted on that directory. RELIABLE_D_INO
144 encapsulates whether we can use the more efficient approach of relying
145 on readdir-supplied d_ino values, or whether we must incur the cost of
146 calling stat or lstat to obtain each guaranteed-valid inode number. */
148 #ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
149 # define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
152 #if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
153 # define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
155 # define RELIABLE_D_INO(dp) D_INO (dp)
158 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
159 # define st_author st_uid
175 enum { filetype_cardinality
= arg_directory
+ 1 };
177 /* Display letters and indicators for each filetype.
178 Keep these in sync with enum filetype. */
179 static char const filetype_letter
[] =
180 {'?', 'p', 'c', 'd', 'b', '-', 'l', 's', 'w', 'd'};
181 static_assert (ARRAY_CARDINALITY (filetype_letter
) == filetype_cardinality
);
183 /* Map enum filetype to <dirent.h> d_type values. */
184 static unsigned char const filetype_d_type
[] =
186 DT_UNKNOWN
, DT_FIFO
, DT_CHR
, DT_DIR
, DT_BLK
, DT_REG
, DT_LNK
, DT_SOCK
,
189 static_assert (ARRAY_CARDINALITY (filetype_d_type
) == filetype_cardinality
);
191 /* Map d_type values to enum filetype. */
192 static char const d_type_filetype
[UCHAR_MAX
+ 1] =
194 [DT_BLK
] = blockdev
, [DT_CHR
] = chardev
, [DT_DIR
] = directory
,
195 [DT_FIFO
] = fifo
, [DT_LNK
] = symbolic_link
, [DT_REG
] = normal
,
196 [DT_SOCK
] = sock
, [DT_WHT
] = whiteout
202 ACL_T_LSM_CONTEXT_ONLY
,
211 /* For symbolic link, name of the file linked to, otherwise zero. */
214 /* For terminal hyperlinks. */
219 enum filetype filetype
;
221 /* For symbolic link and long listing, st_mode of file linked to, otherwise
225 /* security context. */
230 /* For symbolic link and color printing, true if linked-to file
231 exists, otherwise false. */
234 /* For long listings, true if the file has an access control list,
235 or a security context. */
236 enum acl_type acl_type
;
238 /* For color listings, true if a regular file has capability info. */
241 /* Whether file name needs quoting. tri-state with -1 == unknown. */
244 /* Cached screen width (including quoting). */
248 /* Null is a valid character in a color indicator (think about Epson
249 printers, for example) so we have to use a length/buffer string
254 size_t len
; /* Number of bytes */
255 char const *string
; /* Pointer to the same */
259 # define tcgetpgrp(Fd) 0
262 static size_t quote_name (char const *name
,
263 struct quoting_options
const *options
,
264 int needs_general_quoting
,
265 const struct bin_str
*color
,
266 bool allow_pad
, struct obstack
*stack
,
267 char const *absolute_name
);
268 static size_t quote_name_buf (char **inbuf
, size_t bufsize
, char *name
,
269 struct quoting_options
const *options
,
270 int needs_general_quoting
, size_t *width
,
272 static int decode_switches (int argc
, char **argv
);
273 static bool file_ignored (char const *name
);
274 static uintmax_t gobble_file (char const *name
, enum filetype type
,
275 ino_t inode
, bool command_line_arg
,
276 char const *dirname
);
277 static const struct bin_str
* get_color_indicator (const struct fileinfo
*f
,
278 bool symlink_target
);
279 static bool print_color_indicator (const struct bin_str
*ind
);
280 static void put_indicator (const struct bin_str
*ind
);
281 static void add_ignore_pattern (char const *pattern
);
282 static void attach (char *dest
, char const *dirname
, char const *name
);
283 static void clear_files (void);
284 static void extract_dirs_from_files (char const *dirname
,
285 bool command_line_arg
);
286 static void get_link_name (char const *filename
, struct fileinfo
*f
,
287 bool command_line_arg
);
288 static void indent (size_t from
, size_t to
);
289 static idx_t
calculate_columns (bool by_columns
);
290 static void print_current_files (void);
291 static void print_dir (char const *name
, char const *realname
,
292 bool command_line_arg
);
293 static size_t print_file_name_and_frills (const struct fileinfo
*f
,
295 static void print_horizontal (void);
296 static int format_user_width (uid_t u
);
297 static int format_group_width (gid_t g
);
298 static void print_long_format (const struct fileinfo
*f
);
299 static void print_many_per_line (void);
300 static size_t print_name_with_quoting (const struct fileinfo
*f
,
302 struct obstack
*stack
,
304 static void prep_non_filename_text (void);
305 static bool print_type_indicator (bool stat_ok
, mode_t mode
,
307 static void print_with_separator (char sep
);
308 static void queue_directory (char const *name
, char const *realname
,
309 bool command_line_arg
);
310 static void sort_files (void);
311 static void parse_ls_color (void);
313 static int getenv_quoting_style (void);
315 static size_t quote_name_width (char const *name
,
316 struct quoting_options
const *options
,
317 int needs_general_quoting
);
319 /* Initial size of hash table.
320 Most hierarchies are likely to be shallower than this. */
321 enum { INITIAL_TABLE_SIZE
= 30 };
323 /* The set of 'active' directories, from the current command-line argument
324 to the level in the hierarchy at which files are being listed.
325 A directory is represented by its device and inode numbers (struct dev_ino).
326 A directory is added to this set when ls begins listing it or its
327 entries, and it is removed from the set just after ls has finished
328 processing it. This set is used solely to detect loops, e.g., with
329 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
330 static Hash_table
*active_dir_set
;
332 #define LOOP_DETECT (!!active_dir_set)
334 /* The table of files in the current directory:
336 'cwd_file' points to a vector of 'struct fileinfo', one per file.
337 'cwd_n_alloc' is the number of elements space has been allocated for.
338 'cwd_n_used' is the number actually in use. */
340 /* Address of block containing the files that are described. */
341 static struct fileinfo
*cwd_file
;
343 /* Length of block that 'cwd_file' points to, measured in files. */
344 static idx_t cwd_n_alloc
;
346 /* Index of first unused slot in 'cwd_file'. */
347 static idx_t cwd_n_used
;
349 /* Whether files needs may need padding due to quoting. */
350 static bool cwd_some_quoted
;
352 /* Whether quoting style _may_ add outer quotes,
353 and whether aligning those is useful. */
354 static bool align_variable_outer_quotes
;
356 /* Vector of pointers to files, in proper sorted order, and the number
357 of entries allocated for it. */
358 static void **sorted_file
;
359 static size_t sorted_file_alloc
;
361 /* When true, in a color listing, color each symlink name according to the
362 type of file it points to. Otherwise, color them according to the 'ln'
363 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
364 regardless. This is set when 'ln=target' appears in LS_COLORS. */
366 static bool color_symlink_as_referent
;
368 static char const *hostname
;
370 /* Mode of appropriate file for coloring. */
372 file_or_link_mode (struct fileinfo
const *file
)
374 return (color_symlink_as_referent
&& file
->linkok
375 ? file
->linkmode
: file
->stat
.st_mode
);
379 /* Record of one pending directory waiting to be listed. */
384 /* If the directory is actually the file pointed to by a symbolic link we
385 were told to list, 'realname' will contain the name of the symbolic
386 link, otherwise zero. */
388 bool command_line_arg
;
389 struct pending
*next
;
392 static struct pending
*pending_dirs
;
394 /* Current time in seconds and nanoseconds since 1970, updated as
395 needed when deciding whether a file is recent. */
397 static struct timespec current_time
;
399 static bool print_scontext
;
400 static char UNKNOWN_SECURITY_CONTEXT
[] = "?";
402 /* Whether any of the files has an ACL. This affects the width of the
405 static bool any_has_acl
;
407 /* The number of columns to use for columns containing inode numbers,
408 block sizes, link counts, owners, groups, authors, major device
409 numbers, minor device numbers, and file sizes, respectively. */
411 static int inode_number_width
;
412 static int block_size_width
;
413 static int nlink_width
;
414 static int scontext_width
;
415 static int owner_width
;
416 static int group_width
;
417 static int author_width
;
418 static int major_device_number_width
;
419 static int minor_device_number_width
;
420 static int file_size_width
;
424 /* long_format for lots of info, one per line.
425 one_per_line for just names, one per line.
426 many_per_line for just names, many per line, sorted vertically.
427 horizontal for just names, many per line, sorted horizontally.
428 with_commas for just names, many per line, separated by commas.
430 -l (and other options that imply -l), -1, -C, -x and -m control
435 long_format
, /* -l and other options that imply -l */
436 one_per_line
, /* -1 */
437 many_per_line
, /* -C */
442 static enum format format
;
444 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
445 ISO-style timestamps, though shorter than 'full-iso'. 'iso' uses shorter
446 ISO-style timestamps. 'locale' uses locale-dependent timestamps. */
449 full_iso_time_style
, /* --time-style=full-iso */
450 long_iso_time_style
, /* --time-style=long-iso */
451 iso_time_style
, /* --time-style=iso */
452 locale_time_style
/* --time-style=locale */
455 static char const *const time_style_args
[] =
457 "full-iso", "long-iso", "iso", "locale", nullptr
459 static enum time_style
const time_style_types
[] =
461 full_iso_time_style
, long_iso_time_style
, iso_time_style
,
464 ARGMATCH_VERIFY (time_style_args
, time_style_types
);
466 /* Type of time to print or sort by. Controlled by -c and -u.
467 The values of each item of this enum are important since they are
468 used as indices in the sort functions array (see sort_files()). */
472 time_mtime
= 0, /* default */
475 time_btime
, /* birth time */
476 time_numtypes
/* the number of elements of this enum */
479 static enum time_type time_type
;
480 static bool explicit_time
;
482 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
483 The values of each item of this enum are important since they are
484 used as indices in the sort functions array (see sort_files()). */
488 sort_name
= 0, /* default */
489 sort_extension
, /* -X */
492 sort_version
, /* -v */
493 sort_time
, /* -t; must be second to last */
494 sort_none
, /* -U; must be last */
495 sort_numtypes
/* the number of elements of this enum */
498 static enum sort_type sort_type
;
500 /* Direction of sort.
501 false means highest first if numeric,
502 lowest first if alphabetic;
503 these are the defaults.
504 true means the opposite order in each case. -r */
506 static bool sort_reverse
;
508 /* True means to display owner information. -g turns this off. */
510 static bool print_owner
= true;
512 /* True means to display author information. */
514 static bool print_author
;
516 /* True means to display group information. -G and -o turn this off. */
518 static bool print_group
= true;
520 /* True means print the user and group id's as numbers rather
523 static bool numeric_ids
;
525 /* True means mention the size in blocks of each file. -s */
527 static bool print_block_size
;
529 /* Human-readable options for output, when printing block counts. */
530 static int human_output_opts
;
532 /* The units to use when printing block counts. */
533 static uintmax_t output_block_size
;
535 /* Likewise, but for file sizes. */
536 static int file_human_output_opts
;
537 static uintmax_t file_output_block_size
= 1;
539 /* Follow the output with a special string. Using this format,
540 Emacs' dired mode starts up twice as fast, and can handle all
541 strange characters in file names. */
544 /* 'none' means don't mention the type of files.
545 'slash' means mention directories only, with a '/'.
546 'file_type' means mention file types.
547 'classify' means mention file types and mark executables.
549 Controlled by -F, -p, and --indicator-style. */
553 none
= 0, /* --indicator-style=none (default) */
554 slash
, /* -p, --indicator-style=slash */
555 file_type
, /* --indicator-style=file-type */
556 classify
/* -F, --indicator-style=classify */
559 static enum indicator_style indicator_style
;
561 /* Names of indicator styles. */
562 static char const *const indicator_style_args
[] =
564 "none", "slash", "file-type", "classify", nullptr
566 static enum indicator_style
const indicator_style_types
[] =
568 none
, slash
, file_type
, classify
570 ARGMATCH_VERIFY (indicator_style_args
, indicator_style_types
);
572 /* True means use colors to mark types. Also define the different
573 colors as well as the stuff for the LS_COLORS environment variable.
574 The LS_COLORS variable is now in a termcap-like format. */
576 static bool print_with_color
;
578 static bool print_hyperlink
;
580 /* Whether we used any colors in the output so far. If so, we will
581 need to restore the default color later. If not, we will need to
582 call prep_non_filename_text before using color for the first time. */
584 static bool used_color
= false;
588 when_never
, /* 0: default or --color=never */
589 when_always
, /* 1: --color=always */
590 when_if_tty
/* 2: --color=tty */
593 enum Dereference_symlink
595 DEREF_UNDEFINED
= 0, /* default */
597 DEREF_COMMAND_LINE_ARGUMENTS
, /* -H */
598 DEREF_COMMAND_LINE_SYMLINK_TO_DIR
, /* the default, in certain cases */
599 DEREF_ALWAYS
/* -L */
604 C_LEFT
, C_RIGHT
, C_END
, C_RESET
, C_NORM
, C_FILE
, C_DIR
, C_LINK
,
606 C_BLK
, C_CHR
, C_MISSING
, C_ORPHAN
, C_EXEC
, C_DOOR
, C_SETUID
, C_SETGID
,
607 C_STICKY
, C_OTHER_WRITABLE
, C_STICKY_OTHER_WRITABLE
, C_CAP
, C_MULTIHARDLINK
,
611 static char const indicator_name
[][2]=
613 {'l','c'}, {'r','c'}, {'e','c'}, {'r','s'}, {'n','o'},
614 {'f','i'}, {'d','i'}, {'l','n'},
615 {'p','i'}, {'s','o'},
616 {'b','d'}, {'c','d'}, {'m','i'}, {'o','r'}, {'e','x'},
617 {'d','o'}, {'s','u'}, {'s','g'},
618 {'s','t'}, {'o','w'}, {'t','w'}, {'c','a'}, {'m','h'},
622 struct color_ext_type
624 struct bin_str ext
; /* The extension we're looking for */
625 struct bin_str seq
; /* The sequence to output when we do */
626 bool exact_match
; /* Whether to compare case insensitively */
627 struct color_ext_type
*next
; /* Next in list */
630 static struct bin_str color_indicator
[] =
632 { 2, (char const []) {'\033','['} },/* lc: Left of color sequence */
633 { 1, (char const []) {'m'} }, /* rc: Right of color sequence */
634 { 0, nullptr }, /* ec: End color (replaces lc+rs+rc) */
635 { 1, (char const []) {'0'} }, /* rs: Reset to ordinary colors */
636 { 0, nullptr }, /* no: Normal */
637 { 0, nullptr }, /* fi: File: default */
638 { 5, ((char const [])
639 {'0','1',';','3','4'}) }, /* di: Directory: bright blue */
640 { 5, ((char const [])
641 {'0','1',';','3','6'}) }, /* ln: Symlink: bright cyan */
642 { 2, (char const []) {'3','3'} }, /* pi: Pipe: yellow/brown */
643 { 5, ((char const [])
644 {'0','1',';','3','5'}) }, /* so: Socket: bright magenta */
645 { 5, ((char const [])
646 {'0','1',';','3','3'}) }, /* bd: Block device: bright yellow */
647 { 5, ((char const [])
648 {'0','1',';','3','3'}) }, /* cd: Char device: bright yellow */
649 { 0, nullptr }, /* mi: Missing file: undefined */
650 { 0, nullptr }, /* or: Orphaned symlink: undefined */
651 { 5, ((char const [])
652 {'0','1',';','3','2'}) }, /* ex: Executable: bright green */
653 { 5, ((char const [])
654 {'0','1',';','3','5'}) }, /* do: Door: bright magenta */
655 { 5, ((char const [])
656 {'3','7',';','4','1'}) }, /* su: setuid: white on red */
657 { 5, ((char const [])
658 {'3','0',';','4','3'}) }, /* sg: setgid: black on yellow */
659 { 5, ((char const [])
660 {'3','7',';','4','4'}) }, /* st: sticky: black on blue */
661 { 5, ((char const [])
662 {'3','4',';','4','2'}) }, /* ow: other-writable: blue on green */
663 { 5, ((char const [])
664 {'3','0',';','4','2'}) }, /* tw: ow w/ sticky: black on green */
665 { 0, nullptr }, /* ca: disabled by default */
666 { 0, nullptr }, /* mh: disabled by default */
667 { 3, ((char const [])
668 {'\033','[','K'}) }, /* cl: clear to end of line */
671 /* A list mapping file extensions to corresponding display sequence. */
672 static struct color_ext_type
*color_ext_list
= nullptr;
674 /* Buffer for color sequences */
675 static char *color_buf
;
677 /* True means to check for orphaned symbolic link, for displaying
678 colors, or to group symlink to directories with other dirs. */
680 static bool check_symlink_mode
;
682 /* True means mention the inode number of each file. -i */
684 static bool print_inode
;
686 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
687 other options that imply -l), and -L. */
689 static enum Dereference_symlink dereference
;
691 /* True means when a directory is found, display info on its
694 static bool recursive
;
696 /* True means when an argument is a directory name, display info
699 static bool immediate_dirs
;
701 /* True means that directories are grouped before files. */
703 static bool directories_first
;
705 /* Which files to ignore. */
709 /* Ignore files whose names start with '.', and files specified by
710 --hide and --ignore. */
713 /* Ignore '.', '..', and files specified by --ignore. */
714 IGNORE_DOT_AND_DOTDOT
,
716 /* Ignore only files specified by --ignore. */
720 /* A linked list of shell-style globbing patterns. If a non-argument
721 file name matches any of these patterns, it is ignored.
722 Controlled by -I. Multiple -I options accumulate.
723 The -B option adds '*~' and '.*~' to this list. */
725 struct ignore_pattern
728 struct ignore_pattern
*next
;
731 static struct ignore_pattern
*ignore_patterns
;
733 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
734 variable itself to be ignored. */
735 static struct ignore_pattern
*hide_patterns
;
737 /* True means output nongraphic chars in file names as '?'.
738 (-q, --hide-control-chars)
739 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
740 independent. The algorithm is: first, obey the quoting style to get a
741 string representing the file name; then, if qmark_funny_chars is set,
742 replace all nonprintable chars in that string with '?'. It's necessary
743 to replace nonprintable chars even in quoted strings, because we don't
744 want to mess up the terminal if control chars get sent to it, and some
745 quoting methods pass through control chars as-is. */
746 static bool qmark_funny_chars
;
748 /* Quoting options for file and dir name output. */
750 static struct quoting_options
*filename_quoting_options
;
751 static struct quoting_options
*dirname_quoting_options
;
753 /* The number of chars per hardware tab stop. Setting this to zero
754 inhibits the use of TAB characters for separating columns. -T */
755 static size_t tabsize
;
757 /* True means print each directory name before listing it. */
759 static bool print_dir_name
;
761 /* The line length to use for breaking lines in many-per-line format.
762 Can be set with -w. If zero, there is no limit. */
764 static size_t line_length
;
766 /* The local time zone rules, as per the TZ environment variable. */
768 static timezone_t localtz
;
770 /* If true, the file listing format requires that stat be called on
773 static bool format_needs_stat
;
775 /* Similar to 'format_needs_stat', but set if only the file type is
778 static bool format_needs_type
;
780 /* Like 'format_needs_stat', but set only if capability colors are needed. */
782 static bool format_needs_capability
;
784 /* An arbitrary limit on the number of bytes in a printed timestamp.
785 This is set to a relatively small value to avoid the need to worry
786 about denial-of-service attacks on servers that run "ls" on behalf
787 of remote clients. 1000 bytes should be enough for any practical
790 enum { TIME_STAMP_LEN_MAXIMUM
= MAX (1000, INT_STRLEN_BOUND (time_t)) };
792 /* strftime formats for non-recent and recent files, respectively, in
795 static char const *long_time_format
[2] =
797 /* strftime format for non-recent files (older than 6 months), in
798 -l output. This should contain the year, month and day (at
799 least), in an order that is understood by people in your
800 locale's territory. Please try to keep the number of used
801 screen columns small, because many people work in windows with
802 only 80 columns. But make this as wide as the other string
803 below, for recent files. */
804 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
805 so be wary of using variable width fields from the locale.
806 Note %b is handled specially by ls and aligned correctly.
807 Note also that specifying a width as in %5b is erroneous as strftime
808 will count bytes rather than characters in multibyte locales. */
810 /* strftime format for recent files (younger than 6 months), in -l
811 output. This should contain the month, day and time (at
812 least), in an order that is understood by people in your
813 locale's territory. Please try to keep the number of used
814 screen columns small, because many people work in windows with
815 only 80 columns. But make this as wide as the other string
816 above, for non-recent files. */
817 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
818 so be wary of using variable width fields from the locale.
819 Note %b is handled specially by ls and aligned correctly.
820 Note also that specifying a width as in %5b is erroneous as strftime
821 will count bytes rather than characters in multibyte locales. */
825 /* The set of signals that are caught. */
827 static sigset_t caught_signals
;
829 /* If nonzero, the value of the pending fatal signal. */
831 static sig_atomic_t volatile interrupt_signal
;
833 /* A count of the number of pending stop signals that have been received. */
835 static sig_atomic_t volatile stop_signal_count
;
837 /* Desired exit status. */
839 static int exit_status
;
844 /* "ls" had a minor problem. E.g., while processing a directory,
845 ls obtained the name of an entry via readdir, yet was later
846 unable to stat that name. This happens when listing a directory
847 in which entries are actively being removed or renamed. */
848 LS_MINOR_PROBLEM
= 1,
850 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
851 option or failure to stat a command line argument. */
855 /* For long options that have no equivalent short option, use a
856 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
859 AUTHOR_OPTION
= CHAR_MAX
+ 1,
862 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
,
863 FILE_TYPE_INDICATOR_OPTION
,
866 GROUP_DIRECTORIES_FIRST_OPTION
,
869 INDICATOR_STYLE_OPTION
,
870 QUOTING_STYLE_OPTION
,
871 SHOW_CONTROL_CHARS_OPTION
,
879 static struct option
const long_options
[] =
881 {"all", no_argument
, nullptr, 'a'},
882 {"escape", no_argument
, nullptr, 'b'},
883 {"directory", no_argument
, nullptr, 'd'},
884 {"dired", no_argument
, nullptr, 'D'},
885 {"full-time", no_argument
, nullptr, FULL_TIME_OPTION
},
886 {"group-directories-first", no_argument
, nullptr,
887 GROUP_DIRECTORIES_FIRST_OPTION
},
888 {"human-readable", no_argument
, nullptr, 'h'},
889 {"inode", no_argument
, nullptr, 'i'},
890 {"kibibytes", no_argument
, nullptr, 'k'},
891 {"numeric-uid-gid", no_argument
, nullptr, 'n'},
892 {"no-group", no_argument
, nullptr, 'G'},
893 {"hide-control-chars", no_argument
, nullptr, 'q'},
894 {"reverse", no_argument
, nullptr, 'r'},
895 {"size", no_argument
, nullptr, 's'},
896 {"width", required_argument
, nullptr, 'w'},
897 {"almost-all", no_argument
, nullptr, 'A'},
898 {"ignore-backups", no_argument
, nullptr, 'B'},
899 {"classify", optional_argument
, nullptr, 'F'},
900 {"file-type", no_argument
, nullptr, FILE_TYPE_INDICATOR_OPTION
},
901 {"si", no_argument
, nullptr, SI_OPTION
},
902 {"dereference-command-line", no_argument
, nullptr, 'H'},
903 {"dereference-command-line-symlink-to-dir", no_argument
, nullptr,
904 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
},
905 {"hide", required_argument
, nullptr, HIDE_OPTION
},
906 {"ignore", required_argument
, nullptr, 'I'},
907 {"indicator-style", required_argument
, nullptr, INDICATOR_STYLE_OPTION
},
908 {"dereference", no_argument
, nullptr, 'L'},
909 {"literal", no_argument
, nullptr, 'N'},
910 {"quote-name", no_argument
, nullptr, 'Q'},
911 {"quoting-style", required_argument
, nullptr, QUOTING_STYLE_OPTION
},
912 {"recursive", no_argument
, nullptr, 'R'},
913 {"format", required_argument
, nullptr, FORMAT_OPTION
},
914 {"show-control-chars", no_argument
, nullptr, SHOW_CONTROL_CHARS_OPTION
},
915 {"sort", required_argument
, nullptr, SORT_OPTION
},
916 {"tabsize", required_argument
, nullptr, 'T'},
917 {"time", required_argument
, nullptr, TIME_OPTION
},
918 {"time-style", required_argument
, nullptr, TIME_STYLE_OPTION
},
919 {"zero", no_argument
, nullptr, ZERO_OPTION
},
920 {"color", optional_argument
, nullptr, COLOR_OPTION
},
921 {"hyperlink", optional_argument
, nullptr, HYPERLINK_OPTION
},
922 {"block-size", required_argument
, nullptr, BLOCK_SIZE_OPTION
},
923 {"context", no_argument
, 0, 'Z'},
924 {"author", no_argument
, nullptr, AUTHOR_OPTION
},
925 {GETOPT_HELP_OPTION_DECL
},
926 {GETOPT_VERSION_OPTION_DECL
},
927 {nullptr, 0, nullptr, 0}
930 static char const *const format_args
[] =
932 "verbose", "long", "commas", "horizontal", "across",
933 "vertical", "single-column", nullptr
935 static enum format
const format_types
[] =
937 long_format
, long_format
, with_commas
, horizontal
, horizontal
,
938 many_per_line
, one_per_line
940 ARGMATCH_VERIFY (format_args
, format_types
);
942 static char const *const sort_args
[] =
944 "none", "size", "time", "version", "extension",
945 "name", "width", nullptr
947 static enum sort_type
const sort_types
[] =
949 sort_none
, sort_size
, sort_time
, sort_version
, sort_extension
,
950 sort_name
, sort_width
952 ARGMATCH_VERIFY (sort_args
, sort_types
);
954 static char const *const time_args
[] =
956 "atime", "access", "use",
958 "mtime", "modification",
962 static enum time_type
const time_types
[] =
964 time_atime
, time_atime
, time_atime
,
965 time_ctime
, time_ctime
,
966 time_mtime
, time_mtime
,
967 time_btime
, time_btime
,
969 ARGMATCH_VERIFY (time_args
, time_types
);
971 static char const *const when_args
[] =
973 /* force and none are for compatibility with another color-ls version */
974 "always", "yes", "force",
975 "never", "no", "none",
976 "auto", "tty", "if-tty", nullptr
978 static enum when_type
const when_types
[] =
980 when_always
, when_always
, when_always
,
981 when_never
, when_never
, when_never
,
982 when_if_tty
, when_if_tty
, when_if_tty
984 ARGMATCH_VERIFY (when_args
, when_types
);
986 /* Information about filling a column. */
994 /* Array with information about column fullness. */
995 static struct column_info
*column_info
;
997 /* Maximum number of columns ever possible for this display. */
998 static size_t max_idx
;
1000 /* The minimum width of a column is 3: 1 character for the name and 2
1001 for the separating white space. */
1002 enum { MIN_COLUMN_WIDTH
= 3 };
1005 /* This zero-based index is for the --dired option. It is incremented
1006 for each byte of output generated by this program so that the beginning
1007 and ending indices (in that output) of every file name can be recorded
1008 and later output themselves. */
1009 static off_t dired_pos
;
1012 dired_outbyte (char c
)
1018 /* Output the buffer S, of length S_LEN, and increment DIRED_POS by S_LEN. */
1020 dired_outbuf (char const *s
, size_t s_len
)
1023 fwrite (s
, sizeof *s
, s_len
, stdout
);
1026 /* Output the string S, and increment DIRED_POS by its length. */
1028 dired_outstring (char const *s
)
1030 dired_outbuf (s
, strlen (s
));
1037 dired_outstring (" ");
1040 /* With --dired, store pairs of beginning and ending indices of file names. */
1041 static struct obstack dired_obstack
;
1043 /* With --dired, store pairs of beginning and ending indices of any
1044 directory names that appear as headers (just before 'total' line)
1045 for lists of directory entries. Such directory names are seen when
1046 listing hierarchies using -R and when a directory is listed with at
1047 least one other command line argument. */
1048 static struct obstack subdired_obstack
;
1050 /* Save the current index on the specified obstack, OBS. */
1052 push_current_dired_pos (struct obstack
*obs
)
1055 obstack_grow (obs
, &dired_pos
, sizeof dired_pos
);
1058 /* With -R, this stack is used to help detect directory cycles.
1059 The device/inode pairs on this stack mirror the pairs in the
1060 active_dir_set hash table. */
1061 static struct obstack dev_ino_obstack
;
1063 /* Push a pair onto the device/inode stack. */
1065 dev_ino_push (dev_t dev
, ino_t ino
)
1069 int dev_ino_size
= sizeof *di
;
1070 obstack_blank (&dev_ino_obstack
, dev_ino_size
);
1071 vdi
= obstack_next_free (&dev_ino_obstack
);
1078 /* Pop a dev/ino struct off the global dev_ino_obstack
1079 and return that struct. */
1080 static struct dev_ino
1085 int dev_ino_size
= sizeof *di
;
1086 affirm (dev_ino_size
<= obstack_object_size (&dev_ino_obstack
));
1087 obstack_blank_fast (&dev_ino_obstack
, -dev_ino_size
);
1088 vdi
= obstack_next_free (&dev_ino_obstack
);
1094 assert_matching_dev_ino (char const *name
, struct dev_ino di
)
1096 MAYBE_UNUSED
struct stat sb
;
1097 assure (0 <= stat (name
, &sb
));
1098 assure (sb
.st_dev
== di
.st_dev
);
1099 assure (sb
.st_ino
== di
.st_ino
);
1102 static char eolbyte
= '\n';
1104 /* Write to standard output PREFIX, followed by the quoting style and
1105 a space-separated list of the integers stored in OS all on one line. */
1108 dired_dump_obstack (char const *prefix
, struct obstack
*os
)
1112 n_pos
= obstack_object_size (os
) / sizeof (dired_pos
);
1115 off_t
*pos
= obstack_finish (os
);
1116 fputs (prefix
, stdout
);
1117 for (size_t i
= 0; i
< n_pos
; i
++)
1119 intmax_t p
= pos
[i
];
1126 /* Return the platform birthtime member of the stat structure,
1127 or fallback to the mtime member, which we have populated
1128 from the statx structure or reset to an invalid timestamp
1129 where birth time is not supported. */
1130 static struct timespec
1131 get_stat_btime (struct stat
const *st
)
1133 struct timespec btimespec
;
1135 #if HAVE_STATX && defined STATX_INO
1136 btimespec
= get_stat_mtime (st
);
1138 btimespec
= get_stat_birthtime (st
);
1144 #if HAVE_STATX && defined STATX_INO
1147 time_type_to_statx (void)
1167 calc_req_mask (void)
1169 unsigned int mask
= STATX_MODE
;
1174 if (print_block_size
)
1175 mask
|= STATX_BLOCKS
;
1177 if (format
== long_format
) {
1178 mask
|= STATX_NLINK
| STATX_SIZE
| time_type_to_statx ();
1179 if (print_owner
|| print_author
)
1190 case sort_extension
:
1194 mask
|= time_type_to_statx ();
1207 do_statx (int fd
, char const *name
, struct stat
*st
, int flags
,
1211 bool want_btime
= mask
& STATX_BTIME
;
1212 int ret
= statx (fd
, name
, flags
| AT_NO_AUTOMOUNT
, mask
, &stx
);
1215 statx_to_stat (&stx
, st
);
1216 /* Since we only need one timestamp type,
1217 store birth time in st_mtim. */
1220 if (stx
.stx_mask
& STATX_BTIME
)
1221 st
->st_mtim
= statx_timestamp_to_timespec (stx
.stx_btime
);
1223 st
->st_mtim
.tv_sec
= st
->st_mtim
.tv_nsec
= -1;
1231 do_stat (char const *name
, struct stat
*st
)
1233 return do_statx (AT_FDCWD
, name
, st
, 0, calc_req_mask ());
1237 do_lstat (char const *name
, struct stat
*st
)
1239 return do_statx (AT_FDCWD
, name
, st
, AT_SYMLINK_NOFOLLOW
, calc_req_mask ());
1243 stat_for_mode (char const *name
, struct stat
*st
)
1245 return do_statx (AT_FDCWD
, name
, st
, 0, STATX_MODE
);
1248 /* dev+ino should be static, so no need to sync with backing store */
1250 stat_for_ino (char const *name
, struct stat
*st
)
1252 return do_statx (AT_FDCWD
, name
, st
, 0, STATX_INO
);
1256 fstat_for_ino (int fd
, struct stat
*st
)
1258 return do_statx (fd
, "", st
, AT_EMPTY_PATH
, STATX_INO
);
1262 do_stat (char const *name
, struct stat
*st
)
1264 return stat (name
, st
);
1268 do_lstat (char const *name
, struct stat
*st
)
1270 return lstat (name
, st
);
1274 stat_for_mode (char const *name
, struct stat
*st
)
1276 return stat (name
, st
);
1280 stat_for_ino (char const *name
, struct stat
*st
)
1282 return stat (name
, st
);
1286 fstat_for_ino (int fd
, struct stat
*st
)
1288 return fstat (fd
, st
);
1292 /* Return the address of the first plain %b spec in FMT, or nullptr if
1293 there is no such spec. %5b etc. do not match, so that user
1294 widths/flags are honored. */
1298 first_percent_b (char const *fmt
)
1304 case 'b': return fmt
;
1305 case '%': fmt
++; break;
1310 static char RFC3986
[256];
1312 file_escape_init (void)
1314 for (int i
= 0; i
< 256; i
++)
1315 RFC3986
[i
] |= c_isalnum (i
) || i
== '~' || i
== '-' || i
== '.' || i
== '_';
1318 enum { MBSWIDTH_FLAGS
= MBSW_REJECT_INVALID
| MBSW_REJECT_UNPRINTABLE
};
1320 /* Read the abbreviated month names from the locale, to align them
1321 and to determine the max width of the field and to truncate names
1322 greater than our max allowed.
1323 Note even though this handles multibyte locales correctly
1324 it's not restricted to them as single byte locales can have
1325 variable width abbreviated months and also precomputing/caching
1326 the names was seen to increase the performance of ls significantly. */
1328 /* abformat[RECENT][MON] is the format to use for timestamps with
1329 recentness RECENT and month MON. */
1330 enum { ABFORMAT_SIZE
= 128 };
1331 static char abformat
[2][12][ABFORMAT_SIZE
];
1332 /* True if precomputed formats should be used. This can be false if
1333 nl_langinfo fails, if a format or month abbreviation is unusually
1334 long, or if a month abbreviation contains '%'. */
1335 static bool use_abformat
;
1337 /* Store into ABMON the abbreviated month names, suitably aligned.
1338 Return true if successful. */
1341 abmon_init (char abmon
[12][ABFORMAT_SIZE
])
1343 #ifndef HAVE_NL_LANGINFO
1346 int max_mon_width
= 0;
1350 for (int i
= 0; i
< 12; i
++)
1352 char const *abbr
= nl_langinfo (ABMON_1
+ i
);
1353 mon_len
[i
] = strnlen (abbr
, ABFORMAT_SIZE
);
1354 if (mon_len
[i
] == ABFORMAT_SIZE
)
1356 if (strchr (abbr
, '%'))
1358 mon_width
[i
] = mbswidth (strcpy (abmon
[i
], abbr
), MBSWIDTH_FLAGS
);
1359 if (mon_width
[i
] < 0)
1361 max_mon_width
= MAX (max_mon_width
, mon_width
[i
]);
1364 for (int i
= 0; i
< 12; i
++)
1366 int fill
= max_mon_width
- mon_width
[i
];
1367 if (ABFORMAT_SIZE
- mon_len
[i
] <= fill
)
1369 bool align_left
= !isdigit (to_uchar (abmon
[i
][0]));
1372 fill_offset
= mon_len
[i
];
1375 memmove (abmon
[i
] + fill
, abmon
[i
], mon_len
[i
]);
1378 memset (abmon
[i
] + fill_offset
, ' ', fill
);
1379 abmon
[i
][mon_len
[i
] + fill
] = '\0';
1386 /* Initialize ABFORMAT and USE_ABFORMAT. */
1389 abformat_init (void)
1392 for (int recent
= 0; recent
< 2; recent
++)
1393 pb
[recent
] = first_percent_b (long_time_format
[recent
]);
1394 if (! (pb
[0] || pb
[1]))
1397 char abmon
[12][ABFORMAT_SIZE
];
1398 if (! abmon_init (abmon
))
1401 for (int recent
= 0; recent
< 2; recent
++)
1403 char const *fmt
= long_time_format
[recent
];
1404 for (int i
= 0; i
< 12; i
++)
1406 char *nfmt
= abformat
[recent
][i
];
1410 nbytes
= snprintf (nfmt
, ABFORMAT_SIZE
, "%s", fmt
);
1413 if (! (pb
[recent
] - fmt
<= MIN (ABFORMAT_SIZE
, INT_MAX
)))
1415 int prefix_len
= pb
[recent
] - fmt
;
1416 nbytes
= snprintf (nfmt
, ABFORMAT_SIZE
, "%.*s%s%s",
1417 prefix_len
, fmt
, abmon
[i
], pb
[recent
] + 2);
1420 if (! (0 <= nbytes
&& nbytes
< ABFORMAT_SIZE
))
1425 use_abformat
= true;
1429 dev_ino_hash (void const *x
, size_t table_size
)
1431 struct dev_ino
const *p
= x
;
1432 return (uintmax_t) p
->st_ino
% table_size
;
1436 dev_ino_compare (void const *x
, void const *y
)
1438 struct dev_ino
const *a
= x
;
1439 struct dev_ino
const *b
= y
;
1440 return PSAME_INODE (a
, b
);
1444 dev_ino_free (void *x
)
1449 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1450 active directories. Return true if there is already a matching
1451 entry in the table. */
1454 visit_dir (dev_t dev
, ino_t ino
)
1456 struct dev_ino
*ent
;
1457 struct dev_ino
*ent_from_table
;
1460 ent
= xmalloc (sizeof *ent
);
1464 /* Attempt to insert this entry into the table. */
1465 ent_from_table
= hash_insert (active_dir_set
, ent
);
1467 if (ent_from_table
== nullptr)
1469 /* Insertion failed due to lack of memory. */
1473 found_match
= (ent_from_table
!= ent
);
1477 /* ent was not inserted, so free it. */
1485 free_pending_ent (struct pending
*p
)
1493 is_colored (enum indicator_no type
)
1495 /* Return true unless the string is "", "0" or "00"; try to be efficient. */
1496 size_t len
= color_indicator
[type
].len
;
1501 char const *s
= color_indicator
[type
].string
;
1502 return (s
[0] != '0') | (s
[len
- 1] != '0');
1506 restore_default_color (void)
1508 put_indicator (&color_indicator
[C_LEFT
]);
1509 put_indicator (&color_indicator
[C_RIGHT
]);
1513 set_normal_color (void)
1515 if (print_with_color
&& is_colored (C_NORM
))
1517 put_indicator (&color_indicator
[C_LEFT
]);
1518 put_indicator (&color_indicator
[C_NORM
]);
1519 put_indicator (&color_indicator
[C_RIGHT
]);
1523 /* An ordinary signal was received; arrange for the program to exit. */
1526 sighandler (int sig
)
1529 signal (sig
, SIG_IGN
);
1530 if (! interrupt_signal
)
1531 interrupt_signal
= sig
;
1534 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1537 stophandler (int sig
)
1540 signal (sig
, stophandler
);
1541 if (! interrupt_signal
)
1542 stop_signal_count
++;
1545 /* Process any pending signals. If signals are caught, this function
1546 should be called periodically. Ideally there should never be an
1547 unbounded amount of time when signals are not being processed.
1548 Signal handling can restore the default colors, so callers must
1549 immediately change colors after invoking this function. */
1552 process_signals (void)
1554 while (interrupt_signal
|| stop_signal_count
)
1561 restore_default_color ();
1564 sigprocmask (SIG_BLOCK
, &caught_signals
, &oldset
);
1566 /* Reload interrupt_signal and stop_signal_count, in case a new
1567 signal was handled before sigprocmask took effect. */
1568 sig
= interrupt_signal
;
1569 stops
= stop_signal_count
;
1571 /* SIGTSTP is special, since the application can receive that signal
1572 more than once. In this case, don't set the signal handler to the
1573 default. Instead, just raise the uncatchable SIGSTOP. */
1576 stop_signal_count
= stops
- 1;
1580 signal (sig
, SIG_DFL
);
1582 /* Exit or suspend the program. */
1584 sigprocmask (SIG_SETMASK
, &oldset
, nullptr);
1586 /* If execution reaches here, then the program has been
1587 continued (after being suspended). */
1591 /* Setup signal handlers if INIT is true,
1592 otherwise restore to the default. */
1595 signal_setup (bool init
)
1597 /* The signals that are trapped, and the number of such signals. */
1598 static int const sig
[] =
1600 /* This one is handled specially. */
1603 /* The usual suspects. */
1604 SIGALRM
, SIGHUP
, SIGINT
, SIGPIPE
, SIGQUIT
, SIGTERM
,
1621 enum { nsigs
= ARRAY_CARDINALITY (sig
) };
1624 static bool caught_sig
[nsigs
];
1632 struct sigaction act
;
1634 sigemptyset (&caught_signals
);
1635 for (j
= 0; j
< nsigs
; j
++)
1637 sigaction (sig
[j
], nullptr, &act
);
1638 if (act
.sa_handler
!= SIG_IGN
)
1639 sigaddset (&caught_signals
, sig
[j
]);
1642 act
.sa_mask
= caught_signals
;
1643 act
.sa_flags
= SA_RESTART
;
1645 for (j
= 0; j
< nsigs
; j
++)
1646 if (sigismember (&caught_signals
, sig
[j
]))
1648 act
.sa_handler
= sig
[j
] == SIGTSTP
? stophandler
: sighandler
;
1649 sigaction (sig
[j
], &act
, nullptr);
1652 for (j
= 0; j
< nsigs
; j
++)
1654 caught_sig
[j
] = (signal (sig
[j
], SIG_IGN
) != SIG_IGN
);
1657 signal (sig
[j
], sig
[j
] == SIGTSTP
? stophandler
: sighandler
);
1658 siginterrupt (sig
[j
], 0);
1666 for (j
= 0; j
< nsigs
; j
++)
1667 if (sigismember (&caught_signals
, sig
[j
]))
1668 signal (sig
[j
], SIG_DFL
);
1670 for (j
= 0; j
< nsigs
; j
++)
1672 signal (sig
[j
], SIG_DFL
);
1680 signal_setup (true);
1684 signal_restore (void)
1686 signal_setup (false);
1690 main (int argc
, char **argv
)
1693 struct pending
*thispend
;
1696 initialize_main (&argc
, &argv
);
1697 set_program_name (argv
[0]);
1698 setlocale (LC_ALL
, "");
1699 bindtextdomain (PACKAGE
, LOCALEDIR
);
1700 textdomain (PACKAGE
);
1702 initialize_exit_failure (LS_FAILURE
);
1703 atexit (close_stdout
);
1705 static_assert (ARRAY_CARDINALITY (color_indicator
)
1706 == ARRAY_CARDINALITY (indicator_name
));
1708 exit_status
= EXIT_SUCCESS
;
1709 print_dir_name
= true;
1710 pending_dirs
= nullptr;
1712 current_time
.tv_sec
= TYPE_MINIMUM (time_t);
1713 current_time
.tv_nsec
= -1;
1715 i
= decode_switches (argc
, argv
);
1717 if (print_with_color
)
1720 /* Test print_with_color again, because the call to parse_ls_color
1721 may have just reset it -- e.g., if LS_COLORS is invalid. */
1723 if (print_with_color
)
1725 /* Don't use TAB characters in output. Some terminal
1726 emulators can't handle the combination of tabs and
1727 color codes on the same line. */
1731 if (directories_first
)
1732 check_symlink_mode
= true;
1733 else if (print_with_color
)
1735 /* Avoid following symbolic links when possible. */
1736 if (is_colored (C_ORPHAN
)
1737 || (is_colored (C_EXEC
) && color_symlink_as_referent
)
1738 || (is_colored (C_MISSING
) && format
== long_format
))
1739 check_symlink_mode
= true;
1742 if (dereference
== DEREF_UNDEFINED
)
1743 dereference
= ((immediate_dirs
1744 || indicator_style
== classify
1745 || format
== long_format
)
1747 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR
);
1749 /* When using -R, initialize a data structure we'll use to
1750 detect any directory cycles. */
1753 active_dir_set
= hash_initialize (INITIAL_TABLE_SIZE
, nullptr,
1757 if (active_dir_set
== nullptr)
1760 obstack_init (&dev_ino_obstack
);
1763 localtz
= tzalloc (getenv ("TZ"));
1765 format_needs_stat
= ((sort_type
== sort_time
) | (sort_type
== sort_size
)
1766 | (format
== long_format
)
1767 | print_block_size
| print_hyperlink
);
1768 format_needs_type
= ((! format_needs_stat
)
1769 & (recursive
| print_with_color
| print_scontext
1771 | (indicator_style
!= none
)));
1772 format_needs_capability
= print_with_color
&& is_colored (C_CAP
);
1776 obstack_init (&dired_obstack
);
1777 obstack_init (&subdired_obstack
);
1780 if (print_hyperlink
)
1782 file_escape_init ();
1784 hostname
= xgethostname ();
1785 /* The hostname is generally ignored,
1786 so ignore failures obtaining it. */
1792 cwd_file
= xmalloc (cwd_n_alloc
* sizeof *cwd_file
);
1802 gobble_file (".", directory
, NOT_AN_INODE_NUMBER
, true, nullptr);
1804 queue_directory (".", nullptr, true);
1808 gobble_file (argv
[i
++], unknown
, NOT_AN_INODE_NUMBER
, true, nullptr);
1814 if (!immediate_dirs
)
1815 extract_dirs_from_files (nullptr, true);
1816 /* 'cwd_n_used' might be zero now. */
1819 /* In the following if/else blocks, it is sufficient to test 'pending_dirs'
1820 (and not pending_dirs->name) because there may be no markers in the queue
1821 at this point. A marker may be enqueued when extract_dirs_from_files is
1822 called with a non-empty string or via print_dir. */
1825 print_current_files ();
1827 dired_outbyte ('\n');
1829 else if (n_files
<= 1 && pending_dirs
&& pending_dirs
->next
== 0)
1830 print_dir_name
= false;
1832 while (pending_dirs
)
1834 thispend
= pending_dirs
;
1835 pending_dirs
= pending_dirs
->next
;
1839 if (thispend
->name
== nullptr)
1841 /* thispend->name == nullptr means this is a marker entry
1842 indicating we've finished processing the directory.
1843 Use its dev/ino numbers to remove the corresponding
1844 entry from the active_dir_set hash table. */
1845 struct dev_ino di
= dev_ino_pop ();
1846 struct dev_ino
*found
= hash_remove (active_dir_set
, &di
);
1848 assert_matching_dev_ino (thispend
->realname
, di
);
1850 dev_ino_free (found
);
1851 free_pending_ent (thispend
);
1856 print_dir (thispend
->name
, thispend
->realname
,
1857 thispend
->command_line_arg
);
1859 free_pending_ent (thispend
);
1860 print_dir_name
= true;
1863 if (print_with_color
&& used_color
)
1867 /* Skip the restore when it would be a no-op, i.e.,
1868 when left is "\033[" and right is "m". */
1869 if (!(color_indicator
[C_LEFT
].len
== 2
1870 && memcmp (color_indicator
[C_LEFT
].string
, "\033[", 2) == 0
1871 && color_indicator
[C_RIGHT
].len
== 1
1872 && color_indicator
[C_RIGHT
].string
[0] == 'm'))
1873 restore_default_color ();
1879 /* Act on any signals that arrived before the default was restored.
1880 This can process signals out of order, but there doesn't seem to
1881 be an easy way to do them in order, and the order isn't that
1882 important anyway. */
1883 for (j
= stop_signal_count
; j
; j
--)
1885 j
= interrupt_signal
;
1892 /* No need to free these since we're about to exit. */
1893 dired_dump_obstack ("//DIRED//", &dired_obstack
);
1894 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack
);
1895 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1896 quoting_style_args
[get_quoting_style (filename_quoting_options
)]);
1901 assure (hash_get_n_entries (active_dir_set
) == 0);
1902 hash_free (active_dir_set
);
1908 /* Return the line length indicated by the value given by SPEC, or -1
1909 if unsuccessful. 0 means no limit on line length. */
1912 decode_line_length (char const *spec
)
1916 /* Treat too-large values as if they were 0, which is
1917 effectively infinity. */
1918 switch (xstrtoumax (spec
, nullptr, 0, &val
, ""))
1921 return val
<= MIN (PTRDIFF_MAX
, SIZE_MAX
) ? val
: 0;
1923 case LONGINT_OVERFLOW
:
1931 /* Return true if standard output is a tty, caching the result. */
1934 stdout_isatty (void)
1936 static signed char out_tty
= -1;
1938 out_tty
= isatty (STDOUT_FILENO
);
1939 assume (out_tty
== 0 || out_tty
== 1);
1943 /* Set all the option flags according to the switches specified.
1944 Return the index of the first non-option argument. */
1947 decode_switches (int argc
, char **argv
)
1949 char const *time_style_option
= nullptr;
1951 /* These variables are false or -1 unless a switch says otherwise. */
1952 bool kibibytes_specified
= false;
1953 int format_opt
= -1;
1954 int hide_control_chars_opt
= -1;
1955 int quoting_style_opt
= -1;
1957 ptrdiff_t tabsize_opt
= -1;
1958 ptrdiff_t width_opt
= -1;
1963 int c
= getopt_long (argc
, argv
,
1964 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1972 ignore_mode
= IGNORE_MINIMAL
;
1976 quoting_style_opt
= escape_quoting_style
;
1980 time_type
= time_ctime
;
1981 explicit_time
= true;
1985 immediate_dirs
= true;
1989 ignore_mode
= IGNORE_MINIMAL
; /* enable -a */
1990 sort_opt
= sort_none
; /* enable -U */
1993 case FILE_TYPE_INDICATOR_OPTION
: /* --file-type */
1994 indicator_style
= file_type
;
1998 format_opt
= long_format
;
1999 print_owner
= false;
2003 file_human_output_opts
= human_output_opts
=
2004 human_autoscale
| human_SI
| human_base_1024
;
2005 file_output_block_size
= output_block_size
= 1;
2013 kibibytes_specified
= true;
2017 format_opt
= long_format
;
2021 format_opt
= with_commas
;
2026 format_opt
= long_format
;
2029 case 'o': /* Just like -l, but don't display group info. */
2030 format_opt
= long_format
;
2031 print_group
= false;
2035 indicator_style
= slash
;
2039 hide_control_chars_opt
= true;
2043 sort_reverse
= true;
2047 print_block_size
= true;
2051 sort_opt
= sort_time
;
2055 time_type
= time_atime
;
2056 explicit_time
= true;
2060 sort_opt
= sort_version
;
2064 width_opt
= decode_line_length (optarg
);
2066 error (LS_FAILURE
, 0, "%s: %s", _("invalid line width"),
2071 format_opt
= horizontal
;
2075 ignore_mode
= IGNORE_DOT_AND_DOTDOT
;
2079 add_ignore_pattern ("*~");
2080 add_ignore_pattern (".*~");
2084 format_opt
= many_per_line
;
2088 format_opt
= long_format
;
2089 print_hyperlink
= false;
2097 i
= XARGMATCH ("--classify", optarg
, when_args
, when_types
);
2099 /* Using --classify with no argument is equivalent to using
2100 --classify=always. */
2103 if (i
== when_always
|| (i
== when_if_tty
&& stdout_isatty ()))
2104 indicator_style
= classify
;
2108 case 'G': /* inhibit display of group info */
2109 print_group
= false;
2113 dereference
= DEREF_COMMAND_LINE_ARGUMENTS
;
2116 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
:
2117 dereference
= DEREF_COMMAND_LINE_SYMLINK_TO_DIR
;
2121 add_ignore_pattern (optarg
);
2125 dereference
= DEREF_ALWAYS
;
2129 quoting_style_opt
= literal_quoting_style
;
2133 quoting_style_opt
= c_quoting_style
;
2141 sort_opt
= sort_size
;
2145 tabsize_opt
= xnumtoumax (optarg
, 0, 0, MIN (PTRDIFF_MAX
, SIZE_MAX
),
2146 "", _("invalid tab size"), LS_FAILURE
, 0);
2150 sort_opt
= sort_none
;
2154 sort_opt
= sort_extension
;
2158 /* -1 has no effect after -l. */
2159 if (format_opt
!= long_format
)
2160 format_opt
= one_per_line
;
2164 print_author
= true;
2169 struct ignore_pattern
*hide
= xmalloc (sizeof *hide
);
2170 hide
->pattern
= optarg
;
2171 hide
->next
= hide_patterns
;
2172 hide_patterns
= hide
;
2177 sort_opt
= XARGMATCH ("--sort", optarg
, sort_args
, sort_types
);
2180 case GROUP_DIRECTORIES_FIRST_OPTION
:
2181 directories_first
= true;
2185 time_type
= XARGMATCH ("--time", optarg
, time_args
, time_types
);
2186 explicit_time
= true;
2190 format_opt
= XARGMATCH ("--format", optarg
, format_args
,
2194 case FULL_TIME_OPTION
:
2195 format_opt
= long_format
;
2196 time_style_option
= "full-iso";
2203 i
= XARGMATCH ("--color", optarg
, when_args
, when_types
);
2205 /* Using --color with no argument is equivalent to using
2209 print_with_color
= (i
== when_always
2210 || (i
== when_if_tty
&& stdout_isatty ()));
2214 case HYPERLINK_OPTION
:
2218 i
= XARGMATCH ("--hyperlink", optarg
, when_args
, when_types
);
2220 /* Using --hyperlink with no argument is equivalent to using
2221 --hyperlink=always. */
2224 print_hyperlink
= (i
== when_always
2225 || (i
== when_if_tty
&& stdout_isatty ()));
2229 case INDICATOR_STYLE_OPTION
:
2230 indicator_style
= XARGMATCH ("--indicator-style", optarg
,
2231 indicator_style_args
,
2232 indicator_style_types
);
2235 case QUOTING_STYLE_OPTION
:
2236 quoting_style_opt
= XARGMATCH ("--quoting-style", optarg
,
2238 quoting_style_vals
);
2241 case TIME_STYLE_OPTION
:
2242 time_style_option
= optarg
;
2245 case SHOW_CONTROL_CHARS_OPTION
:
2246 hide_control_chars_opt
= false;
2249 case BLOCK_SIZE_OPTION
:
2251 enum strtol_error e
= human_options (optarg
, &human_output_opts
,
2252 &output_block_size
);
2253 if (e
!= LONGINT_OK
)
2254 xstrtol_fatal (e
, oi
, 0, long_options
, optarg
);
2255 file_human_output_opts
= human_output_opts
;
2256 file_output_block_size
= output_block_size
;
2261 file_human_output_opts
= human_output_opts
=
2262 human_autoscale
| human_SI
;
2263 file_output_block_size
= output_block_size
= 1;
2267 print_scontext
= true;
2272 hide_control_chars_opt
= false;
2273 if (format_opt
!= long_format
)
2274 format_opt
= one_per_line
;
2275 print_with_color
= false;
2276 quoting_style_opt
= literal_quoting_style
;
2279 case_GETOPT_HELP_CHAR
;
2281 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
2288 if (! output_block_size
)
2290 char const *ls_block_size
= getenv ("LS_BLOCK_SIZE");
2291 human_options (ls_block_size
,
2292 &human_output_opts
, &output_block_size
);
2293 if (ls_block_size
|| getenv ("BLOCK_SIZE"))
2295 file_human_output_opts
= human_output_opts
;
2296 file_output_block_size
= output_block_size
;
2298 if (kibibytes_specified
)
2300 human_output_opts
= 0;
2301 output_block_size
= 1024;
2305 format
= (0 <= format_opt
? format_opt
2306 : ls_mode
== LS_LS
? (stdout_isatty ()
2307 ? many_per_line
: one_per_line
)
2308 : ls_mode
== LS_MULTI_COL
? many_per_line
2309 : /* ls_mode == LS_LONG_FORMAT */ long_format
);
2311 /* If the line length was not set by a switch but is needed to determine
2312 output, go to the work of obtaining it from the environment. */
2313 ptrdiff_t linelen
= width_opt
;
2314 if (format
== many_per_line
|| format
== horizontal
|| format
== with_commas
2315 || print_with_color
)
2321 if (stdout_isatty ()
2322 && 0 <= ioctl (STDOUT_FILENO
, TIOCGWINSZ
, &ws
)
2324 linelen
= ws
.ws_col
<= MIN (PTRDIFF_MAX
, SIZE_MAX
) ? ws
.ws_col
: 0;
2329 char const *p
= getenv ("COLUMNS");
2332 linelen
= decode_line_length (p
);
2335 _("ignoring invalid width"
2336 " in environment variable COLUMNS: %s"),
2342 line_length
= linelen
< 0 ? 80 : linelen
;
2344 /* Determine the max possible number of display columns. */
2345 max_idx
= line_length
/ MIN_COLUMN_WIDTH
;
2346 /* Account for first display column not having a separator,
2347 or line_lengths shorter than MIN_COLUMN_WIDTH. */
2348 max_idx
+= line_length
% MIN_COLUMN_WIDTH
!= 0;
2350 if (format
== many_per_line
|| format
== horizontal
|| format
== with_commas
)
2352 if (0 <= tabsize_opt
)
2353 tabsize
= tabsize_opt
;
2357 char const *p
= getenv ("TABSIZE");
2361 if (xstrtoumax (p
, nullptr, 0, &tmp
, "") == LONGINT_OK
2366 _("ignoring invalid tab size"
2367 " in environment variable TABSIZE: %s"),
2373 qmark_funny_chars
= (hide_control_chars_opt
< 0
2374 ? ls_mode
== LS_LS
&& stdout_isatty ()
2375 : hide_control_chars_opt
);
2377 int qs
= quoting_style_opt
;
2379 qs
= getenv_quoting_style ();
2381 qs
= (ls_mode
== LS_LS
2382 ? (stdout_isatty () ? shell_escape_quoting_style
: -1)
2383 : escape_quoting_style
);
2385 set_quoting_style (nullptr, qs
);
2386 qs
= get_quoting_style (nullptr);
2387 align_variable_outer_quotes
2388 = ((format
== long_format
2389 || ((format
== many_per_line
|| format
== horizontal
) && line_length
))
2390 && (qs
== shell_quoting_style
2391 || qs
== shell_escape_quoting_style
2392 || qs
== c_maybe_quoting_style
));
2393 filename_quoting_options
= clone_quoting_options (nullptr);
2394 if (qs
== escape_quoting_style
)
2395 set_char_quoting (filename_quoting_options
, ' ', 1);
2396 if (file_type
<= indicator_style
)
2399 for (p
= &"*=>@|"[indicator_style
- file_type
]; *p
; p
++)
2400 set_char_quoting (filename_quoting_options
, *p
, 1);
2403 dirname_quoting_options
= clone_quoting_options (nullptr);
2404 set_char_quoting (dirname_quoting_options
, ':', 1);
2406 /* --dired implies --format=long (-l) and sans --hyperlink.
2407 So ignore it if those overridden. */
2408 dired
&= (format
== long_format
) & !print_hyperlink
;
2410 if (eolbyte
< dired
)
2411 error (LS_FAILURE
, 0, _("--dired and --zero are incompatible"));
2413 /* If a time type is explicitly specified (with -c, -u, or --time=)
2414 and we're not showing a time (-l not specified), then sort by that time,
2415 rather than by name. Note this behavior is unspecified by POSIX. */
2417 sort_type
= (0 <= sort_opt
? sort_opt
2418 : (format
!= long_format
&& explicit_time
)
2419 ? sort_time
: sort_name
);
2421 if (format
== long_format
)
2423 char const *style
= time_style_option
;
2424 static char const posix_prefix
[] = "posix-";
2428 style
= getenv ("TIME_STYLE");
2433 while (STREQ_LEN (style
, posix_prefix
, sizeof posix_prefix
- 1))
2435 if (! hard_locale (LC_TIME
))
2437 style
+= sizeof posix_prefix
- 1;
2442 char const *p0
= style
+ 1;
2443 char *p0nl
= strchr (p0
, '\n');
2444 char const *p1
= p0
;
2447 if (strchr (p0nl
+ 1, '\n'))
2448 error (LS_FAILURE
, 0, _("invalid time style format %s"),
2453 long_time_format
[0] = p0
;
2454 long_time_format
[1] = p1
;
2458 ptrdiff_t res
= argmatch (style
, time_style_args
,
2459 (char const *) time_style_types
,
2460 sizeof (*time_style_types
));
2463 /* This whole block used to be a simple use of XARGMATCH.
2464 but that didn't print the "posix-"-prefixed variants or
2465 the "+"-prefixed format string option upon failure. */
2466 argmatch_invalid ("time style", style
, res
);
2468 /* The following is a manual expansion of argmatch_valid,
2469 but with the added "+ ..." description and the [posix-]
2470 prefixes prepended. Note that this simplification works
2471 only because all four existing time_style_types values
2473 fputs (_("Valid arguments are:\n"), stderr
);
2474 char const *const *p
= time_style_args
;
2476 fprintf (stderr
, " - [posix-]%s\n", *p
++);
2477 fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
2478 " format\n"), stderr
);
2483 case full_iso_time_style
:
2484 long_time_format
[0] = long_time_format
[1] =
2485 "%Y-%m-%d %H:%M:%S.%N %z";
2488 case long_iso_time_style
:
2489 long_time_format
[0] = long_time_format
[1] = "%Y-%m-%d %H:%M";
2492 case iso_time_style
:
2493 long_time_format
[0] = "%Y-%m-%d ";
2494 long_time_format
[1] = "%m-%d %H:%M";
2497 case locale_time_style
:
2498 if (hard_locale (LC_TIME
))
2500 for (int i
= 0; i
< 2; i
++)
2501 long_time_format
[i
] =
2502 dcgettext (nullptr, long_time_format
[i
], LC_TIME
);
2513 /* Parse a string as part of the LS_COLORS variable; this may involve
2514 decoding all kinds of escape characters. If equals_end is set an
2515 unescaped equal sign ends the string, otherwise only a : or \0
2516 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2519 The resulting string is *not* null-terminated, but may contain
2522 Note that both dest and src are char **; on return they point to
2523 the first free byte after the array and the character that ended
2524 the input string, respectively. */
2527 get_funky_string (char **dest
, char const **src
, bool equals_end
,
2528 size_t *output_count
)
2530 char num
; /* For numerical codes */
2531 size_t count
; /* Something to count with */
2533 ST_GND
, ST_BACKSLASH
, ST_OCTAL
, ST_HEX
, ST_CARET
, ST_END
, ST_ERROR
2538 p
= *src
; /* We don't want to double-indirect */
2539 q
= *dest
; /* the whole darn time. */
2541 count
= 0; /* No characters counted in yet. */
2544 state
= ST_GND
; /* Start in ground state. */
2545 while (state
< ST_END
)
2549 case ST_GND
: /* Ground state (no escapes) */
2554 state
= ST_END
; /* End of string */
2557 state
= ST_BACKSLASH
; /* Backslash escape sequence */
2561 state
= ST_CARET
; /* Caret escape */
2567 state
= ST_END
; /* End */
2578 case ST_BACKSLASH
: /* Backslash escaped character */
2589 state
= ST_OCTAL
; /* Octal sequence */
2594 state
= ST_HEX
; /* Hex sequence */
2597 case 'a': /* Bell */
2600 case 'b': /* Backspace */
2603 case 'e': /* Escape */
2606 case 'f': /* Form feed */
2609 case 'n': /* Newline */
2612 case 'r': /* Carriage return */
2618 case 'v': /* Vtab */
2621 case '?': /* Delete */
2624 case '_': /* Space */
2627 case '\0': /* End of string */
2628 state
= ST_ERROR
; /* Error! */
2630 default: /* Escaped character like \ ^ : = */
2634 if (state
== ST_BACKSLASH
)
2643 case ST_OCTAL
: /* Octal sequence */
2644 if (*p
< '0' || *p
> '7')
2651 num
= (num
<< 3) + (*(p
++) - '0');
2654 case ST_HEX
: /* Hex sequence */
2667 num
= (num
<< 4) + (*(p
++) - '0');
2675 num
= (num
<< 4) + (*(p
++) - 'a') + 10;
2683 num
= (num
<< 4) + (*(p
++) - 'A') + 10;
2693 case ST_CARET
: /* Caret escape */
2694 state
= ST_GND
; /* Should be the next state... */
2695 if (*p
>= '@' && *p
<= '~')
2697 *(q
++) = *(p
++) & 037;
2716 *output_count
= count
;
2718 return state
!= ST_ERROR
;
2732 /* Check if the content of TERM is a valid name in dircolors. */
2735 known_term_type (void)
2737 char const *term
= getenv ("TERM");
2738 if (! term
|| ! *term
)
2741 char const *line
= G_line
;
2742 while (line
- G_line
< sizeof (G_line
))
2744 if (STRNCMP_LIT (line
, "TERM ") == 0)
2746 if (fnmatch (line
+ 5, term
, 0) == 0)
2749 line
+= strlen (line
) + 1;
2756 parse_ls_color (void)
2758 char const *p
; /* Pointer to character being parsed */
2759 char *buf
; /* color_buf buffer pointer */
2760 char label0
, label1
; /* Indicator label */
2761 struct color_ext_type
*ext
; /* Extension we are working on */
2763 if ((p
= getenv ("LS_COLORS")) == nullptr || *p
== '\0')
2765 /* LS_COLORS takes precedence, but if that's not set then
2766 honor the COLORTERM and TERM env variables so that
2767 we only go with the internal ANSI color codes if the
2768 former is non empty or the latter is set to a known value. */
2769 char const *colorterm
= getenv ("COLORTERM");
2770 if (! (colorterm
&& *colorterm
) && ! known_term_type ())
2771 print_with_color
= false;
2777 /* This is an overly conservative estimate, but any possible
2778 LS_COLORS string will *not* generate a color_buf longer than
2779 itself, so it is a safe way of allocating a buffer in
2781 buf
= color_buf
= xstrdup (p
);
2783 enum parse_state state
= PS_START
;
2788 case PS_START
: /* First label character */
2796 /* Allocate new extension block and add to head of
2797 linked list (this way a later definition will
2798 override an earlier one, which can be useful for
2799 having terminal-specific defs override global). */
2801 ext
= xmalloc (sizeof *ext
);
2802 ext
->next
= color_ext_list
;
2803 color_ext_list
= ext
;
2804 ext
->exact_match
= false;
2807 ext
->ext
.string
= buf
;
2809 state
= (get_funky_string (&buf
, &p
, true, &ext
->ext
.len
)
2814 state
= PS_DONE
; /* Done! */
2817 default: /* Assume it is file type label */
2824 case PS_2
: /* Second label character */
2831 state
= PS_FAIL
; /* Error */
2834 case PS_3
: /* Equal sign after indicator label */
2835 state
= PS_FAIL
; /* Assume failure... */
2836 if (*(p
++) == '=')/* It *should* be... */
2838 for (int i
= 0; i
< ARRAY_CARDINALITY (indicator_name
); i
++)
2840 if ((label0
== indicator_name
[i
][0])
2841 && (label1
== indicator_name
[i
][1]))
2843 color_indicator
[i
].string
= buf
;
2844 state
= (get_funky_string (&buf
, &p
, false,
2845 &color_indicator
[i
].len
)
2846 ? PS_START
: PS_FAIL
);
2850 if (state
== PS_FAIL
)
2851 error (0, 0, _("unrecognized prefix: %s"),
2852 quote ((char []) {label0
, label1
, '\0'}));
2856 case PS_4
: /* Equal sign after *.ext */
2859 ext
->seq
.string
= buf
;
2860 state
= (get_funky_string (&buf
, &p
, false, &ext
->seq
.len
)
2861 ? PS_START
: PS_FAIL
);
2876 if (state
== PS_FAIL
)
2878 struct color_ext_type
*e
;
2879 struct color_ext_type
*e2
;
2882 _("unparsable value for LS_COLORS environment variable"));
2884 for (e
= color_ext_list
; e
!= nullptr; /* empty */)
2890 print_with_color
= false;
2894 /* Postprocess list to set EXACT_MATCH on entries where there are
2895 different cased extensions with separate sequences defined.
2896 Also set ext.len to SIZE_MAX on any entries that can't
2897 match due to precedence, to avoid redundant string compares. */
2898 struct color_ext_type
*e1
;
2900 for (e1
= color_ext_list
; e1
!= nullptr; e1
= e1
->next
)
2902 struct color_ext_type
*e2
;
2903 bool case_ignored
= false;
2905 for (e2
= e1
->next
; e2
!= nullptr; e2
= e2
->next
)
2907 if (e2
->ext
.len
< SIZE_MAX
&& e1
->ext
.len
== e2
->ext
.len
)
2909 if (memcmp (e1
->ext
.string
, e2
->ext
.string
, e1
->ext
.len
) == 0)
2910 e2
->ext
.len
= SIZE_MAX
; /* Ignore */
2911 else if (c_strncasecmp (e1
->ext
.string
, e2
->ext
.string
,
2916 e2
->ext
.len
= SIZE_MAX
; /* Ignore */
2918 else if (e1
->seq
.len
== e2
->seq
.len
2919 && memcmp (e1
->seq
.string
, e2
->seq
.string
,
2922 e2
->ext
.len
= SIZE_MAX
; /* Ignore */
2923 case_ignored
= true; /* Ignore all subsequent */
2927 e1
->exact_match
= true;
2928 e2
->exact_match
= true;
2936 if (color_indicator
[C_LINK
].len
== 6
2937 && !STRNCMP_LIT (color_indicator
[C_LINK
].string
, "target"))
2938 color_symlink_as_referent
= true;
2941 /* Return the quoting style specified by the environment variable
2942 QUOTING_STYLE if set and valid, -1 otherwise. */
2945 getenv_quoting_style (void)
2947 char const *q_style
= getenv ("QUOTING_STYLE");
2950 int i
= ARGMATCH (q_style
, quoting_style_args
, quoting_style_vals
);
2954 _("ignoring invalid value"
2955 " of environment variable QUOTING_STYLE: %s"),
2959 return quoting_style_vals
[i
];
2962 /* Set the exit status to report a failure. If SERIOUS, it is a
2963 serious failure; otherwise, it is merely a minor problem. */
2966 set_exit_status (bool serious
)
2969 exit_status
= LS_FAILURE
;
2970 else if (exit_status
== EXIT_SUCCESS
)
2971 exit_status
= LS_MINOR_PROBLEM
;
2974 /* Assuming a failure is serious if SERIOUS, use the printf-style
2975 MESSAGE to report the failure to access a file named FILE. Assume
2976 errno is set appropriately for the failure. */
2979 file_failure (bool serious
, char const *message
, char const *file
)
2981 error (0, errno
, message
, quoteaf (file
));
2982 set_exit_status (serious
);
2985 /* Request that the directory named NAME have its contents listed later.
2986 If REALNAME is nonzero, it will be used instead of NAME when the
2987 directory name is printed. This allows symbolic links to directories
2988 to be treated as regular directories but still be listed under their
2989 real names. NAME == nullptr is used to insert a marker entry for the
2990 directory named in REALNAME.
2991 If NAME is non-null, we use its dev/ino information to save
2992 a call to stat -- when doing a recursive (-R) traversal.
2993 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2996 queue_directory (char const *name
, char const *realname
, bool command_line_arg
)
2998 struct pending
*new = xmalloc (sizeof *new);
2999 new->realname
= realname
? xstrdup (realname
) : nullptr;
3000 new->name
= name
? xstrdup (name
) : nullptr;
3001 new->command_line_arg
= command_line_arg
;
3002 new->next
= pending_dirs
;
3006 /* Read directory NAME, and list the files in it.
3007 If REALNAME is nonzero, print its name instead of NAME;
3008 this is used for symbolic links to directories.
3009 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
3012 print_dir (char const *name
, char const *realname
, bool command_line_arg
)
3015 struct dirent
*next
;
3016 uintmax_t total_blocks
= 0;
3017 static bool first
= true;
3020 dirp
= opendir (name
);
3023 file_failure (command_line_arg
, _("cannot open directory %s"), name
);
3029 struct stat dir_stat
;
3030 int fd
= dirfd (dirp
);
3032 /* If dirfd failed, endure the overhead of stat'ing by path */
3034 ? fstat_for_ino (fd
, &dir_stat
)
3035 : stat_for_ino (name
, &dir_stat
)) < 0)
3037 file_failure (command_line_arg
,
3038 _("cannot determine device and inode of %s"), name
);
3043 /* If we've already visited this dev/inode pair, warn that
3044 we've found a loop, and do not process this directory. */
3045 if (visit_dir (dir_stat
.st_dev
, dir_stat
.st_ino
))
3047 error (0, 0, _("%s: not listing already-listed directory"),
3050 set_exit_status (true);
3054 dev_ino_push (dir_stat
.st_dev
, dir_stat
.st_ino
);
3059 if (recursive
|| print_dir_name
)
3062 dired_outbyte ('\n');
3066 char *absolute_name
= nullptr;
3067 if (print_hyperlink
)
3069 absolute_name
= canonicalize_filename_mode (name
, CAN_MISSING
);
3070 if (! absolute_name
)
3071 file_failure (command_line_arg
,
3072 _("error canonicalizing %s"), name
);
3074 quote_name (realname
? realname
: name
, dirname_quoting_options
, -1,
3075 nullptr, true, &subdired_obstack
, absolute_name
);
3077 free (absolute_name
);
3079 dired_outstring (":\n");
3082 /* Read the directory entries, and insert the subfiles into the 'cwd_file'
3087 /* Set errno to zero so we can distinguish between a readdir failure
3088 and when readdir simply finds that there are no more entries. */
3090 next
= readdir (dirp
);
3091 /* Some readdir()s do not absorb ENOENT (dir deleted but open). */
3092 if (errno
== ENOENT
)
3096 if (! file_ignored (next
->d_name
))
3099 #if HAVE_STRUCT_DIRENT_D_TYPE
3100 type
= d_type_filetype
[next
->d_type
];
3104 total_blocks
+= gobble_file (next
->d_name
, type
,
3105 RELIABLE_D_INO (next
),
3108 /* In this narrow case, print out each name right away, so
3109 ls uses constant memory while processing the entries of
3110 this directory. Useful when there are many (millions)
3111 of entries in a directory. */
3112 if (format
== one_per_line
&& sort_type
== sort_none
3113 && !print_block_size
&& !recursive
)
3115 /* We must call sort_files in spite of
3116 "sort_type == sort_none" for its initialization
3117 of the sorted_file vector. */
3119 print_current_files ();
3124 else if (errno
!= 0)
3126 file_failure (command_line_arg
, _("reading directory %s"), name
);
3127 if (errno
!= EOVERFLOW
)
3133 /* When processing a very large directory, and since we've inhibited
3134 interrupts, this loop would take so long that ls would be annoyingly
3135 uninterruptible. This ensures that it handles signals promptly. */
3139 if (closedir (dirp
) != 0)
3141 file_failure (command_line_arg
, _("closing directory %s"), name
);
3142 /* Don't return; print whatever we got. */
3145 /* Sort the directory contents. */
3148 /* If any member files are subdirectories, perhaps they should have their
3149 contents listed rather than being mentioned here as files. */
3152 extract_dirs_from_files (name
, false);
3154 if (format
== long_format
|| print_block_size
)
3156 char buf
[LONGEST_HUMAN_READABLE
+ 3];
3157 char *p
= human_readable (total_blocks
, buf
+ 1, human_output_opts
,
3158 ST_NBLOCKSIZE
, output_block_size
);
3159 char *pend
= p
+ strlen (p
);
3163 dired_outstring (_("total"));
3164 dired_outbuf (p
, pend
- p
);
3168 print_current_files ();
3171 /* Add 'pattern' to the list of patterns for which files that match are
3175 add_ignore_pattern (char const *pattern
)
3177 struct ignore_pattern
*ignore
;
3179 ignore
= xmalloc (sizeof *ignore
);
3180 ignore
->pattern
= pattern
;
3181 /* Add it to the head of the linked list. */
3182 ignore
->next
= ignore_patterns
;
3183 ignore_patterns
= ignore
;
3186 /* Return true if one of the PATTERNS matches FILE. */
3189 patterns_match (struct ignore_pattern
const *patterns
, char const *file
)
3191 struct ignore_pattern
const *p
;
3192 for (p
= patterns
; p
; p
= p
->next
)
3193 if (fnmatch (p
->pattern
, file
, FNM_PERIOD
) == 0)
3198 /* Return true if FILE should be ignored. */
3201 file_ignored (char const *name
)
3203 return ((ignore_mode
!= IGNORE_MINIMAL
3205 && (ignore_mode
== IGNORE_DEFAULT
|| ! name
[1 + (name
[1] == '.')]))
3206 || (ignore_mode
== IGNORE_DEFAULT
3207 && patterns_match (hide_patterns
, name
))
3208 || patterns_match (ignore_patterns
, name
));
3211 /* POSIX requires that a file size be printed without a sign, even
3212 when negative. Assume the typical case where negative sizes are
3213 actually positive values that have wrapped around. */
3216 unsigned_file_size (off_t size
)
3218 return size
+ (size
< 0) * ((uintmax_t) OFF_T_MAX
- OFF_T_MIN
+ 1);
3222 /* Return true if NAME has a capability (see linux/capability.h) */
3224 has_capability (char const *name
)
3229 cap_t cap_d
= cap_get_file (name
);
3230 if (cap_d
== nullptr)
3233 result
= cap_to_text (cap_d
, nullptr);
3238 /* check if human-readable capability string is empty */
3239 has_cap
= !!*result
;
3246 has_capability (MAYBE_UNUSED
char const *name
)
3253 /* Enter and remove entries in the table 'cwd_file'. */
3256 free_ent (struct fileinfo
*f
)
3260 free (f
->absolute_name
);
3261 if (f
->scontext
!= UNKNOWN_SECURITY_CONTEXT
)
3262 aclinfo_scontext_free (f
->scontext
);
3265 /* Empty the table of files. */
3269 for (idx_t i
= 0; i
< cwd_n_used
; i
++)
3271 struct fileinfo
*f
= sorted_file
[i
];
3276 cwd_some_quoted
= false;
3277 any_has_acl
= false;
3278 inode_number_width
= 0;
3279 block_size_width
= 0;
3285 major_device_number_width
= 0;
3286 minor_device_number_width
= 0;
3287 file_size_width
= 0;
3290 /* Cache file_has_aclinfo failure, when it's trivial to do.
3291 Like file_has_aclinfo, but when F's st_dev says it's on a file
3292 system lacking ACL support, return 0 with ENOTSUP immediately. */
3294 file_has_aclinfo_cache (char const *file
, struct fileinfo
*f
,
3295 struct aclinfo
*ai
, int flags
)
3297 /* st_dev and associated info for the most recently processed device
3298 for which file_has_acl failed indicating lack of support. */
3299 static int unsupported_return
;
3300 static char *unsupported_scontext
;
3301 static int unsupported_scontext_err
;
3302 static dev_t unsupported_device
;
3304 if (f
->stat
.st_dev
== unsupported_device
)
3306 ai
->buf
= ai
->u
.__gl_acl_ch
;
3308 ai
->scontext
= unsupported_scontext
;
3309 ai
->scontext_err
= unsupported_scontext_err
;
3311 return unsupported_return
;
3315 int n
= file_has_aclinfo (file
, ai
, flags
);
3317 if (n
<= 0 && !acl_errno_valid (err
))
3319 unsupported_return
= n
;
3320 unsupported_scontext
= ai
->scontext
;
3321 unsupported_scontext_err
= ai
->scontext_err
;
3322 unsupported_device
= f
->stat
.st_dev
;
3327 /* Cache has_capability failure, when it's trivial to do.
3328 Like has_capability, but when F's st_dev says it's on a file
3329 system lacking capability support, return 0 with ENOTSUP immediately. */
3331 has_capability_cache (char const *file
, struct fileinfo
*f
)
3333 /* st_dev of the most recently processed device for which we've
3334 found that has_capability fails indicating lack of support. */
3335 static dev_t unsupported_device
;
3337 if (f
->stat
.st_dev
== unsupported_device
)
3343 bool b
= has_capability (file
);
3344 if ( !b
&& !acl_errno_valid (errno
))
3345 unsupported_device
= f
->stat
.st_dev
;
3350 needs_quoting (char const *name
)
3353 size_t len
= quotearg_buffer (test
, sizeof test
, name
, -1,
3354 filename_quoting_options
);
3355 return *name
!= *test
|| strlen (name
) != len
;
3358 /* Add a file to the current table of files.
3359 Verify that the file exists, and print an error message if it does not.
3360 Return the number of blocks that the file occupies. */
3362 gobble_file (char const *name
, enum filetype type
, ino_t inode
,
3363 bool command_line_arg
, char const *dirname
)
3365 uintmax_t blocks
= 0;
3368 /* An inode value prior to gobble_file necessarily came from readdir,
3369 which is not used for command line arguments. */
3370 affirm (! command_line_arg
|| inode
== NOT_AN_INODE_NUMBER
);
3372 if (cwd_n_used
== cwd_n_alloc
)
3373 cwd_file
= xpalloc (cwd_file
, &cwd_n_alloc
, 1, -1, sizeof *cwd_file
);
3375 f
= &cwd_file
[cwd_n_used
];
3376 memset (f
, '\0', sizeof *f
);
3377 f
->stat
.st_ino
= inode
;
3379 f
->scontext
= UNKNOWN_SECURITY_CONTEXT
;
3382 if ((! cwd_some_quoted
) && align_variable_outer_quotes
)
3384 /* Determine if any quoted for padding purposes. */
3385 f
->quoted
= needs_quoting (name
);
3387 cwd_some_quoted
= 1;
3393 || format_needs_stat
3394 || (format_needs_type
&& type
== unknown
)
3395 /* When coloring a directory, stat it to indicate
3396 sticky and/or other-writable attributes. */
3397 || ((type
== directory
|| type
== unknown
) && print_with_color
3398 && (is_colored (C_OTHER_WRITABLE
)
3399 || is_colored (C_STICKY
)
3400 || is_colored (C_STICKY_OTHER_WRITABLE
)))
3401 /* When dereferencing symlinks, the inode and type must come from
3402 stat, but readdir provides the inode and type of lstat. */
3403 || ((print_inode
|| format_needs_type
)
3404 && (type
== symbolic_link
|| type
== unknown
)
3405 && (dereference
== DEREF_ALWAYS
3406 || color_symlink_as_referent
|| check_symlink_mode
))
3407 /* Command line dereferences are already taken care of by the above
3408 assertion that the inode number is not yet known. */
3409 || (print_inode
&& inode
== NOT_AN_INODE_NUMBER
)
3410 /* --indicator-style=classify (aka -F) requires statting each
3411 regular file to see whether it's executable. */
3412 || ((type
== normal
|| type
== unknown
)
3413 && (indicator_style
== classify
3414 /* This is so that --color ends up highlighting files with these
3415 mode bits set even when options like -F are not specified. */
3416 || (print_with_color
&& (is_colored (C_EXEC
)
3417 || is_colored (C_SETUID
)
3418 || is_colored (C_SETGID
))))));
3420 /* Absolute name of this file, if needed. */
3421 char const *full_name
= name
;
3422 if (check_stat
| print_scontext
| format_needs_capability
3423 && name
[0] != '/' && dirname
)
3425 char *p
= alloca (strlen (name
) + strlen (dirname
) + 2);
3426 attach (p
, dirname
, name
);
3433 do_deref
= dereference
== DEREF_ALWAYS
;
3438 if (print_hyperlink
)
3440 f
->absolute_name
= canonicalize_filename_mode (full_name
,
3442 if (! f
->absolute_name
)
3443 file_failure (command_line_arg
,
3444 _("error canonicalizing %s"), full_name
);
3447 switch (dereference
)
3450 err
= do_stat (full_name
, &f
->stat
);
3454 case DEREF_COMMAND_LINE_ARGUMENTS
:
3455 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR
:
3456 if (command_line_arg
)
3459 err
= do_stat (full_name
, &f
->stat
);
3462 if (dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
3465 need_lstat
= (err
< 0
3466 ? (errno
== ENOENT
|| errno
== ELOOP
)
3467 : ! S_ISDIR (f
->stat
.st_mode
));
3471 /* stat failed because of ENOENT || ELOOP, maybe indicating a
3472 non-traversable symlink. Or stat succeeded,
3473 FULL_NAME does not refer to a directory,
3474 and --dereference-command-line-symlink-to-dir is in effect.
3475 Fall through so that we call lstat instead. */
3479 default: /* DEREF_NEVER */
3480 err
= do_lstat (full_name
, &f
->stat
);
3487 /* Failure to stat a command line argument leads to
3488 an exit status of 2. For other files, stat failure
3489 provokes an exit status of 1. */
3490 file_failure (command_line_arg
,
3491 _("cannot access %s"), full_name
);
3493 if (command_line_arg
)
3496 f
->name
= xstrdup (name
);
3503 f
->filetype
= type
= d_type_filetype
[IFTODT (f
->stat
.st_mode
)];
3506 if (type
== directory
&& command_line_arg
&& !immediate_dirs
)
3507 f
->filetype
= type
= arg_directory
;
3509 bool get_scontext
= (format
== long_format
) | print_scontext
;
3510 bool check_capability
= format_needs_capability
& (type
== normal
);
3512 if (get_scontext
| check_capability
)
3515 int aclinfo_flags
= ((do_deref
? ACL_SYMLINK_FOLLOW
: 0)
3516 | (get_scontext
? ACL_GET_SCONTEXT
: 0)
3517 | filetype_d_type
[type
]);
3518 int n
= file_has_aclinfo_cache (full_name
, f
, &ai
, aclinfo_flags
);
3519 bool have_acl
= 0 < n
;
3520 bool have_scontext
= !ai
.scontext_err
;
3521 f
->acl_type
= (!have_scontext
&& !have_acl
3523 : (have_scontext
&& !have_acl
3524 ? ACL_T_LSM_CONTEXT_ONLY
3526 any_has_acl
|= f
->acl_type
!= ACL_T_NONE
;
3528 if (format
== long_format
&& n
< 0)
3529 error (0, ai
.u
.err
, "%s", quotef (full_name
));
3532 /* When requesting security context information, don't make
3533 ls fail just because the file (even a command line argument)
3534 isn't on the right type of file system. I.e., a getfilecon
3535 failure isn't in the same class as a stat failure. */
3536 if (print_scontext
&& ai
.scontext_err
3537 && (! (is_ENOTSUP (ai
.scontext_err
)
3538 || ai
.scontext_err
== ENODATA
)))
3539 error (0, ai
.scontext_err
, "%s", quotef (full_name
));
3542 /* has_capability adds around 30% runtime to 'ls --color',
3543 so call it only if really needed. Note capability coloring
3544 is disabled in the default color config. */
3545 if (check_capability
&& aclinfo_has_xattr (&ai
, XATTR_NAME_CAPS
))
3546 f
->has_capability
= has_capability_cache (full_name
, f
);
3548 f
->scontext
= ai
.scontext
;
3549 ai
.scontext
= nullptr;
3553 if ((type
== symbolic_link
)
3554 & ((format
== long_format
) | check_symlink_mode
))
3556 struct stat linkstats
;
3558 get_link_name (full_name
, f
, command_line_arg
);
3560 /* Use the slower quoting path for this entry, though
3561 don't update CWD_SOME_QUOTED since alignment not affected. */
3562 if (f
->linkname
&& f
->quoted
== 0 && needs_quoting (f
->linkname
))
3565 /* Avoid following symbolic links when possible, i.e., when
3566 they won't be traced and when no indicator is needed. */
3568 && (file_type
<= indicator_style
|| check_symlink_mode
)
3569 && stat_for_mode (full_name
, &linkstats
) == 0)
3572 f
->linkmode
= linkstats
.st_mode
;
3576 blocks
= STP_NBLOCKS (&f
->stat
);
3577 if (format
== long_format
|| print_block_size
)
3579 char buf
[LONGEST_HUMAN_READABLE
+ 1];
3580 int len
= mbswidth (human_readable (blocks
, buf
, human_output_opts
,
3581 ST_NBLOCKSIZE
, output_block_size
),
3583 if (block_size_width
< len
)
3584 block_size_width
= len
;
3587 if (format
== long_format
)
3591 int len
= format_user_width (f
->stat
.st_uid
);
3592 if (owner_width
< len
)
3598 int len
= format_group_width (f
->stat
.st_gid
);
3599 if (group_width
< len
)
3605 int len
= format_user_width (f
->stat
.st_author
);
3606 if (author_width
< len
)
3613 int len
= strlen (f
->scontext
);
3614 if (scontext_width
< len
)
3615 scontext_width
= len
;
3618 if (format
== long_format
)
3620 char b
[INT_BUFSIZE_BOUND (uintmax_t)];
3621 int b_len
= strlen (umaxtostr (f
->stat
.st_nlink
, b
));
3622 if (nlink_width
< b_len
)
3623 nlink_width
= b_len
;
3625 if ((type
== chardev
) | (type
== blockdev
))
3627 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
3628 int len
= strlen (umaxtostr (major (f
->stat
.st_rdev
), buf
));
3629 if (major_device_number_width
< len
)
3630 major_device_number_width
= len
;
3631 len
= strlen (umaxtostr (minor (f
->stat
.st_rdev
), buf
));
3632 if (minor_device_number_width
< len
)
3633 minor_device_number_width
= len
;
3634 len
= major_device_number_width
+ 2 + minor_device_number_width
;
3635 if (file_size_width
< len
)
3636 file_size_width
= len
;
3640 char buf
[LONGEST_HUMAN_READABLE
+ 1];
3641 uintmax_t size
= unsigned_file_size (f
->stat
.st_size
);
3642 int len
= mbswidth (human_readable (size
, buf
,
3643 file_human_output_opts
,
3644 1, file_output_block_size
),
3646 if (file_size_width
< len
)
3647 file_size_width
= len
;
3653 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
3654 int len
= strlen (umaxtostr (f
->stat
.st_ino
, buf
));
3655 if (inode_number_width
< len
)
3656 inode_number_width
= len
;
3659 f
->name
= xstrdup (name
);
3665 /* Return true if F refers to a directory. */
3667 is_directory (const struct fileinfo
*f
)
3669 return f
->filetype
== directory
|| f
->filetype
== arg_directory
;
3672 /* Return true if F refers to a (symlinked) directory. */
3674 is_linked_directory (const struct fileinfo
*f
)
3676 return f
->filetype
== directory
|| f
->filetype
== arg_directory
3677 || S_ISDIR (f
->linkmode
);
3680 /* Put the name of the file that FILENAME is a symbolic link to
3681 into the LINKNAME field of 'f'. COMMAND_LINE_ARG indicates whether
3682 FILENAME is a command-line argument. */
3685 get_link_name (char const *filename
, struct fileinfo
*f
, bool command_line_arg
)
3687 f
->linkname
= areadlink_with_size (filename
, f
->stat
.st_size
);
3688 if (f
->linkname
== nullptr)
3689 file_failure (command_line_arg
, _("cannot read symbolic link %s"),
3693 /* Return true if the last component of NAME is '.' or '..'
3694 This is so we don't try to recurse on '././././. ...' */
3697 basename_is_dot_or_dotdot (char const *name
)
3699 char const *base
= last_component (name
);
3700 return dot_or_dotdot (base
);
3703 /* Remove any entries from CWD_FILE that are for directories,
3704 and queue them to be listed as directories instead.
3705 DIRNAME is the prefix to prepend to each dirname
3706 to make it correct relative to ls's working dir;
3707 if it is null, no prefix is needed and "." and ".." should not be ignored.
3708 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3709 This is desirable when processing directories recursively. */
3712 extract_dirs_from_files (char const *dirname
, bool command_line_arg
)
3715 bool ignore_dot_and_dot_dot
= (dirname
!= nullptr);
3717 if (dirname
&& LOOP_DETECT
)
3719 /* Insert a marker entry first. When we dequeue this marker entry,
3720 we'll know that DIRNAME has been processed and may be removed
3721 from the set of active directories. */
3722 queue_directory (nullptr, dirname
, false);
3725 /* Queue the directories last one first, because queueing reverses the
3727 for (i
= cwd_n_used
; 0 < i
; )
3730 struct fileinfo
*f
= sorted_file
[i
];
3732 if (is_directory (f
)
3733 && (! ignore_dot_and_dot_dot
3734 || ! basename_is_dot_or_dotdot (f
->name
)))
3736 if (!dirname
|| f
->name
[0] == '/')
3737 queue_directory (f
->name
, f
->linkname
, command_line_arg
);
3740 char *name
= file_name_concat (dirname
, f
->name
, nullptr);
3741 queue_directory (name
, f
->linkname
, command_line_arg
);
3744 if (f
->filetype
== arg_directory
)
3749 /* Now delete the directories from the table, compacting all the remaining
3752 for (i
= 0, j
= 0; i
< cwd_n_used
; i
++)
3754 struct fileinfo
*f
= sorted_file
[i
];
3756 j
+= (f
->filetype
!= arg_directory
);
3761 /* Use strcoll to compare strings in this locale. If an error occurs,
3762 report an error and longjmp to failed_strcoll. */
3764 static jmp_buf failed_strcoll
;
3767 xstrcoll (char const *a
, char const *b
)
3771 diff
= strcoll (a
, b
);
3774 error (0, errno
, _("cannot compare file names %s and %s"),
3775 quote_n (0, a
), quote_n (1, b
));
3776 set_exit_status (false);
3777 longjmp (failed_strcoll
, 1);
3782 /* Comparison routines for sorting the files. */
3784 typedef void const *V
;
3785 typedef int (*qsortFunc
)(V a
, V b
);
3787 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants. */
3789 dirfirst_check (struct fileinfo
const *a
, struct fileinfo
const *b
,
3792 int diff
= is_linked_directory (b
) - is_linked_directory (a
);
3793 return diff
? diff
: cmp (a
, b
);
3796 /* Define the 8 different sort function variants required for each sortkey.
3797 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3798 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3799 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3800 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3801 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3802 /* direct, non-dirfirst versions */ \
3803 static int xstrcoll_##key_name (V a, V b) \
3804 { return key_cmp_func (a, b, xstrcoll); } \
3805 ATTRIBUTE_PURE static int strcmp_##key_name (V a, V b) \
3806 { return key_cmp_func (a, b, strcmp); } \
3808 /* reverse, non-dirfirst versions */ \
3809 static int rev_xstrcoll_##key_name (V a, V b) \
3810 { return key_cmp_func (b, a, xstrcoll); } \
3811 ATTRIBUTE_PURE static int rev_strcmp_##key_name (V a, V b) \
3812 { return key_cmp_func (b, a, strcmp); } \
3814 /* direct, dirfirst versions */ \
3815 static int xstrcoll_df_##key_name (V a, V b) \
3816 { return dirfirst_check (a, b, xstrcoll_##key_name); } \
3817 ATTRIBUTE_PURE static int strcmp_df_##key_name (V a, V b) \
3818 { return dirfirst_check (a, b, strcmp_##key_name); } \
3820 /* reverse, dirfirst versions */ \
3821 static int rev_xstrcoll_df_##key_name (V a, V b) \
3822 { return dirfirst_check (a, b, rev_xstrcoll_##key_name); } \
3823 ATTRIBUTE_PURE static int rev_strcmp_df_##key_name (V a, V b) \
3824 { return dirfirst_check (a, b, rev_strcmp_##key_name); }
3827 cmp_ctime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3828 int (*cmp
) (char const *, char const *))
3830 int diff
= timespec_cmp (get_stat_ctime (&b
->stat
),
3831 get_stat_ctime (&a
->stat
));
3832 return diff
? diff
: cmp (a
->name
, b
->name
);
3836 cmp_mtime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3837 int (*cmp
) (char const *, char const *))
3839 int diff
= timespec_cmp (get_stat_mtime (&b
->stat
),
3840 get_stat_mtime (&a
->stat
));
3841 return diff
? diff
: cmp (a
->name
, b
->name
);
3845 cmp_atime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3846 int (*cmp
) (char const *, char const *))
3848 int diff
= timespec_cmp (get_stat_atime (&b
->stat
),
3849 get_stat_atime (&a
->stat
));
3850 return diff
? diff
: cmp (a
->name
, b
->name
);
3854 cmp_btime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3855 int (*cmp
) (char const *, char const *))
3857 int diff
= timespec_cmp (get_stat_btime (&b
->stat
),
3858 get_stat_btime (&a
->stat
));
3859 return diff
? diff
: cmp (a
->name
, b
->name
);
3863 off_cmp (off_t a
, off_t b
)
3865 return (a
> b
) - (a
< b
);
3869 cmp_size (struct fileinfo
const *a
, struct fileinfo
const *b
,
3870 int (*cmp
) (char const *, char const *))
3872 int diff
= off_cmp (b
->stat
.st_size
, a
->stat
.st_size
);
3873 return diff
? diff
: cmp (a
->name
, b
->name
);
3877 cmp_name (struct fileinfo
const *a
, struct fileinfo
const *b
,
3878 int (*cmp
) (char const *, char const *))
3880 return cmp (a
->name
, b
->name
);
3883 /* Compare file extensions. Files with no extension are 'smallest'.
3884 If extensions are the same, compare by file names instead. */
3887 cmp_extension (struct fileinfo
const *a
, struct fileinfo
const *b
,
3888 int (*cmp
) (char const *, char const *))
3890 char const *base1
= strrchr (a
->name
, '.');
3891 char const *base2
= strrchr (b
->name
, '.');
3892 int diff
= cmp (base1
? base1
: "", base2
? base2
: "");
3893 return diff
? diff
: cmp (a
->name
, b
->name
);
3896 /* Return the (cached) screen width,
3897 for the NAME associated with the passed fileinfo F. */
3900 fileinfo_name_width (struct fileinfo
const *f
)
3904 : quote_name_width (f
->name
, filename_quoting_options
, f
->quoted
);
3908 cmp_width (struct fileinfo
const *a
, struct fileinfo
const *b
,
3909 int (*cmp
) (char const *, char const *))
3911 int diff
= fileinfo_name_width (a
) - fileinfo_name_width (b
);
3912 return diff
? diff
: cmp (a
->name
, b
->name
);
3915 DEFINE_SORT_FUNCTIONS (ctime
, cmp_ctime
)
3916 DEFINE_SORT_FUNCTIONS (mtime
, cmp_mtime
)
3917 DEFINE_SORT_FUNCTIONS (atime
, cmp_atime
)
3918 DEFINE_SORT_FUNCTIONS (btime
, cmp_btime
)
3919 DEFINE_SORT_FUNCTIONS (size
, cmp_size
)
3920 DEFINE_SORT_FUNCTIONS (name
, cmp_name
)
3921 DEFINE_SORT_FUNCTIONS (extension
, cmp_extension
)
3922 DEFINE_SORT_FUNCTIONS (width
, cmp_width
)
3924 /* Compare file versions.
3925 Unlike the other compare functions, cmp_version does not fail
3926 because filevercmp and strcmp do not fail; cmp_version uses strcmp
3927 instead of xstrcoll because filevercmp is locale-independent so
3928 strcmp is its appropriate secondary.
3930 All the other sort options need xstrcoll and strcmp variants,
3931 because they all use xstrcoll (either as the primary or secondary
3932 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3935 cmp_version (struct fileinfo
const *a
, struct fileinfo
const *b
)
3937 int diff
= filevercmp (a
->name
, b
->name
);
3938 return diff
? diff
: strcmp (a
->name
, b
->name
);
3942 xstrcoll_version (V a
, V b
)
3944 return cmp_version (a
, b
);
3947 rev_xstrcoll_version (V a
, V b
)
3949 return cmp_version (b
, a
);
3952 xstrcoll_df_version (V a
, V b
)
3954 return dirfirst_check (a
, b
, xstrcoll_version
);
3957 rev_xstrcoll_df_version (V a
, V b
)
3959 return dirfirst_check (a
, b
, rev_xstrcoll_version
);
3963 /* We have 2^3 different variants for each sort-key function
3964 (for 3 independent sort modes).
3965 The function pointers stored in this array must be dereferenced as:
3967 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3969 Note that the order in which sort keys are listed in the function pointer
3970 array below is defined by the order of the elements in the time_type and
3973 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3976 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3977 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3980 { strcmp_##key_name, strcmp_df_##key_name }, \
3981 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3985 static qsortFunc
const sort_functions
[][2][2][2] =
3987 LIST_SORTFUNCTION_VARIANTS (name
),
3988 LIST_SORTFUNCTION_VARIANTS (extension
),
3989 LIST_SORTFUNCTION_VARIANTS (width
),
3990 LIST_SORTFUNCTION_VARIANTS (size
),
3994 { xstrcoll_version
, xstrcoll_df_version
},
3995 { rev_xstrcoll_version
, rev_xstrcoll_df_version
},
3998 /* We use nullptr for the strcmp variants of version comparison
3999 since as explained in cmp_version definition, version comparison
4000 does not rely on xstrcoll, so it will never longjmp, and never
4001 need to try the strcmp fallback. */
4003 { nullptr, nullptr },
4004 { nullptr, nullptr },
4008 /* last are time sort functions */
4009 LIST_SORTFUNCTION_VARIANTS (mtime
),
4010 LIST_SORTFUNCTION_VARIANTS (ctime
),
4011 LIST_SORTFUNCTION_VARIANTS (atime
),
4012 LIST_SORTFUNCTION_VARIANTS (btime
)
4015 /* The number of sort keys is calculated as the sum of
4016 the number of elements in the sort_type enum (i.e., sort_numtypes)
4017 -2 because neither sort_time nor sort_none use entries themselves
4018 the number of elements in the time_type enum (i.e., time_numtypes)
4019 This is because when sort_type==sort_time, we have up to
4020 time_numtypes possible sort keys.
4022 This line verifies at compile-time that the array of sort functions has been
4023 initialized for all possible sort keys. */
4024 static_assert (ARRAY_CARDINALITY (sort_functions
)
4025 == sort_numtypes
- 2 + time_numtypes
);
4027 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
4030 initialize_ordering_vector (void)
4032 for (idx_t i
= 0; i
< cwd_n_used
; i
++)
4033 sorted_file
[i
] = &cwd_file
[i
];
4036 /* Cache values based on attributes global to all files. */
4039 update_current_files_info (void)
4041 /* Cache screen width of name, if needed multiple times. */
4042 if (sort_type
== sort_width
4043 || (line_length
&& (format
== many_per_line
|| format
== horizontal
)))
4045 for (idx_t i
= 0; i
< cwd_n_used
; i
++)
4047 struct fileinfo
*f
= sorted_file
[i
];
4048 f
->width
= fileinfo_name_width (f
);
4053 /* Sort the files now in the table. */
4060 if (sorted_file_alloc
< cwd_n_used
+ (cwd_n_used
>> 1))
4063 sorted_file
= xinmalloc (cwd_n_used
, 3 * sizeof *sorted_file
);
4064 sorted_file_alloc
= 3 * cwd_n_used
;
4067 initialize_ordering_vector ();
4069 update_current_files_info ();
4071 if (sort_type
== sort_none
)
4074 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
4075 ignore strcoll failures, as a failing strcoll might be a
4076 comparison function that is not a total order, and if we ignored
4077 the failure this might cause qsort to dump core. */
4079 if (! setjmp (failed_strcoll
))
4080 use_strcmp
= false; /* strcoll() succeeded */
4084 affirm (sort_type
!= sort_version
);
4085 initialize_ordering_vector ();
4088 /* When sort_type == sort_time, use time_type as subindex. */
4089 mpsort ((void const **) sorted_file
, cwd_n_used
,
4090 sort_functions
[sort_type
+ (sort_type
== sort_time
? time_type
: 0)]
4091 [use_strcmp
][sort_reverse
]
4092 [directories_first
]);
4095 /* List all the files now in the table. */
4098 print_current_files (void)
4103 for (idx_t i
= 0; i
< cwd_n_used
; i
++)
4105 print_file_name_and_frills (sorted_file
[i
], 0);
4112 print_with_separator (' ');
4114 print_many_per_line ();
4119 print_with_separator (' ');
4121 print_horizontal ();
4125 print_with_separator (',');
4129 for (idx_t i
= 0; i
< cwd_n_used
; i
++)
4131 set_normal_color ();
4132 print_long_format (sorted_file
[i
]);
4133 dired_outbyte (eolbyte
);
4139 /* Replace the first %b with precomputed aligned month names.
4140 Note on glibc-2.7 at least, this speeds up the whole 'ls -lU'
4141 process by around 17%, compared to letting strftime() handle the %b. */
4144 align_nstrftime (char *buf
, size_t size
, bool recent
, struct tm
const *tm
,
4145 timezone_t tz
, int ns
)
4147 char const *nfmt
= (use_abformat
4148 ? abformat
[recent
][tm
->tm_mon
]
4149 : long_time_format
[recent
]);
4150 return nstrftime (buf
, size
, nfmt
, tm
, tz
, ns
);
4153 /* Return the expected number of columns in a long-format timestamp,
4154 or zero if it cannot be calculated. */
4157 long_time_expected_width (void)
4159 static int width
= -1;
4165 char buf
[TIME_STAMP_LEN_MAXIMUM
+ 1];
4167 /* In case you're wondering if localtime_rz can fail with an input time_t
4168 value of 0, let's just say it's very unlikely, but not inconceivable.
4169 The TZ environment variable would have to specify a time zone that
4170 is 2**31-1900 years or more ahead of UTC. This could happen only on
4171 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
4172 However, this is not possible with Solaris 10 or glibc-2.3.5, since
4173 their implementations limit the offset to 167:59 and 24:00, resp. */
4174 if (localtime_rz (localtz
, &epoch
, &tm
))
4176 size_t len
= align_nstrftime (buf
, sizeof buf
, false,
4179 width
= mbsnwidth (buf
, len
, MBSWIDTH_FLAGS
);
4189 /* Print the user or group name NAME, with numeric id ID, using a
4190 print width of WIDTH columns. */
4193 format_user_or_group (char const *name
, uintmax_t id
, int width
)
4197 int name_width
= mbswidth (name
, MBSWIDTH_FLAGS
);
4198 int width_gap
= name_width
< 0 ? 0 : width
- name_width
;
4199 int pad
= MAX (0, width_gap
);
4200 dired_outstring (name
);
4203 dired_outbyte (' ');
4207 dired_pos
+= printf ("%*ju ", width
, id
);
4210 /* Print the name or id of the user with id U, using a print width of
4214 format_user (uid_t u
, int width
, bool stat_ok
)
4216 format_user_or_group (! stat_ok
? "?" :
4217 (numeric_ids
? nullptr : getuser (u
)), u
, width
);
4220 /* Likewise, for groups. */
4223 format_group (gid_t g
, int width
, bool stat_ok
)
4225 format_user_or_group (! stat_ok
? "?" :
4226 (numeric_ids
? nullptr : getgroup (g
)), g
, width
);
4229 /* Return the number of columns that format_user_or_group will print,
4230 or -1 if unknown. */
4233 format_user_or_group_width (char const *name
, uintmax_t id
)
4236 ? mbswidth (name
, MBSWIDTH_FLAGS
)
4237 : snprintf (nullptr, 0, "%ju", id
));
4240 /* Return the number of columns that format_user will print,
4241 or -1 if unknown. */
4244 format_user_width (uid_t u
)
4246 return format_user_or_group_width (numeric_ids
? nullptr : getuser (u
), u
);
4249 /* Likewise, for groups. */
4252 format_group_width (gid_t g
)
4254 return format_user_or_group_width (numeric_ids
? nullptr : getgroup (g
), g
);
4257 /* Return a pointer to a formatted version of F->stat.st_ino,
4258 possibly using buffer, which must be at least
4259 INT_BUFSIZE_BOUND (uintmax_t) bytes. */
4261 format_inode (char buf
[INT_BUFSIZE_BOUND (uintmax_t)],
4262 const struct fileinfo
*f
)
4264 return (f
->stat_ok
&& f
->stat
.st_ino
!= NOT_AN_INODE_NUMBER
4265 ? umaxtostr (f
->stat
.st_ino
, buf
)
4269 /* Print information about F in long format. */
4271 print_long_format (const struct fileinfo
*f
)
4275 [LONGEST_HUMAN_READABLE
+ 1 /* inode */
4276 + LONGEST_HUMAN_READABLE
+ 1 /* size in blocks */
4277 + sizeof (modebuf
) - 1 + 1 /* mode string */
4278 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
4279 + LONGEST_HUMAN_READABLE
+ 2 /* major device number */
4280 + LONGEST_HUMAN_READABLE
+ 1 /* minor device number */
4281 + TIME_STAMP_LEN_MAXIMUM
+ 1 /* max length of time/date */
4285 struct timespec when_timespec
;
4286 struct tm when_local
;
4287 bool btime_ok
= true;
4289 /* Compute the mode string, except remove the trailing space if no
4290 file in this directory has an ACL or security context. */
4292 filemodestring (&f
->stat
, modebuf
);
4295 modebuf
[0] = filetype_letter
[f
->filetype
];
4296 memset (modebuf
+ 1, '?', 10);
4301 else if (f
->acl_type
== ACL_T_LSM_CONTEXT_ONLY
)
4303 else if (f
->acl_type
== ACL_T_YES
)
4309 when_timespec
= get_stat_ctime (&f
->stat
);
4312 when_timespec
= get_stat_mtime (&f
->stat
);
4315 when_timespec
= get_stat_atime (&f
->stat
);
4318 when_timespec
= get_stat_btime (&f
->stat
);
4319 if (when_timespec
.tv_sec
== -1 && when_timespec
.tv_nsec
== -1)
4330 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4331 p
+= sprintf (p
, "%*s ", inode_number_width
, format_inode (hbuf
, f
));
4334 if (print_block_size
)
4336 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
4337 char const *blocks
=
4340 : human_readable (STP_NBLOCKS (&f
->stat
), hbuf
, human_output_opts
,
4341 ST_NBLOCKSIZE
, output_block_size
));
4342 int blocks_width
= mbswidth (blocks
, MBSWIDTH_FLAGS
);
4343 for (int pad
= blocks_width
< 0 ? 0 : block_size_width
- blocks_width
;
4346 while ((*p
++ = *blocks
++))
4351 /* The last byte of the mode string is the POSIX
4352 "optional alternate access method flag". */
4354 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4355 p
+= sprintf (p
, "%s %*s ", modebuf
, nlink_width
,
4356 ! f
->stat_ok
? "?" : umaxtostr (f
->stat
.st_nlink
, hbuf
));
4361 if (print_owner
|| print_group
|| print_author
|| print_scontext
)
4363 dired_outbuf (buf
, p
- buf
);
4366 format_user (f
->stat
.st_uid
, owner_width
, f
->stat_ok
);
4369 format_group (f
->stat
.st_gid
, group_width
, f
->stat_ok
);
4372 format_user (f
->stat
.st_author
, author_width
, f
->stat_ok
);
4375 format_user_or_group (f
->scontext
, 0, scontext_width
);
4381 && (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
)))
4383 char majorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4384 char minorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4385 int blanks_width
= (file_size_width
4386 - (major_device_number_width
+ 2
4387 + minor_device_number_width
));
4388 p
+= sprintf (p
, "%*s, %*s ",
4389 major_device_number_width
+ MAX (0, blanks_width
),
4390 umaxtostr (major (f
->stat
.st_rdev
), majorbuf
),
4391 minor_device_number_width
,
4392 umaxtostr (minor (f
->stat
.st_rdev
), minorbuf
));
4396 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
4400 : human_readable (unsigned_file_size (f
->stat
.st_size
),
4401 hbuf
, file_human_output_opts
, 1,
4402 file_output_block_size
));
4403 int size_width
= mbswidth (size
, MBSWIDTH_FLAGS
);
4404 for (int pad
= size_width
< 0 ? 0 : file_size_width
- size_width
;
4407 while ((*p
++ = *size
++))
4415 if (f
->stat_ok
&& btime_ok
4416 && localtime_rz (localtz
, &when_timespec
.tv_sec
, &when_local
))
4418 struct timespec six_months_ago
;
4421 /* If the file appears to be in the future, update the current
4422 time, in case the file happens to have been modified since
4423 the last time we checked the clock. */
4424 if (timespec_cmp (current_time
, when_timespec
) < 0)
4425 gettime (¤t_time
);
4427 /* Consider a time to be recent if it is within the past six months.
4428 A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952 seconds
4429 on the average. Write this value as an integer constant to
4430 avoid floating point hassles. */
4431 six_months_ago
.tv_sec
= current_time
.tv_sec
- 31556952 / 2;
4432 six_months_ago
.tv_nsec
= current_time
.tv_nsec
;
4434 recent
= (timespec_cmp (six_months_ago
, when_timespec
) < 0
4435 && timespec_cmp (when_timespec
, current_time
) < 0);
4437 /* We assume here that all time zones are offset from UTC by a
4438 whole number of seconds. */
4439 s
= align_nstrftime (p
, TIME_STAMP_LEN_MAXIMUM
+ 1, recent
,
4440 &when_local
, localtz
, when_timespec
.tv_nsec
);
4450 /* The time cannot be converted using the desired format, so
4451 print it as a huge integer number of seconds. */
4452 char hbuf
[INT_BUFSIZE_BOUND (intmax_t)];
4453 p
+= sprintf (p
, "%*s ", long_time_expected_width (),
4454 (! f
->stat_ok
|| ! btime_ok
4456 : timetostr (when_timespec
.tv_sec
, hbuf
)));
4457 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
4460 dired_outbuf (buf
, p
- buf
);
4461 size_t w
= print_name_with_quoting (f
, false, &dired_obstack
, p
- buf
);
4463 if (f
->filetype
== symbolic_link
)
4467 dired_outstring (" -> ");
4468 print_name_with_quoting (f
, true, nullptr, (p
- buf
) + w
+ 4);
4469 if (indicator_style
!= none
)
4470 print_type_indicator (true, f
->linkmode
, unknown
);
4473 else if (indicator_style
!= none
)
4474 print_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
4477 /* Write to *BUF a quoted representation of the file name NAME, if non-null,
4478 using OPTIONS to control quoting. *BUF is set to NAME if no quoting
4479 is required. *BUF is allocated if more space required (and the original
4480 *BUF is not deallocated).
4481 Store the number of screen columns occupied by NAME's quoted
4482 representation into WIDTH, if non-null.
4483 Store into PAD whether an initial space is needed for padding.
4484 Return the number of bytes in *BUF. */
4487 quote_name_buf (char **inbuf
, size_t bufsize
, char *name
,
4488 struct quoting_options
const *options
,
4489 int needs_general_quoting
, size_t *width
, bool *pad
)
4492 size_t displayed_width
IF_LINT ( = 0);
4496 enum quoting_style qs
= get_quoting_style (options
);
4497 bool needs_further_quoting
= qmark_funny_chars
4498 && (qs
== shell_quoting_style
4499 || qs
== shell_always_quoting_style
4500 || qs
== literal_quoting_style
);
4502 if (needs_general_quoting
!= 0)
4504 len
= quotearg_buffer (buf
, bufsize
, name
, -1, options
);
4507 buf
= xmalloc (len
+ 1);
4508 quotearg_buffer (buf
, len
+ 1, name
, -1, options
);
4511 quoted
= (*name
!= *buf
) || strlen (name
) != len
;
4513 else if (needs_further_quoting
)
4515 len
= strlen (name
);
4517 buf
= xmalloc (len
+ 1);
4518 memcpy (buf
, name
, len
+ 1);
4524 len
= strlen (name
);
4529 if (needs_further_quoting
)
4533 char const *p
= buf
;
4534 char const *plimit
= buf
+ len
;
4536 displayed_width
= 0;
4541 case ' ': case '!': case '"': case '#': case '%':
4542 case '&': case '\'': case '(': case ')': case '*':
4543 case '+': case ',': case '-': case '.': case '/':
4544 case '0': case '1': case '2': case '3': case '4':
4545 case '5': case '6': case '7': case '8': case '9':
4546 case ':': case ';': case '<': case '=': case '>':
4548 case 'A': case 'B': case 'C': case 'D': case 'E':
4549 case 'F': case 'G': case 'H': case 'I': case 'J':
4550 case 'K': case 'L': case 'M': case 'N': case 'O':
4551 case 'P': case 'Q': case 'R': case 'S': case 'T':
4552 case 'U': case 'V': case 'W': case 'X': case 'Y':
4554 case '[': case '\\': case ']': case '^': case '_':
4555 case 'a': case 'b': case 'c': case 'd': case 'e':
4556 case 'f': case 'g': case 'h': case 'i': case 'j':
4557 case 'k': case 'l': case 'm': case 'n': case 'o':
4558 case 'p': case 'q': case 'r': case 's': case 't':
4559 case 'u': case 'v': case 'w': case 'x': case 'y':
4560 case 'z': case '{': case '|': case '}': case '~':
4561 /* These characters are printable ASCII characters. */
4563 displayed_width
+= 1;
4566 /* If we have a multibyte sequence, copy it until we
4567 reach its end, replacing each non-printable multibyte
4568 character with a single question mark. */
4570 mbstate_t mbstate
; mbszero (&mbstate
);
4577 bytes
= mbrtoc32 (&wc
, p
, plimit
- p
, &mbstate
);
4579 if (bytes
== (size_t) -1)
4581 /* An invalid multibyte sequence was
4582 encountered. Skip one input byte, and
4583 put a question mark. */
4586 displayed_width
+= 1;
4590 if (bytes
== (size_t) -2)
4592 /* An incomplete multibyte character
4593 at the end. Replace it entirely with
4597 displayed_width
+= 1;
4602 /* A null wide character was encountered. */
4608 /* A printable multibyte character.
4610 for (; bytes
> 0; --bytes
)
4612 displayed_width
+= w
;
4616 /* An nonprintable multibyte character.
4617 Replace it entirely with a question
4621 displayed_width
+= 1;
4624 while (! mbsinit (&mbstate
));
4629 /* The buffer may have shrunk. */
4635 char const *plimit
= buf
+ len
;
4639 if (! isprint (to_uchar (*p
)))
4643 displayed_width
= len
;
4646 else if (width
!= nullptr)
4650 displayed_width
= mbsnwidth (buf
, len
, MBSWIDTH_FLAGS
);
4651 displayed_width
= MAX (0, displayed_width
);
4655 char const *p
= buf
;
4656 char const *plimit
= buf
+ len
;
4658 displayed_width
= 0;
4661 if (isprint (to_uchar (*p
)))
4668 /* Set padding to better align quoted items,
4669 and also give a visual indication that quotes are
4670 not actually part of the name. */
4671 *pad
= (align_variable_outer_quotes
&& cwd_some_quoted
&& ! quoted
);
4673 if (width
!= nullptr)
4674 *width
= displayed_width
;
4682 quote_name_width (char const *name
, struct quoting_options
const *options
,
4683 int needs_general_quoting
)
4685 char smallbuf
[BUFSIZ
];
4686 char *buf
= smallbuf
;
4690 quote_name_buf (&buf
, sizeof smallbuf
, (char *) name
, options
,
4691 needs_general_quoting
, &width
, &pad
);
4693 if (buf
!= smallbuf
&& buf
!= name
)
4701 /* %XX escape any input out of range as defined in RFC3986,
4702 and also if PATH, convert all path separators to '/'. */
4704 file_escape (char const *str
, bool path
)
4706 char *esc
= xnmalloc (3, strlen (str
) + 1);
4710 if (path
&& ISSLASH (*str
))
4715 else if (RFC3986
[to_uchar (*str
)])
4718 p
+= sprintf (p
, "%%%02x", to_uchar (*str
++));
4725 quote_name (char const *name
, struct quoting_options
const *options
,
4726 int needs_general_quoting
, const struct bin_str
*color
,
4727 bool allow_pad
, struct obstack
*stack
, char const *absolute_name
)
4729 char smallbuf
[BUFSIZ
];
4730 char *buf
= smallbuf
;
4734 len
= quote_name_buf (&buf
, sizeof smallbuf
, (char *) name
, options
,
4735 needs_general_quoting
, nullptr, &pad
);
4737 if (pad
&& allow_pad
)
4738 dired_outbyte (' ');
4741 print_color_indicator (color
);
4743 /* If we're padding, then don't include the outer quotes in
4744 the --hyperlink, to improve the alignment of those links. */
4745 bool skip_quotes
= false;
4749 if (align_variable_outer_quotes
&& cwd_some_quoted
&& ! pad
)
4754 char *h
= file_escape (hostname
, /* path= */ false);
4755 char *n
= file_escape (absolute_name
, /* path= */ true);
4756 /* TODO: It would be good to be able to define parameters
4757 to give hints to the terminal as how best to render the URI.
4758 For example since ls is outputting a dense block of URIs
4759 it would be best to not underline by default, and only
4760 do so upon hover etc. */
4761 printf ("\033]8;;file://%s%s%s\a", h
, *n
== '/' ? "" : "/", n
);
4767 push_current_dired_pos (stack
);
4769 fwrite (buf
+ skip_quotes
, 1, len
- (skip_quotes
* 2), stdout
);
4774 push_current_dired_pos (stack
);
4778 fputs ("\033]8;;\a", stdout
);
4780 putchar (*(buf
+ len
- 1));
4783 if (buf
!= smallbuf
&& buf
!= name
)
4790 print_name_with_quoting (const struct fileinfo
*f
,
4791 bool symlink_target
,
4792 struct obstack
*stack
,
4795 char const *name
= symlink_target
? f
->linkname
: f
->name
;
4797 const struct bin_str
*color
4798 = print_with_color
? get_color_indicator (f
, symlink_target
) : nullptr;
4800 bool used_color_this_time
= (print_with_color
4801 && (color
|| is_colored (C_NORM
)));
4803 size_t len
= quote_name (name
, filename_quoting_options
, f
->quoted
,
4804 color
, !symlink_target
, stack
, f
->absolute_name
);
4807 if (used_color_this_time
)
4809 prep_non_filename_text ();
4811 /* We use the byte length rather than display width here as
4812 an optimization to avoid accurately calculating the width,
4813 because we only output the clear to EOL sequence if the name
4814 _might_ wrap to the next line. This may output a sequence
4815 unnecessarily in multi-byte locales for example,
4816 but in that case it's inconsequential to the output. */
4818 && (start_col
/ line_length
!= (start_col
+ len
- 1) / line_length
))
4819 put_indicator (&color_indicator
[C_CLR_TO_EOL
]);
4826 prep_non_filename_text (void)
4828 if (color_indicator
[C_END
].string
!= nullptr)
4829 put_indicator (&color_indicator
[C_END
]);
4832 put_indicator (&color_indicator
[C_LEFT
]);
4833 put_indicator (&color_indicator
[C_RESET
]);
4834 put_indicator (&color_indicator
[C_RIGHT
]);
4838 /* Print the file name of 'f' with appropriate quoting.
4839 Also print file size, inode number, and filetype indicator character,
4840 as requested by switches. */
4843 print_file_name_and_frills (const struct fileinfo
*f
, size_t start_col
)
4845 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
4847 set_normal_color ();
4850 printf ("%*s ", format
== with_commas
? 0 : inode_number_width
,
4851 format_inode (buf
, f
));
4853 if (print_block_size
)
4854 printf ("%*s ", format
== with_commas
? 0 : block_size_width
,
4856 : human_readable (STP_NBLOCKS (&f
->stat
), buf
, human_output_opts
,
4857 ST_NBLOCKSIZE
, output_block_size
));
4860 printf ("%*s ", format
== with_commas
? 0 : scontext_width
, f
->scontext
);
4862 size_t width
= print_name_with_quoting (f
, false, nullptr, start_col
);
4864 if (indicator_style
!= none
)
4865 width
+= print_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
4870 /* Given these arguments describing a file, return the single-byte
4871 type indicator, or 0. */
4873 get_type_indicator (bool stat_ok
, mode_t mode
, enum filetype type
)
4877 if (stat_ok
? S_ISREG (mode
) : type
== normal
)
4879 if (stat_ok
&& indicator_style
== classify
&& (mode
& S_IXUGO
))
4886 if (stat_ok
? S_ISDIR (mode
) : type
== directory
|| type
== arg_directory
)
4888 else if (indicator_style
== slash
)
4890 else if (stat_ok
? S_ISLNK (mode
) : type
== symbolic_link
)
4892 else if (stat_ok
? S_ISFIFO (mode
) : type
== fifo
)
4894 else if (stat_ok
? S_ISSOCK (mode
) : type
== sock
)
4896 else if (stat_ok
&& S_ISDOOR (mode
))
4905 print_type_indicator (bool stat_ok
, mode_t mode
, enum filetype type
)
4907 char c
= get_type_indicator (stat_ok
, mode
, type
);
4913 /* Returns if color sequence was printed. */
4915 print_color_indicator (const struct bin_str
*ind
)
4919 /* Need to reset so not dealing with attribute combinations */
4920 if (is_colored (C_NORM
))
4921 restore_default_color ();
4922 put_indicator (&color_indicator
[C_LEFT
]);
4923 put_indicator (ind
);
4924 put_indicator (&color_indicator
[C_RIGHT
]);
4927 return ind
!= nullptr;
4930 /* Returns color indicator or nullptr if none. */
4932 static const struct bin_str
*
4933 get_color_indicator (const struct fileinfo
*f
, bool symlink_target
)
4935 enum indicator_no type
;
4936 struct color_ext_type
*ext
; /* Color extension */
4937 size_t len
; /* Length of name */
4946 linkok
= f
->linkok
? 0 : -1;
4951 mode
= file_or_link_mode (f
);
4955 /* Is this a nonexistent file? If so, linkok == -1. */
4957 if (linkok
== -1 && is_colored (C_MISSING
))
4959 else if (!f
->stat_ok
)
4961 static enum indicator_no
const filetype_indicator
[] =
4963 C_ORPHAN
, C_FIFO
, C_CHR
, C_DIR
, C_BLK
, C_FILE
,
4964 C_LINK
, C_SOCK
, C_FILE
, C_DIR
4966 static_assert (ARRAY_CARDINALITY (filetype_indicator
)
4967 == filetype_cardinality
);
4968 type
= filetype_indicator
[f
->filetype
];
4976 if ((mode
& S_ISUID
) != 0 && is_colored (C_SETUID
))
4978 else if ((mode
& S_ISGID
) != 0 && is_colored (C_SETGID
))
4980 else if (f
->has_capability
)
4982 else if ((mode
& S_IXUGO
) != 0 && is_colored (C_EXEC
))
4984 else if ((1 < f
->stat
.st_nlink
) && is_colored (C_MULTIHARDLINK
))
4985 type
= C_MULTIHARDLINK
;
4987 else if (S_ISDIR (mode
))
4991 if ((mode
& S_ISVTX
) && (mode
& S_IWOTH
)
4992 && is_colored (C_STICKY_OTHER_WRITABLE
))
4993 type
= C_STICKY_OTHER_WRITABLE
;
4994 else if ((mode
& S_IWOTH
) != 0 && is_colored (C_OTHER_WRITABLE
))
4995 type
= C_OTHER_WRITABLE
;
4996 else if ((mode
& S_ISVTX
) != 0 && is_colored (C_STICKY
))
4999 else if (S_ISLNK (mode
))
5001 else if (S_ISFIFO (mode
))
5003 else if (S_ISSOCK (mode
))
5005 else if (S_ISBLK (mode
))
5007 else if (S_ISCHR (mode
))
5009 else if (S_ISDOOR (mode
))
5013 /* Classify a file of some other type as C_ORPHAN. */
5018 /* Check the file's suffix only if still classified as C_FILE. */
5022 /* Test if NAME has a recognized suffix. */
5024 len
= strlen (name
);
5025 name
+= len
; /* Pointer to final \0. */
5026 for (ext
= color_ext_list
; ext
!= nullptr; ext
= ext
->next
)
5028 if (ext
->ext
.len
<= len
)
5030 if (ext
->exact_match
)
5032 if (STREQ_LEN (name
- ext
->ext
.len
, ext
->ext
.string
,
5038 if (c_strncasecmp (name
- ext
->ext
.len
, ext
->ext
.string
,
5046 /* Adjust the color for orphaned symlinks. */
5047 if (type
== C_LINK
&& !linkok
)
5049 if (color_symlink_as_referent
|| is_colored (C_ORPHAN
))
5053 const struct bin_str
*const s
5054 = ext
? &(ext
->seq
) : &color_indicator
[type
];
5056 return s
->string
? s
: nullptr;
5059 /* Output a color indicator (which may contain nulls). */
5061 put_indicator (const struct bin_str
*ind
)
5067 /* If the standard output is a controlling terminal, watch out
5068 for signals, so that the colors can be restored to the
5069 default state if "ls" is suspended or interrupted. */
5071 if (0 <= tcgetpgrp (STDOUT_FILENO
))
5074 prep_non_filename_text ();
5077 fwrite (ind
->string
, ind
->len
, 1, stdout
);
5081 length_of_file_name_and_frills (const struct fileinfo
*f
)
5084 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
5087 len
+= 1 + (format
== with_commas
5088 ? strlen (umaxtostr (f
->stat
.st_ino
, buf
))
5089 : inode_number_width
);
5091 if (print_block_size
)
5092 len
+= 1 + (format
== with_commas
5093 ? strlen (! f
->stat_ok
? "?"
5094 : human_readable (STP_NBLOCKS (&f
->stat
), buf
,
5095 human_output_opts
, ST_NBLOCKSIZE
,
5097 : block_size_width
);
5100 len
+= 1 + (format
== with_commas
? strlen (f
->scontext
) : scontext_width
);
5102 len
+= fileinfo_name_width (f
);
5104 if (indicator_style
!= none
)
5106 char c
= get_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
5114 print_many_per_line (void)
5116 idx_t cols
= calculate_columns (true);
5117 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
5119 /* Calculate the number of rows that will be in each column except possibly
5120 for a short column on the right. */
5121 idx_t rows
= cwd_n_used
/ cols
+ (cwd_n_used
% cols
!= 0);
5123 for (idx_t row
= 0; row
< rows
; row
++)
5126 idx_t filesno
= row
;
5129 /* Print the next row. */
5132 struct fileinfo
const *f
= sorted_file
[filesno
];
5133 size_t name_length
= length_of_file_name_and_frills (f
);
5134 size_t max_name_length
= line_fmt
->col_arr
[col
++];
5135 print_file_name_and_frills (f
, pos
);
5137 if (cwd_n_used
- rows
<= filesno
)
5141 indent (pos
+ name_length
, pos
+ max_name_length
);
5142 pos
+= max_name_length
;
5149 print_horizontal (void)
5152 idx_t cols
= calculate_columns (false);
5153 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
5154 struct fileinfo
const *f
= sorted_file
[0];
5155 size_t name_length
= length_of_file_name_and_frills (f
);
5156 size_t max_name_length
= line_fmt
->col_arr
[0];
5158 /* Print first entry. */
5159 print_file_name_and_frills (f
, 0);
5162 for (idx_t filesno
= 1; filesno
< cwd_n_used
; filesno
++)
5164 idx_t col
= filesno
% cols
;
5173 indent (pos
+ name_length
, pos
+ max_name_length
);
5174 pos
+= max_name_length
;
5177 f
= sorted_file
[filesno
];
5178 print_file_name_and_frills (f
, pos
);
5180 name_length
= length_of_file_name_and_frills (f
);
5181 max_name_length
= line_fmt
->col_arr
[col
];
5186 /* Output name + SEP + ' '. */
5189 print_with_separator (char sep
)
5193 for (idx_t filesno
= 0; filesno
< cwd_n_used
; filesno
++)
5195 struct fileinfo
const *f
= sorted_file
[filesno
];
5196 size_t len
= line_length
? length_of_file_name_and_frills (f
) : 0;
5203 || ((pos
+ len
+ 2 < line_length
)
5204 && (pos
<= SIZE_MAX
- len
- 2)))
5212 separator
= eolbyte
;
5216 putchar (separator
);
5219 print_file_name_and_frills (f
, pos
);
5225 /* Assuming cursor is at position FROM, indent up to position TO.
5226 Use a TAB character instead of two or more spaces whenever possible. */
5229 indent (size_t from
, size_t to
)
5233 if (tabsize
!= 0 && to
/ tabsize
> (from
+ 1) / tabsize
)
5236 from
+= tabsize
- from
% tabsize
;
5246 /* Put DIRNAME/NAME into DEST, handling '.' and '/' properly. */
5247 /* FIXME: maybe remove this function someday. See about using a
5248 non-malloc'ing version of file_name_concat. */
5251 attach (char *dest
, char const *dirname
, char const *name
)
5253 char const *dirnamep
= dirname
;
5255 /* Copy dirname if it is not ".". */
5256 if (dirname
[0] != '.' || dirname
[1] != 0)
5259 *dest
++ = *dirnamep
++;
5260 /* Add '/' if 'dirname' doesn't already end with it. */
5261 if (dirnamep
> dirname
&& dirnamep
[-1] != '/')
5269 /* Allocate enough column info suitable for the current number of
5270 files and display columns, and initialize the info to represent the
5271 narrowest possible columns. */
5274 init_column_info (idx_t max_cols
)
5276 /* Currently allocated columns in column_info. */
5277 static idx_t column_info_alloc
;
5279 if (column_info_alloc
< max_cols
)
5281 idx_t old_column_info_alloc
= column_info_alloc
;
5282 column_info
= xpalloc (column_info
, &column_info_alloc
,
5283 max_cols
- column_info_alloc
, -1,
5284 sizeof *column_info
);
5286 /* Allocate the new size_t objects by computing the triangle
5287 formula n * (n + 1) / 2, except that we don't need to
5288 allocate the part of the triangle that we've already
5289 allocated. Check for address arithmetic overflow. */
5290 idx_t column_info_growth
= column_info_alloc
- old_column_info_alloc
, s
;
5291 if (ckd_add (&s
, old_column_info_alloc
+ 1, column_info_alloc
)
5292 || ckd_mul (&s
, s
, column_info_growth
))
5294 size_t *p
= xinmalloc (s
>> 1, sizeof *p
);
5296 /* Grow the triangle by parceling out the cells just allocated. */
5297 for (idx_t i
= old_column_info_alloc
; i
< column_info_alloc
; i
++)
5299 column_info
[i
].col_arr
= p
;
5304 for (idx_t i
= 0; i
< max_cols
; ++i
)
5306 column_info
[i
].valid_len
= true;
5307 column_info
[i
].line_len
= (i
+ 1) * MIN_COLUMN_WIDTH
;
5308 for (idx_t j
= 0; j
<= i
; ++j
)
5309 column_info
[i
].col_arr
[j
] = MIN_COLUMN_WIDTH
;
5313 /* Calculate the number of columns needed to represent the current set
5314 of files in the current display width. */
5317 calculate_columns (bool by_columns
)
5319 /* Normally the maximum number of columns is determined by the
5320 screen width. But if few files are available this might limit it
5322 idx_t max_cols
= 0 < max_idx
&& max_idx
< cwd_n_used
? max_idx
: cwd_n_used
;
5324 init_column_info (max_cols
);
5326 /* Compute the maximum number of possible columns. */
5327 for (idx_t filesno
= 0; filesno
< cwd_n_used
; ++filesno
)
5329 struct fileinfo
const *f
= sorted_file
[filesno
];
5330 size_t name_length
= length_of_file_name_and_frills (f
);
5332 for (idx_t i
= 0; i
< max_cols
; ++i
)
5334 if (column_info
[i
].valid_len
)
5336 idx_t idx
= (by_columns
5337 ? filesno
/ ((cwd_n_used
+ i
) / (i
+ 1))
5338 : filesno
% (i
+ 1));
5339 size_t real_length
= name_length
+ (idx
== i
? 0 : 2);
5341 if (column_info
[i
].col_arr
[idx
] < real_length
)
5343 column_info
[i
].line_len
+= (real_length
5344 - column_info
[i
].col_arr
[idx
]);
5345 column_info
[i
].col_arr
[idx
] = real_length
;
5346 column_info
[i
].valid_len
= (column_info
[i
].line_len
5353 /* Find maximum allowed columns. */
5355 for (cols
= max_cols
; 1 < cols
; --cols
)
5357 if (column_info
[cols
- 1].valid_len
)
5367 if (status
!= EXIT_SUCCESS
)
5371 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name
);
5373 List information about the FILEs (the current directory by default).\n\
5374 Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n\
5377 emit_mandatory_arg_note ();
5380 -a, --all do not ignore entries starting with .\n\
5381 -A, --almost-all do not list implied . and ..\n\
5382 --author with -l, print the author of each file\n\
5383 -b, --escape print C-style escapes for nongraphic characters\n\
5386 --block-size=SIZE with -l, scale sizes by SIZE when printing them;\n\
5387 e.g., '--block-size=M'; see SIZE format below\n\
5391 -B, --ignore-backups do not list implied entries ending with ~\n\
5394 -c with -lt: sort by, and show, ctime (time of last\n\
5395 change of file status information);\n\
5396 with -l: show ctime and sort by name;\n\
5397 otherwise: sort by ctime, newest first\n\
5401 -C list entries by columns\n\
5402 --color[=WHEN] color the output WHEN; more info below\n\
5403 -d, --directory list directories themselves, not their contents\n\
5404 -D, --dired generate output designed for Emacs' dired mode\n\
5408 -F, --classify[=WHEN] append indicator (one of */=>@|) to entries WHEN\n\
5409 --file-type likewise, except do not append '*'\n\
5412 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
5413 single-column -1, verbose -l, vertical -C\n\
5417 --full-time like -l --time-style=full-iso\n\
5420 -g like -l, but do not list owner\n\
5423 --group-directories-first\n\
5424 group directories before files\n\
5427 -G, --no-group in a long listing, don't print group names\n\
5430 -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc.\n\
5431 --si likewise, but use powers of 1000 not 1024\n\
5434 -H, --dereference-command-line\n\
5435 follow symbolic links listed on the command line\n\
5438 --dereference-command-line-symlink-to-dir\n\
5439 follow each command line symbolic link\n\
5440 that points to a directory\n\
5444 --hide=PATTERN do not list implied entries matching shell PATTERN\
5446 (overridden by -a or -A)\n\
5450 --hyperlink[=WHEN] hyperlink file names WHEN\n\
5453 --indicator-style=WORD\n\
5454 append indicator with style WORD to entry names:\n\
5455 none (default), slash (-p),\n\
5456 file-type (--file-type), classify (-F)\n\
5460 -i, --inode print the index number of each file\n\
5461 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\
5465 -k, --kibibytes default to 1024-byte blocks for file system usage;\
5467 used only with -s and per directory totals\n\
5471 -l use a long listing format\n\
5474 -L, --dereference when showing file information for a symbolic\n\
5475 link, show information for the file the link\n\
5476 references rather than for the link itself\n\
5480 -m fill width with a comma separated list of entries\
5484 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
5485 -N, --literal print entry names without quoting\n\
5486 -o like -l, but do not list group information\n\
5487 -p, --indicator-style=slash\n\
5488 append / indicator to directories\n\
5491 -q, --hide-control-chars print ? instead of nongraphic characters\n\
5494 --show-control-chars show nongraphic characters as-is (the default,\n\
5495 unless program is 'ls' and output is a terminal)\
5500 -Q, --quote-name enclose entry names in double quotes\n\
5503 --quoting-style=WORD use quoting style WORD for entry names:\n\
5504 literal, locale, shell, shell-always,\n\
5505 shell-escape, shell-escape-always, c, escape\n\
5506 (overrides QUOTING_STYLE environment variable)\n\
5510 -r, --reverse reverse order while sorting\n\
5511 -R, --recursive list subdirectories recursively\n\
5512 -s, --size print the allocated size of each file, in blocks\n\
5515 -S sort by file size, largest first\n\
5518 --sort=WORD change default 'name' sort to WORD:\n\
5519 none (-U), size (-S), time (-t),\n\
5520 version (-v), extension (-X), name, width\n\
5524 --time=WORD select which timestamp used to display or sort;\n\
5525 access time (-u): atime, access, use;\n\
5526 metadata change time (-c): ctime, status;\n\
5527 modified time (default): mtime, modification;\n\
5528 birth time: birth, creation;\n\
5529 with -l, WORD determines which time to show;\n\
5530 with --sort=time, sort by WORD (newest first)\n\
5534 --time-style=TIME_STYLE\n\
5535 time/date format with -l; see TIME_STYLE below\n\
5538 -t sort by time, newest first; see --time\n\
5539 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
5542 -u with -lt: sort by, and show, access time;\n\
5543 with -l: show access time and sort by name;\n\
5544 otherwise: sort by access time, newest first\n\
5548 -U do not sort directory entries\n\
5551 -v natural sort of (version) numbers within text\n\
5554 -w, --width=COLS set output width to COLS. 0 means no limit\n\
5555 -x list entries by lines instead of by columns\n\
5556 -X sort alphabetically by entry extension\n\
5557 -Z, --context print any security context of each file\n\
5558 --zero end each output line with NUL, not newline\n\
5559 -1 list one file per line\n\
5561 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
5562 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
5566 The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT.\n\
5567 FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2,\n\
5568 then FORMAT1 applies to non-recent files and FORMAT2 to recent files.\n\
5569 TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale.\n\
5570 Also the TIME_STYLE environment variable sets the default style to use.\n\
5574 The WHEN argument defaults to 'always' and can also be 'auto' or 'never'.\n\
5578 Using color to distinguish file types is disabled both by default and\n\
5579 with --color=never. With --color=auto, ls emits color codes only when\n\
5580 standard output is connected to a terminal. The LS_COLORS environment\n\
5581 variable can change the settings. Use the dircolors(1) command to set it.\n\
5587 1 if minor problems (e.g., cannot access subdirectory),\n\
5588 2 if serious trouble (e.g., cannot access command-line argument).\n\
5590 emit_ancillary_info (PROGRAM_NAME
);