1 /* 'dir', 'vdir' and 'ls' directory listing programs for GNU.
2 Copyright (C) 1985-2023 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* If ls_mode is LS_MULTI_COL,
18 the multi-column format is the default regardless
19 of the type of output device.
20 This is for the 'dir' program.
22 If ls_mode is LS_LONG_FORMAT,
23 the long format is the default regardless of the
24 type of output device.
25 This is for the 'vdir' program.
28 the output format depends on whether the output
30 This is for the 'ls' program. */
32 /* Written by Richard Stallman and David MacKenzie. */
34 /* Color support by Peter Anvin <Peter.Anvin@linux.org> and Dennis
35 Flaherty <dennisf@denix.elk.miles.com> based on original patches by
36 Greg Lee <lee@uhunix.uhcc.hawaii.edu>. */
39 #include <sys/types.h>
45 #include <sys/ioctl.h>
47 #ifdef WINSIZE_IN_PTEM
48 # include <sys/stream.h>
49 # include <sys/ptem.h>
58 #include <selinux/selinux.h>
61 #if HAVE_LANGINFO_CODESET
62 # include <langinfo.h>
65 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
68 # define SA_NOCLDSTOP 0
69 # define sigprocmask(How, Set, Oset) /* empty */
71 # if ! HAVE_SIGINTERRUPT
72 # define siginterrupt(sig, flag) /* empty */
76 /* NonStop circa 2011 lacks both SA_RESTART and siginterrupt, so don't
77 restart syscalls after a signal handler fires. This may cause
78 colors to get messed up on the screen if 'ls' is interrupted, but
79 that's the best we can do on such a platform. */
89 #include "c-strcase.h"
93 #include "filenamecat.h"
94 #include "hard-locale.h"
98 #include "filevercmp.h"
101 #include "mbswidth.h"
106 #include "stat-size.h"
107 #include "stat-time.h"
108 #include "strftime.h"
109 #include "xdectoint.h"
111 #include "xstrtol-error.h"
112 #include "areadlink.h"
113 #include "mbsalign.h"
114 #include "dircolors.h"
115 #include "xgethostname.h"
117 #include "canonicalize.h"
120 /* Include <sys/capability.h> last to avoid a clash of <sys/types.h>
121 include guards with some premature versions of libcap.
122 For more details, see <https://bugzilla.redhat.com/483548>. */
124 # include <sys/capability.h>
127 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
128 : (ls_mode == LS_MULTI_COL \
132 proper_name ("Richard M. Stallman"), \
133 proper_name ("David MacKenzie")
135 #define obstack_chunk_alloc malloc
136 #define obstack_chunk_free free
138 /* Unix-based readdir implementations have historically returned a dirent.d_ino
139 value that is sometimes not equal to the stat-obtained st_ino value for
140 that same entry. This error occurs for a readdir entry that refers
141 to a mount point. readdir's error is to return the inode number of
142 the underlying directory -- one that typically cannot be stat'ed, as
143 long as a file system is mounted on that directory. RELIABLE_D_INO
144 encapsulates whether we can use the more efficient approach of relying
145 on readdir-supplied d_ino values, or whether we must incur the cost of
146 calling stat or lstat to obtain each guaranteed-valid inode number. */
148 #ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
149 # define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
152 #if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
153 # define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
155 # define RELIABLE_D_INO(dp) D_INO (dp)
158 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
159 # define st_author st_uid
176 /* Display letters and indicators for each filetype.
177 Keep these in sync with enum filetype. */
178 static char const filetype_letter
[] = "?pcdb-lswd";
180 /* Ensure that filetype and filetype_letter have the same
181 number of elements. */
182 static_assert (sizeof filetype_letter
- 1 == arg_directory
+ 1);
184 #define FILETYPE_INDICATORS \
186 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
187 C_LINK, C_SOCK, C_FILE, C_DIR \
193 ACL_T_LSM_CONTEXT_ONLY
,
202 /* For symbolic link, name of the file linked to, otherwise zero. */
205 /* For terminal hyperlinks. */
210 enum filetype filetype
;
212 /* For symbolic link and long listing, st_mode of file linked to, otherwise
216 /* security context. */
221 /* For symbolic link and color printing, true if linked-to file
222 exists, otherwise false. */
225 /* For long listings, true if the file has an access control list,
226 or a security context. */
227 enum acl_type acl_type
;
229 /* For color listings, true if a regular file has capability info. */
232 /* Whether file name needs quoting. tri-state with -1 == unknown. */
235 /* Cached screen width (including quoting). */
239 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
241 /* Null is a valid character in a color indicator (think about Epson
242 printers, for example) so we have to use a length/buffer string
247 size_t len
; /* Number of bytes */
248 char const *string
; /* Pointer to the same */
252 # define tcgetpgrp(Fd) 0
255 static size_t quote_name (char const *name
,
256 struct quoting_options
const *options
,
257 int needs_general_quoting
,
258 const struct bin_str
*color
,
259 bool allow_pad
, struct obstack
*stack
,
260 char const *absolute_name
);
261 static size_t quote_name_buf (char **inbuf
, size_t bufsize
, char *name
,
262 struct quoting_options
const *options
,
263 int needs_general_quoting
, size_t *width
,
265 static char *make_link_name (char const *name
, char const *linkname
);
266 static int decode_switches (int argc
, char **argv
);
267 static bool file_ignored (char const *name
);
268 static uintmax_t gobble_file (char const *name
, enum filetype type
,
269 ino_t inode
, bool command_line_arg
,
270 char const *dirname
);
271 static const struct bin_str
* get_color_indicator (const struct fileinfo
*f
,
272 bool symlink_target
);
273 static bool print_color_indicator (const struct bin_str
*ind
);
274 static void put_indicator (const struct bin_str
*ind
);
275 static void add_ignore_pattern (char const *pattern
);
276 static void attach (char *dest
, char const *dirname
, char const *name
);
277 static void clear_files (void);
278 static void extract_dirs_from_files (char const *dirname
,
279 bool command_line_arg
);
280 static void get_link_name (char const *filename
, struct fileinfo
*f
,
281 bool command_line_arg
);
282 static void indent (size_t from
, size_t to
);
283 static size_t calculate_columns (bool by_columns
);
284 static void print_current_files (void);
285 static void print_dir (char const *name
, char const *realname
,
286 bool command_line_arg
);
287 static size_t print_file_name_and_frills (const struct fileinfo
*f
,
289 static void print_horizontal (void);
290 static int format_user_width (uid_t u
);
291 static int format_group_width (gid_t g
);
292 static void print_long_format (const struct fileinfo
*f
);
293 static void print_many_per_line (void);
294 static size_t print_name_with_quoting (const struct fileinfo
*f
,
296 struct obstack
*stack
,
298 static void prep_non_filename_text (void);
299 static bool print_type_indicator (bool stat_ok
, mode_t mode
,
301 static void print_with_separator (char sep
);
302 static void queue_directory (char const *name
, char const *realname
,
303 bool command_line_arg
);
304 static void sort_files (void);
305 static void parse_ls_color (void);
307 static int getenv_quoting_style (void);
309 static size_t quote_name_width (char const *name
,
310 struct quoting_options
const *options
,
311 int needs_general_quoting
);
313 /* Initial size of hash table.
314 Most hierarchies are likely to be shallower than this. */
315 enum { INITIAL_TABLE_SIZE
= 30 };
317 /* The set of 'active' directories, from the current command-line argument
318 to the level in the hierarchy at which files are being listed.
319 A directory is represented by its device and inode numbers (struct dev_ino).
320 A directory is added to this set when ls begins listing it or its
321 entries, and it is removed from the set just after ls has finished
322 processing it. This set is used solely to detect loops, e.g., with
323 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
324 static Hash_table
*active_dir_set
;
326 #define LOOP_DETECT (!!active_dir_set)
328 /* The table of files in the current directory:
330 'cwd_file' points to a vector of 'struct fileinfo', one per file.
331 'cwd_n_alloc' is the number of elements space has been allocated for.
332 'cwd_n_used' is the number actually in use. */
334 /* Address of block containing the files that are described. */
335 static struct fileinfo
*cwd_file
;
337 /* Length of block that 'cwd_file' points to, measured in files. */
338 static size_t cwd_n_alloc
;
340 /* Index of first unused slot in 'cwd_file'. */
341 static size_t cwd_n_used
;
343 /* Whether files needs may need padding due to quoting. */
344 static bool cwd_some_quoted
;
346 /* Whether quoting style _may_ add outer quotes,
347 and whether aligning those is useful. */
348 static bool align_variable_outer_quotes
;
350 /* Vector of pointers to files, in proper sorted order, and the number
351 of entries allocated for it. */
352 static void **sorted_file
;
353 static size_t sorted_file_alloc
;
355 /* When true, in a color listing, color each symlink name according to the
356 type of file it points to. Otherwise, color them according to the 'ln'
357 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
358 regardless. This is set when 'ln=target' appears in LS_COLORS. */
360 static bool color_symlink_as_referent
;
362 static char const *hostname
;
364 /* Mode of appropriate file for coloring. */
366 file_or_link_mode (struct fileinfo
const *file
)
368 return (color_symlink_as_referent
&& file
->linkok
369 ? file
->linkmode
: file
->stat
.st_mode
);
373 /* Record of one pending directory waiting to be listed. */
378 /* If the directory is actually the file pointed to by a symbolic link we
379 were told to list, 'realname' will contain the name of the symbolic
380 link, otherwise zero. */
382 bool command_line_arg
;
383 struct pending
*next
;
386 static struct pending
*pending_dirs
;
388 /* Current time in seconds and nanoseconds since 1970, updated as
389 needed when deciding whether a file is recent. */
391 static struct timespec current_time
;
393 static bool print_scontext
;
394 static char UNKNOWN_SECURITY_CONTEXT
[] = "?";
396 /* Whether any of the files has an ACL. This affects the width of the
399 static bool any_has_acl
;
401 /* The number of columns to use for columns containing inode numbers,
402 block sizes, link counts, owners, groups, authors, major device
403 numbers, minor device numbers, and file sizes, respectively. */
405 static int inode_number_width
;
406 static int block_size_width
;
407 static int nlink_width
;
408 static int scontext_width
;
409 static int owner_width
;
410 static int group_width
;
411 static int author_width
;
412 static int major_device_number_width
;
413 static int minor_device_number_width
;
414 static int file_size_width
;
418 /* long_format for lots of info, one per line.
419 one_per_line for just names, one per line.
420 many_per_line for just names, many per line, sorted vertically.
421 horizontal for just names, many per line, sorted horizontally.
422 with_commas for just names, many per line, separated by commas.
424 -l (and other options that imply -l), -1, -C, -x and -m control
429 long_format
, /* -l and other options that imply -l */
430 one_per_line
, /* -1 */
431 many_per_line
, /* -C */
436 static enum format format
;
438 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
439 ISO-style timestamps, though shorter than 'full-iso'. 'iso' uses shorter
440 ISO-style timestamps. 'locale' uses locale-dependent timestamps. */
443 full_iso_time_style
, /* --time-style=full-iso */
444 long_iso_time_style
, /* --time-style=long-iso */
445 iso_time_style
, /* --time-style=iso */
446 locale_time_style
/* --time-style=locale */
449 static char const *const time_style_args
[] =
451 "full-iso", "long-iso", "iso", "locale", NULL
453 static enum time_style
const time_style_types
[] =
455 full_iso_time_style
, long_iso_time_style
, iso_time_style
,
458 ARGMATCH_VERIFY (time_style_args
, time_style_types
);
460 /* Type of time to print or sort by. Controlled by -c and -u.
461 The values of each item of this enum are important since they are
462 used as indices in the sort functions array (see sort_files()). */
466 time_mtime
= 0, /* default */
469 time_btime
, /* birth time */
470 time_numtypes
/* the number of elements of this enum */
473 static enum time_type time_type
;
475 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
476 The values of each item of this enum are important since they are
477 used as indices in the sort functions array (see sort_files()). */
481 sort_name
= 0, /* default */
482 sort_extension
, /* -X */
485 sort_version
, /* -v */
486 sort_time
, /* -t; must be second to last */
487 sort_none
, /* -U; must be last */
488 sort_numtypes
/* the number of elements of this enum */
491 static enum sort_type sort_type
;
493 /* Direction of sort.
494 false means highest first if numeric,
495 lowest first if alphabetic;
496 these are the defaults.
497 true means the opposite order in each case. -r */
499 static bool sort_reverse
;
501 /* True means to display owner information. -g turns this off. */
503 static bool print_owner
= true;
505 /* True means to display author information. */
507 static bool print_author
;
509 /* True means to display group information. -G and -o turn this off. */
511 static bool print_group
= true;
513 /* True means print the user and group id's as numbers rather
516 static bool numeric_ids
;
518 /* True means mention the size in blocks of each file. -s */
520 static bool print_block_size
;
522 /* Human-readable options for output, when printing block counts. */
523 static int human_output_opts
;
525 /* The units to use when printing block counts. */
526 static uintmax_t output_block_size
;
528 /* Likewise, but for file sizes. */
529 static int file_human_output_opts
;
530 static uintmax_t file_output_block_size
= 1;
532 /* Follow the output with a special string. Using this format,
533 Emacs' dired mode starts up twice as fast, and can handle all
534 strange characters in file names. */
537 /* 'none' means don't mention the type of files.
538 'slash' means mention directories only, with a '/'.
539 'file_type' means mention file types.
540 'classify' means mention file types and mark executables.
542 Controlled by -F, -p, and --indicator-style. */
546 none
= 0, /* --indicator-style=none (default) */
547 slash
, /* -p, --indicator-style=slash */
548 file_type
, /* --indicator-style=file-type */
549 classify
/* -F, --indicator-style=classify */
552 static enum indicator_style indicator_style
;
554 /* Names of indicator styles. */
555 static char const *const indicator_style_args
[] =
557 "none", "slash", "file-type", "classify", NULL
559 static enum indicator_style
const indicator_style_types
[] =
561 none
, slash
, file_type
, classify
563 ARGMATCH_VERIFY (indicator_style_args
, indicator_style_types
);
565 /* True means use colors to mark types. Also define the different
566 colors as well as the stuff for the LS_COLORS environment variable.
567 The LS_COLORS variable is now in a termcap-like format. */
569 static bool print_with_color
;
571 static bool print_hyperlink
;
573 /* Whether we used any colors in the output so far. If so, we will
574 need to restore the default color later. If not, we will need to
575 call prep_non_filename_text before using color for the first time. */
577 static bool used_color
= false;
581 when_never
, /* 0: default or --color=never */
582 when_always
, /* 1: --color=always */
583 when_if_tty
/* 2: --color=tty */
586 enum Dereference_symlink
588 DEREF_UNDEFINED
= 0, /* default */
590 DEREF_COMMAND_LINE_ARGUMENTS
, /* -H */
591 DEREF_COMMAND_LINE_SYMLINK_TO_DIR
, /* the default, in certain cases */
592 DEREF_ALWAYS
/* -L */
597 C_LEFT
, C_RIGHT
, C_END
, C_RESET
, C_NORM
, C_FILE
, C_DIR
, C_LINK
,
599 C_BLK
, C_CHR
, C_MISSING
, C_ORPHAN
, C_EXEC
, C_DOOR
, C_SETUID
, C_SETGID
,
600 C_STICKY
, C_OTHER_WRITABLE
, C_STICKY_OTHER_WRITABLE
, C_CAP
, C_MULTIHARDLINK
,
604 static char const *const indicator_name
[]=
606 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
607 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
608 "ow", "tw", "ca", "mh", "cl", NULL
611 struct color_ext_type
613 struct bin_str ext
; /* The extension we're looking for */
614 struct bin_str seq
; /* The sequence to output when we do */
615 struct color_ext_type
*next
; /* Next in list */
618 static struct bin_str color_indicator
[] =
620 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
621 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
622 { 0, NULL
}, /* ec: End color (replaces lc+rs+rc) */
623 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
624 { 0, NULL
}, /* no: Normal */
625 { 0, NULL
}, /* fi: File: default */
626 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
627 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
628 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
629 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
630 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
631 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
632 { 0, NULL
}, /* mi: Missing file: undefined */
633 { 0, NULL
}, /* or: Orphaned symlink: undefined */
634 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
635 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
636 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
637 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
638 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
639 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
640 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
641 { 0, NULL
}, /* ca: disabled by default */
642 { 0, NULL
}, /* mh: disabled by default */
643 { LEN_STR_PAIR ("\033[K") }, /* cl: clear to end of line */
647 static struct color_ext_type
*color_ext_list
= NULL
;
649 /* Buffer for color sequences */
650 static char *color_buf
;
652 /* True means to check for orphaned symbolic link, for displaying
653 colors, or to group symlink to directories with other dirs. */
655 static bool check_symlink_mode
;
657 /* True means mention the inode number of each file. -i */
659 static bool print_inode
;
661 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
662 other options that imply -l), and -L. */
664 static enum Dereference_symlink dereference
;
666 /* True means when a directory is found, display info on its
669 static bool recursive
;
671 /* True means when an argument is a directory name, display info
674 static bool immediate_dirs
;
676 /* True means that directories are grouped before files. */
678 static bool directories_first
;
680 /* Which files to ignore. */
684 /* Ignore files whose names start with '.', and files specified by
685 --hide and --ignore. */
688 /* Ignore '.', '..', and files specified by --ignore. */
689 IGNORE_DOT_AND_DOTDOT
,
691 /* Ignore only files specified by --ignore. */
695 /* A linked list of shell-style globbing patterns. If a non-argument
696 file name matches any of these patterns, it is ignored.
697 Controlled by -I. Multiple -I options accumulate.
698 The -B option adds '*~' and '.*~' to this list. */
700 struct ignore_pattern
703 struct ignore_pattern
*next
;
706 static struct ignore_pattern
*ignore_patterns
;
708 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
709 variable itself to be ignored. */
710 static struct ignore_pattern
*hide_patterns
;
712 /* True means output nongraphic chars in file names as '?'.
713 (-q, --hide-control-chars)
714 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
715 independent. The algorithm is: first, obey the quoting style to get a
716 string representing the file name; then, if qmark_funny_chars is set,
717 replace all nonprintable chars in that string with '?'. It's necessary
718 to replace nonprintable chars even in quoted strings, because we don't
719 want to mess up the terminal if control chars get sent to it, and some
720 quoting methods pass through control chars as-is. */
721 static bool qmark_funny_chars
;
723 /* Quoting options for file and dir name output. */
725 static struct quoting_options
*filename_quoting_options
;
726 static struct quoting_options
*dirname_quoting_options
;
728 /* The number of chars per hardware tab stop. Setting this to zero
729 inhibits the use of TAB characters for separating columns. -T */
730 static size_t tabsize
;
732 /* True means print each directory name before listing it. */
734 static bool print_dir_name
;
736 /* The line length to use for breaking lines in many-per-line format.
737 Can be set with -w. If zero, there is no limit. */
739 static size_t line_length
;
741 /* The local time zone rules, as per the TZ environment variable. */
743 static timezone_t localtz
;
745 /* If true, the file listing format requires that stat be called on
748 static bool format_needs_stat
;
750 /* Similar to 'format_needs_stat', but set if only the file type is
753 static bool format_needs_type
;
755 /* An arbitrary limit on the number of bytes in a printed timestamp.
756 This is set to a relatively small value to avoid the need to worry
757 about denial-of-service attacks on servers that run "ls" on behalf
758 of remote clients. 1000 bytes should be enough for any practical
761 enum { TIME_STAMP_LEN_MAXIMUM
= MAX (1000, INT_STRLEN_BOUND (time_t)) };
763 /* strftime formats for non-recent and recent files, respectively, in
766 static char const *long_time_format
[2] =
768 /* strftime format for non-recent files (older than 6 months), in
769 -l output. This should contain the year, month and day (at
770 least), in an order that is understood by people in your
771 locale's territory. Please try to keep the number of used
772 screen columns small, because many people work in windows with
773 only 80 columns. But make this as wide as the other string
774 below, for recent files. */
775 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
776 so be wary of using variable width fields from the locale.
777 Note %b is handled specially by ls and aligned correctly.
778 Note also that specifying a width as in %5b is erroneous as strftime
779 will count bytes rather than characters in multibyte locales. */
781 /* strftime format for recent files (younger than 6 months), in -l
782 output. This should contain the month, day and time (at
783 least), in an order that is understood by people in your
784 locale's territory. Please try to keep the number of used
785 screen columns small, because many people work in windows with
786 only 80 columns. But make this as wide as the other string
787 above, for non-recent files. */
788 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
789 so be wary of using variable width fields from the locale.
790 Note %b is handled specially by ls and aligned correctly.
791 Note also that specifying a width as in %5b is erroneous as strftime
792 will count bytes rather than characters in multibyte locales. */
796 /* The set of signals that are caught. */
798 static sigset_t caught_signals
;
800 /* If nonzero, the value of the pending fatal signal. */
802 static sig_atomic_t volatile interrupt_signal
;
804 /* A count of the number of pending stop signals that have been received. */
806 static sig_atomic_t volatile stop_signal_count
;
808 /* Desired exit status. */
810 static int exit_status
;
815 /* "ls" had a minor problem. E.g., while processing a directory,
816 ls obtained the name of an entry via readdir, yet was later
817 unable to stat that name. This happens when listing a directory
818 in which entries are actively being removed or renamed. */
819 LS_MINOR_PROBLEM
= 1,
821 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
822 option or failure to stat a command line argument. */
826 /* For long options that have no equivalent short option, use a
827 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
830 AUTHOR_OPTION
= CHAR_MAX
+ 1,
833 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
,
834 FILE_TYPE_INDICATOR_OPTION
,
837 GROUP_DIRECTORIES_FIRST_OPTION
,
840 INDICATOR_STYLE_OPTION
,
841 QUOTING_STYLE_OPTION
,
842 SHOW_CONTROL_CHARS_OPTION
,
850 static struct option
const long_options
[] =
852 {"all", no_argument
, NULL
, 'a'},
853 {"escape", no_argument
, NULL
, 'b'},
854 {"directory", no_argument
, NULL
, 'd'},
855 {"dired", no_argument
, NULL
, 'D'},
856 {"full-time", no_argument
, NULL
, FULL_TIME_OPTION
},
857 {"group-directories-first", no_argument
, NULL
,
858 GROUP_DIRECTORIES_FIRST_OPTION
},
859 {"human-readable", no_argument
, NULL
, 'h'},
860 {"inode", no_argument
, NULL
, 'i'},
861 {"kibibytes", no_argument
, NULL
, 'k'},
862 {"numeric-uid-gid", no_argument
, NULL
, 'n'},
863 {"no-group", no_argument
, NULL
, 'G'},
864 {"hide-control-chars", no_argument
, NULL
, 'q'},
865 {"reverse", no_argument
, NULL
, 'r'},
866 {"size", no_argument
, NULL
, 's'},
867 {"width", required_argument
, NULL
, 'w'},
868 {"almost-all", no_argument
, NULL
, 'A'},
869 {"ignore-backups", no_argument
, NULL
, 'B'},
870 {"classify", optional_argument
, NULL
, 'F'},
871 {"file-type", no_argument
, NULL
, FILE_TYPE_INDICATOR_OPTION
},
872 {"si", no_argument
, NULL
, SI_OPTION
},
873 {"dereference-command-line", no_argument
, NULL
, 'H'},
874 {"dereference-command-line-symlink-to-dir", no_argument
, NULL
,
875 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
},
876 {"hide", required_argument
, NULL
, HIDE_OPTION
},
877 {"ignore", required_argument
, NULL
, 'I'},
878 {"indicator-style", required_argument
, NULL
, INDICATOR_STYLE_OPTION
},
879 {"dereference", no_argument
, NULL
, 'L'},
880 {"literal", no_argument
, NULL
, 'N'},
881 {"quote-name", no_argument
, NULL
, 'Q'},
882 {"quoting-style", required_argument
, NULL
, QUOTING_STYLE_OPTION
},
883 {"recursive", no_argument
, NULL
, 'R'},
884 {"format", required_argument
, NULL
, FORMAT_OPTION
},
885 {"show-control-chars", no_argument
, NULL
, SHOW_CONTROL_CHARS_OPTION
},
886 {"sort", required_argument
, NULL
, SORT_OPTION
},
887 {"tabsize", required_argument
, NULL
, 'T'},
888 {"time", required_argument
, NULL
, TIME_OPTION
},
889 {"time-style", required_argument
, NULL
, TIME_STYLE_OPTION
},
890 {"zero", no_argument
, NULL
, ZERO_OPTION
},
891 {"color", optional_argument
, NULL
, COLOR_OPTION
},
892 {"hyperlink", optional_argument
, NULL
, HYPERLINK_OPTION
},
893 {"block-size", required_argument
, NULL
, BLOCK_SIZE_OPTION
},
894 {"context", no_argument
, 0, 'Z'},
895 {"author", no_argument
, NULL
, AUTHOR_OPTION
},
896 {GETOPT_HELP_OPTION_DECL
},
897 {GETOPT_VERSION_OPTION_DECL
},
901 static char const *const format_args
[] =
903 "verbose", "long", "commas", "horizontal", "across",
904 "vertical", "single-column", NULL
906 static enum format
const format_types
[] =
908 long_format
, long_format
, with_commas
, horizontal
, horizontal
,
909 many_per_line
, one_per_line
911 ARGMATCH_VERIFY (format_args
, format_types
);
913 static char const *const sort_args
[] =
915 "none", "time", "size", "extension", "version", "width", NULL
917 static enum sort_type
const sort_types
[] =
919 sort_none
, sort_time
, sort_size
, sort_extension
, sort_version
, sort_width
921 ARGMATCH_VERIFY (sort_args
, sort_types
);
923 static char const *const time_args
[] =
925 "atime", "access", "use",
927 "mtime", "modification",
931 static enum time_type
const time_types
[] =
933 time_atime
, time_atime
, time_atime
,
934 time_ctime
, time_ctime
,
935 time_mtime
, time_mtime
,
936 time_btime
, time_btime
,
938 ARGMATCH_VERIFY (time_args
, time_types
);
940 static char const *const when_args
[] =
942 /* force and none are for compatibility with another color-ls version */
943 "always", "yes", "force",
944 "never", "no", "none",
945 "auto", "tty", "if-tty", NULL
947 static enum when_type
const when_types
[] =
949 when_always
, when_always
, when_always
,
950 when_never
, when_never
, when_never
,
951 when_if_tty
, when_if_tty
, when_if_tty
953 ARGMATCH_VERIFY (when_args
, when_types
);
955 /* Information about filling a column. */
963 /* Array with information about column filledness. */
964 static struct column_info
*column_info
;
966 /* Maximum number of columns ever possible for this display. */
967 static size_t max_idx
;
969 /* The minimum width of a column is 3: 1 character for the name and 2
970 for the separating white space. */
971 enum { MIN_COLUMN_WIDTH
= 3 };
974 /* This zero-based index is for the --dired option. It is incremented
975 for each byte of output generated by this program so that the beginning
976 and ending indices (in that output) of every file name can be recorded
977 and later output themselves. */
978 static off_t dired_pos
;
981 dired_outbyte (char c
)
987 /* Output the buffer S, of length S_LEN, and increment DIRED_POS by S_LEN. */
989 dired_outbuf (char const *s
, size_t s_len
)
992 fwrite (s
, sizeof *s
, s_len
, stdout
);
995 /* Output the string S, and increment DIRED_POS by its length. */
997 dired_outstring (char const *s
)
999 dired_outbuf (s
, strlen (s
));
1006 dired_outstring (" ");
1009 /* With --dired, store pairs of beginning and ending indices of file names. */
1010 static struct obstack dired_obstack
;
1012 /* With --dired, store pairs of beginning and ending indices of any
1013 directory names that appear as headers (just before 'total' line)
1014 for lists of directory entries. Such directory names are seen when
1015 listing hierarchies using -R and when a directory is listed with at
1016 least one other command line argument. */
1017 static struct obstack subdired_obstack
;
1019 /* Save the current index on the specified obstack, OBS. */
1021 push_current_dired_pos (struct obstack
*obs
)
1024 obstack_grow (obs
, &dired_pos
, sizeof dired_pos
);
1027 /* With -R, this stack is used to help detect directory cycles.
1028 The device/inode pairs on this stack mirror the pairs in the
1029 active_dir_set hash table. */
1030 static struct obstack dev_ino_obstack
;
1032 /* Push a pair onto the device/inode stack. */
1034 dev_ino_push (dev_t dev
, ino_t ino
)
1038 int dev_ino_size
= sizeof *di
;
1039 obstack_blank (&dev_ino_obstack
, dev_ino_size
);
1040 vdi
= obstack_next_free (&dev_ino_obstack
);
1047 /* Pop a dev/ino struct off the global dev_ino_obstack
1048 and return that struct. */
1049 static struct dev_ino
1054 int dev_ino_size
= sizeof *di
;
1055 assert (dev_ino_size
<= obstack_object_size (&dev_ino_obstack
));
1056 obstack_blank_fast (&dev_ino_obstack
, -dev_ino_size
);
1057 vdi
= obstack_next_free (&dev_ino_obstack
);
1063 assert_matching_dev_ino (char const *name
, struct dev_ino di
)
1067 assert (0 <= stat (name
, &sb
));
1068 assert (sb
.st_dev
== di
.st_dev
);
1069 assert (sb
.st_ino
== di
.st_ino
);
1072 static char eolbyte
= '\n';
1074 /* Write to standard output PREFIX, followed by the quoting style and
1075 a space-separated list of the integers stored in OS all on one line. */
1078 dired_dump_obstack (char const *prefix
, struct obstack
*os
)
1082 n_pos
= obstack_object_size (os
) / sizeof (dired_pos
);
1085 off_t
*pos
= obstack_finish (os
);
1086 fputs (prefix
, stdout
);
1087 for (size_t i
= 0; i
< n_pos
; i
++)
1089 intmax_t p
= pos
[i
];
1090 printf (" %"PRIdMAX
, p
);
1096 /* Return the platform birthtime member of the stat structure,
1097 or fallback to the mtime member, which we have populated
1098 from the statx structure or reset to an invalid timestamp
1099 where birth time is not supported. */
1100 static struct timespec
1101 get_stat_btime (struct stat
const *st
)
1103 struct timespec btimespec
;
1105 #if HAVE_STATX && defined STATX_INO
1106 btimespec
= get_stat_mtime (st
);
1108 btimespec
= get_stat_birthtime (st
);
1114 #if HAVE_STATX && defined STATX_INO
1117 time_type_to_statx (void)
1137 calc_req_mask (void)
1139 unsigned int mask
= STATX_MODE
;
1144 if (print_block_size
)
1145 mask
|= STATX_BLOCKS
;
1147 if (format
== long_format
) {
1148 mask
|= STATX_NLINK
| STATX_SIZE
| time_type_to_statx ();
1149 if (print_owner
|| print_author
)
1160 case sort_extension
:
1164 mask
|= time_type_to_statx ();
1177 do_statx (int fd
, char const *name
, struct stat
*st
, int flags
,
1181 bool want_btime
= mask
& STATX_BTIME
;
1182 int ret
= statx (fd
, name
, flags
| AT_NO_AUTOMOUNT
, mask
, &stx
);
1185 statx_to_stat (&stx
, st
);
1186 /* Since we only need one timestamp type,
1187 store birth time in st_mtim. */
1190 if (stx
.stx_mask
& STATX_BTIME
)
1191 st
->st_mtim
= statx_timestamp_to_timespec (stx
.stx_btime
);
1193 st
->st_mtim
.tv_sec
= st
->st_mtim
.tv_nsec
= -1;
1201 do_stat (char const *name
, struct stat
*st
)
1203 return do_statx (AT_FDCWD
, name
, st
, 0, calc_req_mask ());
1207 do_lstat (char const *name
, struct stat
*st
)
1209 return do_statx (AT_FDCWD
, name
, st
, AT_SYMLINK_NOFOLLOW
, calc_req_mask ());
1213 stat_for_mode (char const *name
, struct stat
*st
)
1215 return do_statx (AT_FDCWD
, name
, st
, 0, STATX_MODE
);
1218 /* dev+ino should be static, so no need to sync with backing store */
1220 stat_for_ino (char const *name
, struct stat
*st
)
1222 return do_statx (AT_FDCWD
, name
, st
, 0, STATX_INO
);
1226 fstat_for_ino (int fd
, struct stat
*st
)
1228 return do_statx (fd
, "", st
, AT_EMPTY_PATH
, STATX_INO
);
1232 do_stat (char const *name
, struct stat
*st
)
1234 return stat (name
, st
);
1238 do_lstat (char const *name
, struct stat
*st
)
1240 return lstat (name
, st
);
1244 stat_for_mode (char const *name
, struct stat
*st
)
1246 return stat (name
, st
);
1250 stat_for_ino (char const *name
, struct stat
*st
)
1252 return stat (name
, st
);
1256 fstat_for_ino (int fd
, struct stat
*st
)
1258 return fstat (fd
, st
);
1262 /* Return the address of the first plain %b spec in FMT, or NULL if
1263 there is no such spec. %5b etc. do not match, so that user
1264 widths/flags are honored. */
1268 first_percent_b (char const *fmt
)
1274 case 'b': return fmt
;
1275 case '%': fmt
++; break;
1280 static char RFC3986
[256];
1282 file_escape_init (void)
1284 for (int i
= 0; i
< 256; i
++)
1285 RFC3986
[i
] |= c_isalnum (i
) || i
== '~' || i
== '-' || i
== '.' || i
== '_';
1288 /* Read the abbreviated month names from the locale, to align them
1289 and to determine the max width of the field and to truncate names
1290 greater than our max allowed.
1291 Note even though this handles multibyte locales correctly
1292 it's not restricted to them as single byte locales can have
1293 variable width abbreviated months and also precomputing/caching
1294 the names was seen to increase the performance of ls significantly. */
1296 /* max number of display cells to use.
1297 As of 2018 the abmon for Arabic has entries with width 12.
1298 It doesn't make much sense to support wider than this
1299 and locales should aim for abmon entries of width <= 5. */
1300 enum { MAX_MON_WIDTH
= 12 };
1301 /* abformat[RECENT][MON] is the format to use for timestamps with
1302 recentness RECENT and month MON. */
1303 enum { ABFORMAT_SIZE
= 128 };
1304 static char abformat
[2][12][ABFORMAT_SIZE
];
1305 /* True if precomputed formats should be used. This can be false if
1306 nl_langinfo fails, if a format or month abbreviation is unusually
1307 long, or if a month abbreviation contains '%'. */
1308 static bool use_abformat
;
1310 /* Store into ABMON the abbreviated month names, suitably aligned.
1311 Return true if successful. */
1314 abmon_init (char abmon
[12][ABFORMAT_SIZE
])
1316 #ifndef HAVE_NL_LANGINFO
1319 size_t required_mon_width
= MAX_MON_WIDTH
;
1320 size_t curr_max_width
;
1323 curr_max_width
= required_mon_width
;
1324 required_mon_width
= 0;
1325 for (int i
= 0; i
< 12; i
++)
1327 size_t width
= curr_max_width
;
1328 char const *abbr
= nl_langinfo (ABMON_1
+ i
);
1329 if (strchr (abbr
, '%'))
1331 mbs_align_t alignment
= isdigit (to_uchar (*abbr
))
1332 ? MBS_ALIGN_RIGHT
: MBS_ALIGN_LEFT
;
1333 size_t req
= mbsalign (abbr
, abmon
[i
], ABFORMAT_SIZE
,
1334 &width
, alignment
, 0);
1335 if (! (req
< ABFORMAT_SIZE
))
1337 required_mon_width
= MAX (required_mon_width
, width
);
1340 while (curr_max_width
> required_mon_width
);
1346 /* Initialize ABFORMAT and USE_ABFORMAT. */
1349 abformat_init (void)
1352 for (int recent
= 0; recent
< 2; recent
++)
1353 pb
[recent
] = first_percent_b (long_time_format
[recent
]);
1354 if (! (pb
[0] || pb
[1]))
1357 char abmon
[12][ABFORMAT_SIZE
];
1358 if (! abmon_init (abmon
))
1361 for (int recent
= 0; recent
< 2; recent
++)
1363 char const *fmt
= long_time_format
[recent
];
1364 for (int i
= 0; i
< 12; i
++)
1366 char *nfmt
= abformat
[recent
][i
];
1370 nbytes
= snprintf (nfmt
, ABFORMAT_SIZE
, "%s", fmt
);
1373 if (! (pb
[recent
] - fmt
<= MIN (ABFORMAT_SIZE
, INT_MAX
)))
1375 int prefix_len
= pb
[recent
] - fmt
;
1376 nbytes
= snprintf (nfmt
, ABFORMAT_SIZE
, "%.*s%s%s",
1377 prefix_len
, fmt
, abmon
[i
], pb
[recent
] + 2);
1380 if (! (0 <= nbytes
&& nbytes
< ABFORMAT_SIZE
))
1385 use_abformat
= true;
1389 dev_ino_hash (void const *x
, size_t table_size
)
1391 struct dev_ino
const *p
= x
;
1392 return (uintmax_t) p
->st_ino
% table_size
;
1396 dev_ino_compare (void const *x
, void const *y
)
1398 struct dev_ino
const *a
= x
;
1399 struct dev_ino
const *b
= y
;
1400 return SAME_INODE (*a
, *b
) ? true : false;
1404 dev_ino_free (void *x
)
1409 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1410 active directories. Return true if there is already a matching
1411 entry in the table. */
1414 visit_dir (dev_t dev
, ino_t ino
)
1416 struct dev_ino
*ent
;
1417 struct dev_ino
*ent_from_table
;
1420 ent
= xmalloc (sizeof *ent
);
1424 /* Attempt to insert this entry into the table. */
1425 ent_from_table
= hash_insert (active_dir_set
, ent
);
1427 if (ent_from_table
== NULL
)
1429 /* Insertion failed due to lack of memory. */
1433 found_match
= (ent_from_table
!= ent
);
1437 /* ent was not inserted, so free it. */
1445 free_pending_ent (struct pending
*p
)
1453 is_colored (enum indicator_no type
)
1455 size_t len
= color_indicator
[type
].len
;
1456 char const *s
= color_indicator
[type
].string
;
1458 || (len
== 1 && STRNCMP_LIT (s
, "0") == 0)
1459 || (len
== 2 && STRNCMP_LIT (s
, "00") == 0));
1463 restore_default_color (void)
1465 put_indicator (&color_indicator
[C_LEFT
]);
1466 put_indicator (&color_indicator
[C_RIGHT
]);
1470 set_normal_color (void)
1472 if (print_with_color
&& is_colored (C_NORM
))
1474 put_indicator (&color_indicator
[C_LEFT
]);
1475 put_indicator (&color_indicator
[C_NORM
]);
1476 put_indicator (&color_indicator
[C_RIGHT
]);
1480 /* An ordinary signal was received; arrange for the program to exit. */
1483 sighandler (int sig
)
1486 signal (sig
, SIG_IGN
);
1487 if (! interrupt_signal
)
1488 interrupt_signal
= sig
;
1491 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1494 stophandler (int sig
)
1497 signal (sig
, stophandler
);
1498 if (! interrupt_signal
)
1499 stop_signal_count
++;
1502 /* Process any pending signals. If signals are caught, this function
1503 should be called periodically. Ideally there should never be an
1504 unbounded amount of time when signals are not being processed.
1505 Signal handling can restore the default colors, so callers must
1506 immediately change colors after invoking this function. */
1509 process_signals (void)
1511 while (interrupt_signal
|| stop_signal_count
)
1518 restore_default_color ();
1521 sigprocmask (SIG_BLOCK
, &caught_signals
, &oldset
);
1523 /* Reload interrupt_signal and stop_signal_count, in case a new
1524 signal was handled before sigprocmask took effect. */
1525 sig
= interrupt_signal
;
1526 stops
= stop_signal_count
;
1528 /* SIGTSTP is special, since the application can receive that signal
1529 more than once. In this case, don't set the signal handler to the
1530 default. Instead, just raise the uncatchable SIGSTOP. */
1533 stop_signal_count
= stops
- 1;
1537 signal (sig
, SIG_DFL
);
1539 /* Exit or suspend the program. */
1541 sigprocmask (SIG_SETMASK
, &oldset
, NULL
);
1543 /* If execution reaches here, then the program has been
1544 continued (after being suspended). */
1548 /* Setup signal handlers if INIT is true,
1549 otherwise restore to the default. */
1552 signal_setup (bool init
)
1554 /* The signals that are trapped, and the number of such signals. */
1555 static int const sig
[] =
1557 /* This one is handled specially. */
1560 /* The usual suspects. */
1561 SIGALRM
, SIGHUP
, SIGINT
, SIGPIPE
, SIGQUIT
, SIGTERM
,
1578 enum { nsigs
= ARRAY_CARDINALITY (sig
) };
1581 static bool caught_sig
[nsigs
];
1589 struct sigaction act
;
1591 sigemptyset (&caught_signals
);
1592 for (j
= 0; j
< nsigs
; j
++)
1594 sigaction (sig
[j
], NULL
, &act
);
1595 if (act
.sa_handler
!= SIG_IGN
)
1596 sigaddset (&caught_signals
, sig
[j
]);
1599 act
.sa_mask
= caught_signals
;
1600 act
.sa_flags
= SA_RESTART
;
1602 for (j
= 0; j
< nsigs
; j
++)
1603 if (sigismember (&caught_signals
, sig
[j
]))
1605 act
.sa_handler
= sig
[j
] == SIGTSTP
? stophandler
: sighandler
;
1606 sigaction (sig
[j
], &act
, NULL
);
1609 for (j
= 0; j
< nsigs
; j
++)
1611 caught_sig
[j
] = (signal (sig
[j
], SIG_IGN
) != SIG_IGN
);
1614 signal (sig
[j
], sig
[j
] == SIGTSTP
? stophandler
: sighandler
);
1615 siginterrupt (sig
[j
], 0);
1623 for (j
= 0; j
< nsigs
; j
++)
1624 if (sigismember (&caught_signals
, sig
[j
]))
1625 signal (sig
[j
], SIG_DFL
);
1627 for (j
= 0; j
< nsigs
; j
++)
1629 signal (sig
[j
], SIG_DFL
);
1637 signal_setup (true);
1641 signal_restore (void)
1643 signal_setup (false);
1647 main (int argc
, char **argv
)
1650 struct pending
*thispend
;
1653 initialize_main (&argc
, &argv
);
1654 set_program_name (argv
[0]);
1655 setlocale (LC_ALL
, "");
1656 bindtextdomain (PACKAGE
, LOCALEDIR
);
1657 textdomain (PACKAGE
);
1659 initialize_exit_failure (LS_FAILURE
);
1660 atexit (close_stdout
);
1662 assert (ARRAY_CARDINALITY (color_indicator
) + 1
1663 == ARRAY_CARDINALITY (indicator_name
));
1665 exit_status
= EXIT_SUCCESS
;
1666 print_dir_name
= true;
1667 pending_dirs
= NULL
;
1669 current_time
.tv_sec
= TYPE_MINIMUM (time_t);
1670 current_time
.tv_nsec
= -1;
1672 i
= decode_switches (argc
, argv
);
1674 if (print_with_color
)
1677 /* Test print_with_color again, because the call to parse_ls_color
1678 may have just reset it -- e.g., if LS_COLORS is invalid. */
1680 if (print_with_color
)
1682 /* Don't use TAB characters in output. Some terminal
1683 emulators can't handle the combination of tabs and
1684 color codes on the same line. */
1688 if (directories_first
)
1689 check_symlink_mode
= true;
1690 else if (print_with_color
)
1692 /* Avoid following symbolic links when possible. */
1693 if (is_colored (C_ORPHAN
)
1694 || (is_colored (C_EXEC
) && color_symlink_as_referent
)
1695 || (is_colored (C_MISSING
) && format
== long_format
))
1696 check_symlink_mode
= true;
1699 if (dereference
== DEREF_UNDEFINED
)
1700 dereference
= ((immediate_dirs
1701 || indicator_style
== classify
1702 || format
== long_format
)
1704 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR
);
1706 /* When using -R, initialize a data structure we'll use to
1707 detect any directory cycles. */
1710 active_dir_set
= hash_initialize (INITIAL_TABLE_SIZE
, NULL
,
1714 if (active_dir_set
== NULL
)
1717 obstack_init (&dev_ino_obstack
);
1720 localtz
= tzalloc (getenv ("TZ"));
1722 format_needs_stat
= sort_type
== sort_time
|| sort_type
== sort_size
1723 || format
== long_format
1725 || print_block_size
;
1726 format_needs_type
= (! format_needs_stat
1729 || indicator_style
!= none
1730 || directories_first
));
1734 obstack_init (&dired_obstack
);
1735 obstack_init (&subdired_obstack
);
1738 if (print_hyperlink
)
1740 file_escape_init ();
1742 hostname
= xgethostname ();
1743 /* The hostname is generally ignored,
1744 so ignore failures obtaining it. */
1750 cwd_file
= xnmalloc (cwd_n_alloc
, sizeof *cwd_file
);
1760 gobble_file (".", directory
, NOT_AN_INODE_NUMBER
, true, "");
1762 queue_directory (".", NULL
, true);
1766 gobble_file (argv
[i
++], unknown
, NOT_AN_INODE_NUMBER
, true, "");
1772 if (!immediate_dirs
)
1773 extract_dirs_from_files (NULL
, true);
1774 /* 'cwd_n_used' might be zero now. */
1777 /* In the following if/else blocks, it is sufficient to test 'pending_dirs'
1778 (and not pending_dirs->name) because there may be no markers in the queue
1779 at this point. A marker may be enqueued when extract_dirs_from_files is
1780 called with a non-empty string or via print_dir. */
1783 print_current_files ();
1785 dired_outbyte ('\n');
1787 else if (n_files
<= 1 && pending_dirs
&& pending_dirs
->next
== 0)
1788 print_dir_name
= false;
1790 while (pending_dirs
)
1792 thispend
= pending_dirs
;
1793 pending_dirs
= pending_dirs
->next
;
1797 if (thispend
->name
== NULL
)
1799 /* thispend->name == NULL means this is a marker entry
1800 indicating we've finished processing the directory.
1801 Use its dev/ino numbers to remove the corresponding
1802 entry from the active_dir_set hash table. */
1803 struct dev_ino di
= dev_ino_pop ();
1804 struct dev_ino
*found
= hash_remove (active_dir_set
, &di
);
1806 assert_matching_dev_ino (thispend
->realname
, di
);
1808 dev_ino_free (found
);
1809 free_pending_ent (thispend
);
1814 print_dir (thispend
->name
, thispend
->realname
,
1815 thispend
->command_line_arg
);
1817 free_pending_ent (thispend
);
1818 print_dir_name
= true;
1821 if (print_with_color
&& used_color
)
1825 /* Skip the restore when it would be a no-op, i.e.,
1826 when left is "\033[" and right is "m". */
1827 if (!(color_indicator
[C_LEFT
].len
== 2
1828 && memcmp (color_indicator
[C_LEFT
].string
, "\033[", 2) == 0
1829 && color_indicator
[C_RIGHT
].len
== 1
1830 && color_indicator
[C_RIGHT
].string
[0] == 'm'))
1831 restore_default_color ();
1837 /* Act on any signals that arrived before the default was restored.
1838 This can process signals out of order, but there doesn't seem to
1839 be an easy way to do them in order, and the order isn't that
1840 important anyway. */
1841 for (j
= stop_signal_count
; j
; j
--)
1843 j
= interrupt_signal
;
1850 /* No need to free these since we're about to exit. */
1851 dired_dump_obstack ("//DIRED//", &dired_obstack
);
1852 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack
);
1853 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1854 quoting_style_args
[get_quoting_style (filename_quoting_options
)]);
1859 assert (hash_get_n_entries (active_dir_set
) == 0);
1860 hash_free (active_dir_set
);
1866 /* Return the line length indicated by the value given by SPEC, or -1
1867 if unsuccessful. 0 means no limit on line length. */
1870 decode_line_length (char const *spec
)
1874 /* Treat too-large values as if they were 0, which is
1875 effectively infinity. */
1876 switch (xstrtoumax (spec
, NULL
, 0, &val
, ""))
1879 return val
<= MIN (PTRDIFF_MAX
, SIZE_MAX
) ? val
: 0;
1881 case LONGINT_OVERFLOW
:
1889 /* Return true if standard output is a tty, caching the result. */
1892 stdout_isatty (void)
1894 static signed char out_tty
= -1;
1896 out_tty
= isatty (STDOUT_FILENO
);
1897 assume (out_tty
== 0 || out_tty
== 1);
1901 /* Set all the option flags according to the switches specified.
1902 Return the index of the first non-option argument. */
1905 decode_switches (int argc
, char **argv
)
1907 char *time_style_option
= NULL
;
1909 /* These variables are false or -1 unless a switch says otherwise. */
1910 bool kibibytes_specified
= false;
1911 int format_opt
= -1;
1912 int hide_control_chars_opt
= -1;
1913 int quoting_style_opt
= -1;
1915 ptrdiff_t tabsize_opt
= -1;
1916 ptrdiff_t width_opt
= -1;
1921 int c
= getopt_long (argc
, argv
,
1922 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1930 ignore_mode
= IGNORE_MINIMAL
;
1934 quoting_style_opt
= escape_quoting_style
;
1938 time_type
= time_ctime
;
1942 immediate_dirs
= true;
1946 /* Same as -a -U -1 --color=none --hyperlink=none,
1947 while disabling -s. */
1948 ignore_mode
= IGNORE_MINIMAL
;
1949 sort_opt
= sort_none
;
1950 if (format_opt
== long_format
)
1952 print_with_color
= false;
1953 print_hyperlink
= false;
1954 print_block_size
= false;
1957 case FILE_TYPE_INDICATOR_OPTION
: /* --file-type */
1958 indicator_style
= file_type
;
1962 format_opt
= long_format
;
1963 print_owner
= false;
1967 file_human_output_opts
= human_output_opts
=
1968 human_autoscale
| human_SI
| human_base_1024
;
1969 file_output_block_size
= output_block_size
= 1;
1977 kibibytes_specified
= true;
1981 format_opt
= long_format
;
1985 format_opt
= with_commas
;
1990 format_opt
= long_format
;
1993 case 'o': /* Just like -l, but don't display group info. */
1994 format_opt
= long_format
;
1995 print_group
= false;
1999 indicator_style
= slash
;
2003 hide_control_chars_opt
= true;
2007 sort_reverse
= true;
2011 print_block_size
= true;
2015 sort_opt
= sort_time
;
2019 time_type
= time_atime
;
2023 sort_opt
= sort_version
;
2027 width_opt
= decode_line_length (optarg
);
2029 die (LS_FAILURE
, 0, "%s: %s", _("invalid line width"),
2034 format_opt
= horizontal
;
2038 ignore_mode
= IGNORE_DOT_AND_DOTDOT
;
2042 add_ignore_pattern ("*~");
2043 add_ignore_pattern (".*~");
2047 format_opt
= many_per_line
;
2058 i
= XARGMATCH ("--classify", optarg
, when_args
, when_types
);
2060 /* Using --classify with no argument is equivalent to using
2061 --classify=always. */
2064 if (i
== when_always
|| (i
== when_if_tty
&& stdout_isatty ()))
2065 indicator_style
= classify
;
2069 case 'G': /* inhibit display of group info */
2070 print_group
= false;
2074 dereference
= DEREF_COMMAND_LINE_ARGUMENTS
;
2077 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
:
2078 dereference
= DEREF_COMMAND_LINE_SYMLINK_TO_DIR
;
2082 add_ignore_pattern (optarg
);
2086 dereference
= DEREF_ALWAYS
;
2090 quoting_style_opt
= literal_quoting_style
;
2094 quoting_style_opt
= c_quoting_style
;
2102 sort_opt
= sort_size
;
2106 tabsize_opt
= xnumtoumax (optarg
, 0, 0, MIN (PTRDIFF_MAX
, SIZE_MAX
),
2107 "", _("invalid tab size"), LS_FAILURE
);
2111 sort_opt
= sort_none
;
2115 sort_opt
= sort_extension
;
2119 /* -1 has no effect after -l. */
2120 if (format_opt
!= long_format
)
2121 format_opt
= one_per_line
;
2125 print_author
= true;
2130 struct ignore_pattern
*hide
= xmalloc (sizeof *hide
);
2131 hide
->pattern
= optarg
;
2132 hide
->next
= hide_patterns
;
2133 hide_patterns
= hide
;
2138 sort_opt
= XARGMATCH ("--sort", optarg
, sort_args
, sort_types
);
2141 case GROUP_DIRECTORIES_FIRST_OPTION
:
2142 directories_first
= true;
2146 time_type
= XARGMATCH ("--time", optarg
, time_args
, time_types
);
2150 format_opt
= XARGMATCH ("--format", optarg
, format_args
,
2154 case FULL_TIME_OPTION
:
2155 format_opt
= long_format
;
2156 time_style_option
= bad_cast ("full-iso");
2163 i
= XARGMATCH ("--color", optarg
, when_args
, when_types
);
2165 /* Using --color with no argument is equivalent to using
2169 print_with_color
= (i
== when_always
2170 || (i
== when_if_tty
&& stdout_isatty ()));
2174 case HYPERLINK_OPTION
:
2178 i
= XARGMATCH ("--hyperlink", optarg
, when_args
, when_types
);
2180 /* Using --hyperlink with no argument is equivalent to using
2181 --hyperlink=always. */
2184 print_hyperlink
= (i
== when_always
2185 || (i
== when_if_tty
&& stdout_isatty ()));
2189 case INDICATOR_STYLE_OPTION
:
2190 indicator_style
= XARGMATCH ("--indicator-style", optarg
,
2191 indicator_style_args
,
2192 indicator_style_types
);
2195 case QUOTING_STYLE_OPTION
:
2196 quoting_style_opt
= XARGMATCH ("--quoting-style", optarg
,
2198 quoting_style_vals
);
2201 case TIME_STYLE_OPTION
:
2202 time_style_option
= optarg
;
2205 case SHOW_CONTROL_CHARS_OPTION
:
2206 hide_control_chars_opt
= false;
2209 case BLOCK_SIZE_OPTION
:
2211 enum strtol_error e
= human_options (optarg
, &human_output_opts
,
2212 &output_block_size
);
2213 if (e
!= LONGINT_OK
)
2214 xstrtol_fatal (e
, oi
, 0, long_options
, optarg
);
2215 file_human_output_opts
= human_output_opts
;
2216 file_output_block_size
= output_block_size
;
2221 file_human_output_opts
= human_output_opts
=
2222 human_autoscale
| human_SI
;
2223 file_output_block_size
= output_block_size
= 1;
2227 print_scontext
= true;
2232 hide_control_chars_opt
= false;
2233 if (format_opt
!= long_format
)
2234 format_opt
= one_per_line
;
2235 print_with_color
= false;
2236 quoting_style_opt
= literal_quoting_style
;
2239 case_GETOPT_HELP_CHAR
;
2241 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
2248 if (! output_block_size
)
2250 char const *ls_block_size
= getenv ("LS_BLOCK_SIZE");
2251 human_options (ls_block_size
,
2252 &human_output_opts
, &output_block_size
);
2253 if (ls_block_size
|| getenv ("BLOCK_SIZE"))
2255 file_human_output_opts
= human_output_opts
;
2256 file_output_block_size
= output_block_size
;
2258 if (kibibytes_specified
)
2260 human_output_opts
= 0;
2261 output_block_size
= 1024;
2265 format
= (0 <= format_opt
? format_opt
2266 : ls_mode
== LS_LS
? (stdout_isatty ()
2267 ? many_per_line
: one_per_line
)
2268 : ls_mode
== LS_MULTI_COL
? many_per_line
2269 : /* ls_mode == LS_LONG_FORMAT */ long_format
);
2271 /* If the line length was not set by a switch but is needed to determine
2272 output, go to the work of obtaining it from the environment. */
2273 ptrdiff_t linelen
= width_opt
;
2274 if (format
== many_per_line
|| format
== horizontal
|| format
== with_commas
2275 || print_with_color
)
2280 /* Suppress bogus warning re comparing ws.ws_col to big integer. */
2281 # if 4 < __GNUC__ + (6 <= __GNUC_MINOR__)
2282 # pragma GCC diagnostic push
2283 # pragma GCC diagnostic ignored "-Wtype-limits"
2286 if (stdout_isatty ()
2287 && 0 <= ioctl (STDOUT_FILENO
, TIOCGWINSZ
, &ws
)
2289 linelen
= ws
.ws_col
<= MIN (PTRDIFF_MAX
, SIZE_MAX
) ? ws
.ws_col
: 0;
2290 # if 4 < __GNUC__ + (6 <= __GNUC_MINOR__)
2291 # pragma GCC diagnostic pop
2297 char const *p
= getenv ("COLUMNS");
2300 linelen
= decode_line_length (p
);
2303 _("ignoring invalid width"
2304 " in environment variable COLUMNS: %s"),
2310 line_length
= linelen
< 0 ? 80 : linelen
;
2312 /* Determine the max possible number of display columns. */
2313 max_idx
= line_length
/ MIN_COLUMN_WIDTH
;
2314 /* Account for first display column not having a separator,
2315 or line_lengths shorter than MIN_COLUMN_WIDTH. */
2316 max_idx
+= line_length
% MIN_COLUMN_WIDTH
!= 0;
2318 if (format
== many_per_line
|| format
== horizontal
|| format
== with_commas
)
2320 if (0 <= tabsize_opt
)
2321 tabsize
= tabsize_opt
;
2325 char const *p
= getenv ("TABSIZE");
2329 if (xstrtoumax (p
, NULL
, 0, &tmp
, "") == LONGINT_OK
2334 _("ignoring invalid tab size"
2335 " in environment variable TABSIZE: %s"),
2341 qmark_funny_chars
= (hide_control_chars_opt
< 0
2342 ? ls_mode
== LS_LS
&& stdout_isatty ()
2343 : hide_control_chars_opt
);
2345 int qs
= quoting_style_opt
;
2347 qs
= getenv_quoting_style ();
2349 qs
= (ls_mode
== LS_LS
2350 ? (stdout_isatty () ? shell_escape_quoting_style
: -1)
2351 : escape_quoting_style
);
2353 set_quoting_style (NULL
, qs
);
2354 qs
= get_quoting_style (NULL
);
2355 align_variable_outer_quotes
2356 = ((format
== long_format
2357 || ((format
== many_per_line
|| format
== horizontal
) && line_length
))
2358 && (qs
== shell_quoting_style
2359 || qs
== shell_escape_quoting_style
2360 || qs
== c_maybe_quoting_style
));
2361 filename_quoting_options
= clone_quoting_options (NULL
);
2362 if (qs
== escape_quoting_style
)
2363 set_char_quoting (filename_quoting_options
, ' ', 1);
2364 if (file_type
<= indicator_style
)
2367 for (p
= &"*=>@|"[indicator_style
- file_type
]; *p
; p
++)
2368 set_char_quoting (filename_quoting_options
, *p
, 1);
2371 dirname_quoting_options
= clone_quoting_options (NULL
);
2372 set_char_quoting (dirname_quoting_options
, ':', 1);
2374 /* --dired is meaningful only with --format=long (-l) and sans --hyperlink.
2375 Otherwise, ignore it. FIXME: warn about this?
2376 Alternatively, make --dired imply --format=long? */
2377 dired
&= (format
== long_format
) & !print_hyperlink
;
2379 if (eolbyte
< dired
)
2380 die (LS_FAILURE
, 0, _("--dired and --zero are incompatible"));
2382 /* If -c or -u is specified and not -l (or any other option that implies -l),
2383 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
2384 The behavior of ls when using either -c or -u but with neither -l nor -t
2385 appears to be unspecified by POSIX. So, with GNU ls, '-u' alone means
2386 sort by atime (this is the one that's not specified by the POSIX spec),
2387 -lu means show atime and sort by name, -lut means show atime and sort
2390 sort_type
= (0 <= sort_opt
? sort_opt
2391 : (format
!= long_format
2392 && (time_type
== time_ctime
|| time_type
== time_atime
2393 || time_type
== time_btime
))
2394 ? sort_time
: sort_name
);
2396 if (format
== long_format
)
2398 char *style
= time_style_option
;
2399 static char const posix_prefix
[] = "posix-";
2402 if (! (style
= getenv ("TIME_STYLE")))
2403 style
= bad_cast ("locale");
2405 while (STREQ_LEN (style
, posix_prefix
, sizeof posix_prefix
- 1))
2407 if (! hard_locale (LC_TIME
))
2409 style
+= sizeof posix_prefix
- 1;
2414 char *p0
= style
+ 1;
2415 char *p1
= strchr (p0
, '\n');
2420 if (strchr (p1
+ 1, '\n'))
2421 die (LS_FAILURE
, 0, _("invalid time style format %s"),
2425 long_time_format
[0] = p0
;
2426 long_time_format
[1] = p1
;
2430 ptrdiff_t res
= argmatch (style
, time_style_args
,
2431 (char const *) time_style_types
,
2432 sizeof (*time_style_types
));
2435 /* This whole block used to be a simple use of XARGMATCH.
2436 but that didn't print the "posix-"-prefixed variants or
2437 the "+"-prefixed format string option upon failure. */
2438 argmatch_invalid ("time style", style
, res
);
2440 /* The following is a manual expansion of argmatch_valid,
2441 but with the added "+ ..." description and the [posix-]
2442 prefixes prepended. Note that this simplification works
2443 only because all four existing time_style_types values
2445 fputs (_("Valid arguments are:\n"), stderr
);
2446 char const *const *p
= time_style_args
;
2448 fprintf (stderr
, " - [posix-]%s\n", *p
++);
2449 fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
2450 " format\n"), stderr
);
2455 case full_iso_time_style
:
2456 long_time_format
[0] = long_time_format
[1] =
2457 "%Y-%m-%d %H:%M:%S.%N %z";
2460 case long_iso_time_style
:
2461 long_time_format
[0] = long_time_format
[1] = "%Y-%m-%d %H:%M";
2464 case iso_time_style
:
2465 long_time_format
[0] = "%Y-%m-%d ";
2466 long_time_format
[1] = "%m-%d %H:%M";
2469 case locale_time_style
:
2470 if (hard_locale (LC_TIME
))
2472 for (int i
= 0; i
< 2; i
++)
2473 long_time_format
[i
] =
2474 dcgettext (NULL
, long_time_format
[i
], LC_TIME
);
2485 /* Parse a string as part of the LS_COLORS variable; this may involve
2486 decoding all kinds of escape characters. If equals_end is set an
2487 unescaped equal sign ends the string, otherwise only a : or \0
2488 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2491 The resulting string is *not* null-terminated, but may contain
2494 Note that both dest and src are char **; on return they point to
2495 the first free byte after the array and the character that ended
2496 the input string, respectively. */
2499 get_funky_string (char **dest
, char const **src
, bool equals_end
,
2500 size_t *output_count
)
2502 char num
; /* For numerical codes */
2503 size_t count
; /* Something to count with */
2505 ST_GND
, ST_BACKSLASH
, ST_OCTAL
, ST_HEX
, ST_CARET
, ST_END
, ST_ERROR
2510 p
= *src
; /* We don't want to double-indirect */
2511 q
= *dest
; /* the whole darn time. */
2513 count
= 0; /* No characters counted in yet. */
2516 state
= ST_GND
; /* Start in ground state. */
2517 while (state
< ST_END
)
2521 case ST_GND
: /* Ground state (no escapes) */
2526 state
= ST_END
; /* End of string */
2529 state
= ST_BACKSLASH
; /* Backslash escape sequence */
2533 state
= ST_CARET
; /* Caret escape */
2539 state
= ST_END
; /* End */
2550 case ST_BACKSLASH
: /* Backslash escaped character */
2561 state
= ST_OCTAL
; /* Octal sequence */
2566 state
= ST_HEX
; /* Hex sequence */
2569 case 'a': /* Bell */
2572 case 'b': /* Backspace */
2575 case 'e': /* Escape */
2578 case 'f': /* Form feed */
2581 case 'n': /* Newline */
2584 case 'r': /* Carriage return */
2590 case 'v': /* Vtab */
2593 case '?': /* Delete */
2596 case '_': /* Space */
2599 case '\0': /* End of string */
2600 state
= ST_ERROR
; /* Error! */
2602 default: /* Escaped character like \ ^ : = */
2606 if (state
== ST_BACKSLASH
)
2615 case ST_OCTAL
: /* Octal sequence */
2616 if (*p
< '0' || *p
> '7')
2623 num
= (num
<< 3) + (*(p
++) - '0');
2626 case ST_HEX
: /* Hex sequence */
2639 num
= (num
<< 4) + (*(p
++) - '0');
2647 num
= (num
<< 4) + (*(p
++) - 'a') + 10;
2655 num
= (num
<< 4) + (*(p
++) - 'A') + 10;
2665 case ST_CARET
: /* Caret escape */
2666 state
= ST_GND
; /* Should be the next state... */
2667 if (*p
>= '@' && *p
<= '~')
2669 *(q
++) = *(p
++) & 037;
2688 *output_count
= count
;
2690 return state
!= ST_ERROR
;
2704 /* Check if the content of TERM is a valid name in dircolors. */
2707 known_term_type (void)
2709 char const *term
= getenv ("TERM");
2710 if (! term
|| ! *term
)
2713 char const *line
= G_line
;
2714 while (line
- G_line
< sizeof (G_line
))
2716 if (STRNCMP_LIT (line
, "TERM ") == 0)
2718 if (fnmatch (line
+ 5, term
, 0) == 0)
2721 line
+= strlen (line
) + 1;
2728 parse_ls_color (void)
2730 char const *p
; /* Pointer to character being parsed */
2731 char *buf
; /* color_buf buffer pointer */
2732 int ind_no
; /* Indicator number */
2733 char label
[3]; /* Indicator label */
2734 struct color_ext_type
*ext
; /* Extension we are working on */
2736 if ((p
= getenv ("LS_COLORS")) == NULL
|| *p
== '\0')
2738 /* LS_COLORS takes precedence, but if that's not set then
2739 honor the COLORTERM and TERM env variables so that
2740 we only go with the internal ANSI color codes if the
2741 former is non empty or the latter is set to a known value. */
2742 char const *colorterm
= getenv ("COLORTERM");
2743 if (! (colorterm
&& *colorterm
) && ! known_term_type ())
2744 print_with_color
= false;
2749 strcpy (label
, "??");
2751 /* This is an overly conservative estimate, but any possible
2752 LS_COLORS string will *not* generate a color_buf longer than
2753 itself, so it is a safe way of allocating a buffer in
2755 buf
= color_buf
= xstrdup (p
);
2757 enum parse_state state
= PS_START
;
2762 case PS_START
: /* First label character */
2770 /* Allocate new extension block and add to head of
2771 linked list (this way a later definition will
2772 override an earlier one, which can be useful for
2773 having terminal-specific defs override global). */
2775 ext
= xmalloc (sizeof *ext
);
2776 ext
->next
= color_ext_list
;
2777 color_ext_list
= ext
;
2780 ext
->ext
.string
= buf
;
2782 state
= (get_funky_string (&buf
, &p
, true, &ext
->ext
.len
)
2787 state
= PS_DONE
; /* Done! */
2790 default: /* Assume it is file type label */
2797 case PS_2
: /* Second label character */
2804 state
= PS_FAIL
; /* Error */
2807 case PS_3
: /* Equal sign after indicator label */
2808 state
= PS_FAIL
; /* Assume failure... */
2809 if (*(p
++) == '=')/* It *should* be... */
2811 for (ind_no
= 0; indicator_name
[ind_no
] != NULL
; ++ind_no
)
2813 if (STREQ (label
, indicator_name
[ind_no
]))
2815 color_indicator
[ind_no
].string
= buf
;
2816 state
= (get_funky_string (&buf
, &p
, false,
2817 &color_indicator
[ind_no
].len
)
2818 ? PS_START
: PS_FAIL
);
2822 if (state
== PS_FAIL
)
2823 error (0, 0, _("unrecognized prefix: %s"), quote (label
));
2827 case PS_4
: /* Equal sign after *.ext */
2830 ext
->seq
.string
= buf
;
2831 state
= (get_funky_string (&buf
, &p
, false, &ext
->seq
.len
)
2832 ? PS_START
: PS_FAIL
);
2847 if (state
== PS_FAIL
)
2849 struct color_ext_type
*e
;
2850 struct color_ext_type
*e2
;
2853 _("unparsable value for LS_COLORS environment variable"));
2855 for (e
= color_ext_list
; e
!= NULL
; /* empty */)
2861 print_with_color
= false;
2864 if (color_indicator
[C_LINK
].len
== 6
2865 && !STRNCMP_LIT (color_indicator
[C_LINK
].string
, "target"))
2866 color_symlink_as_referent
= true;
2869 /* Return the quoting style specified by the environment variable
2870 QUOTING_STYLE if set and valid, -1 otherwise. */
2873 getenv_quoting_style (void)
2875 char const *q_style
= getenv ("QUOTING_STYLE");
2878 int i
= ARGMATCH (q_style
, quoting_style_args
, quoting_style_vals
);
2882 _("ignoring invalid value"
2883 " of environment variable QUOTING_STYLE: %s"),
2887 return quoting_style_vals
[i
];
2890 /* Set the exit status to report a failure. If SERIOUS, it is a
2891 serious failure; otherwise, it is merely a minor problem. */
2894 set_exit_status (bool serious
)
2897 exit_status
= LS_FAILURE
;
2898 else if (exit_status
== EXIT_SUCCESS
)
2899 exit_status
= LS_MINOR_PROBLEM
;
2902 /* Assuming a failure is serious if SERIOUS, use the printf-style
2903 MESSAGE to report the failure to access a file named FILE. Assume
2904 errno is set appropriately for the failure. */
2907 file_failure (bool serious
, char const *message
, char const *file
)
2909 error (0, errno
, message
, quoteaf (file
));
2910 set_exit_status (serious
);
2913 /* Request that the directory named NAME have its contents listed later.
2914 If REALNAME is nonzero, it will be used instead of NAME when the
2915 directory name is printed. This allows symbolic links to directories
2916 to be treated as regular directories but still be listed under their
2917 real names. NAME == NULL is used to insert a marker entry for the
2918 directory named in REALNAME.
2919 If NAME is non-NULL, we use its dev/ino information to save
2920 a call to stat -- when doing a recursive (-R) traversal.
2921 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2924 queue_directory (char const *name
, char const *realname
, bool command_line_arg
)
2926 struct pending
*new = xmalloc (sizeof *new);
2927 new->realname
= realname
? xstrdup (realname
) : NULL
;
2928 new->name
= name
? xstrdup (name
) : NULL
;
2929 new->command_line_arg
= command_line_arg
;
2930 new->next
= pending_dirs
;
2934 /* Read directory NAME, and list the files in it.
2935 If REALNAME is nonzero, print its name instead of NAME;
2936 this is used for symbolic links to directories.
2937 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2940 print_dir (char const *name
, char const *realname
, bool command_line_arg
)
2943 struct dirent
*next
;
2944 uintmax_t total_blocks
= 0;
2945 static bool first
= true;
2948 dirp
= opendir (name
);
2951 file_failure (command_line_arg
, _("cannot open directory %s"), name
);
2957 struct stat dir_stat
;
2958 int fd
= dirfd (dirp
);
2960 /* If dirfd failed, endure the overhead of stat'ing by path */
2962 ? fstat_for_ino (fd
, &dir_stat
)
2963 : stat_for_ino (name
, &dir_stat
)) < 0)
2965 file_failure (command_line_arg
,
2966 _("cannot determine device and inode of %s"), name
);
2971 /* If we've already visited this dev/inode pair, warn that
2972 we've found a loop, and do not process this directory. */
2973 if (visit_dir (dir_stat
.st_dev
, dir_stat
.st_ino
))
2975 error (0, 0, _("%s: not listing already-listed directory"),
2978 set_exit_status (true);
2982 dev_ino_push (dir_stat
.st_dev
, dir_stat
.st_ino
);
2987 if (recursive
|| print_dir_name
)
2990 dired_outbyte ('\n');
2994 char *absolute_name
= NULL
;
2995 if (print_hyperlink
)
2997 absolute_name
= canonicalize_filename_mode (name
, CAN_MISSING
);
2998 if (! absolute_name
)
2999 file_failure (command_line_arg
,
3000 _("error canonicalizing %s"), name
);
3002 quote_name (realname
? realname
: name
, dirname_quoting_options
, -1,
3003 NULL
, true, &subdired_obstack
, absolute_name
);
3005 free (absolute_name
);
3007 dired_outstring (":\n");
3010 /* Read the directory entries, and insert the subfiles into the 'cwd_file'
3015 /* Set errno to zero so we can distinguish between a readdir failure
3016 and when readdir simply finds that there are no more entries. */
3018 next
= readdir (dirp
);
3021 if (! file_ignored (next
->d_name
))
3023 enum filetype type
= unknown
;
3025 #if HAVE_STRUCT_DIRENT_D_TYPE
3026 switch (next
->d_type
)
3028 case DT_BLK
: type
= blockdev
; break;
3029 case DT_CHR
: type
= chardev
; break;
3030 case DT_DIR
: type
= directory
; break;
3031 case DT_FIFO
: type
= fifo
; break;
3032 case DT_LNK
: type
= symbolic_link
; break;
3033 case DT_REG
: type
= normal
; break;
3034 case DT_SOCK
: type
= sock
; break;
3036 case DT_WHT
: type
= whiteout
; break;
3040 total_blocks
+= gobble_file (next
->d_name
, type
,
3041 RELIABLE_D_INO (next
),
3044 /* In this narrow case, print out each name right away, so
3045 ls uses constant memory while processing the entries of
3046 this directory. Useful when there are many (millions)
3047 of entries in a directory. */
3048 if (format
== one_per_line
&& sort_type
== sort_none
3049 && !print_block_size
&& !recursive
)
3051 /* We must call sort_files in spite of
3052 "sort_type == sort_none" for its initialization
3053 of the sorted_file vector. */
3055 print_current_files ();
3060 else if (errno
!= 0)
3062 file_failure (command_line_arg
, _("reading directory %s"), name
);
3063 if (errno
!= EOVERFLOW
)
3069 /* When processing a very large directory, and since we've inhibited
3070 interrupts, this loop would take so long that ls would be annoyingly
3071 uninterruptible. This ensures that it handles signals promptly. */
3075 if (closedir (dirp
) != 0)
3077 file_failure (command_line_arg
, _("closing directory %s"), name
);
3078 /* Don't return; print whatever we got. */
3081 /* Sort the directory contents. */
3084 /* If any member files are subdirectories, perhaps they should have their
3085 contents listed rather than being mentioned here as files. */
3088 extract_dirs_from_files (name
, false);
3090 if (format
== long_format
|| print_block_size
)
3092 char buf
[LONGEST_HUMAN_READABLE
+ 3];
3093 char *p
= human_readable (total_blocks
, buf
+ 1, human_output_opts
,
3094 ST_NBLOCKSIZE
, output_block_size
);
3095 char *pend
= p
+ strlen (p
);
3099 dired_outstring (_("total"));
3100 dired_outbuf (p
, pend
- p
);
3104 print_current_files ();
3107 /* Add 'pattern' to the list of patterns for which files that match are
3111 add_ignore_pattern (char const *pattern
)
3113 struct ignore_pattern
*ignore
;
3115 ignore
= xmalloc (sizeof *ignore
);
3116 ignore
->pattern
= pattern
;
3117 /* Add it to the head of the linked list. */
3118 ignore
->next
= ignore_patterns
;
3119 ignore_patterns
= ignore
;
3122 /* Return true if one of the PATTERNS matches FILE. */
3125 patterns_match (struct ignore_pattern
const *patterns
, char const *file
)
3127 struct ignore_pattern
const *p
;
3128 for (p
= patterns
; p
; p
= p
->next
)
3129 if (fnmatch (p
->pattern
, file
, FNM_PERIOD
) == 0)
3134 /* Return true if FILE should be ignored. */
3137 file_ignored (char const *name
)
3139 return ((ignore_mode
!= IGNORE_MINIMAL
3141 && (ignore_mode
== IGNORE_DEFAULT
|| ! name
[1 + (name
[1] == '.')]))
3142 || (ignore_mode
== IGNORE_DEFAULT
3143 && patterns_match (hide_patterns
, name
))
3144 || patterns_match (ignore_patterns
, name
));
3147 /* POSIX requires that a file size be printed without a sign, even
3148 when negative. Assume the typical case where negative sizes are
3149 actually positive values that have wrapped around. */
3152 unsigned_file_size (off_t size
)
3154 return size
+ (size
< 0) * ((uintmax_t) OFF_T_MAX
- OFF_T_MIN
+ 1);
3158 /* Return true if NAME has a capability (see linux/capability.h) */
3160 has_capability (char const *name
)
3165 cap_t cap_d
= cap_get_file (name
);
3169 result
= cap_to_text (cap_d
, NULL
);
3174 /* check if human-readable capability string is empty */
3175 has_cap
= !!*result
;
3182 has_capability (MAYBE_UNUSED
char const *name
)
3189 /* Enter and remove entries in the table 'cwd_file'. */
3192 free_ent (struct fileinfo
*f
)
3196 free (f
->absolute_name
);
3197 if (f
->scontext
!= UNKNOWN_SECURITY_CONTEXT
)
3199 if (is_smack_enabled ())
3202 freecon (f
->scontext
);
3206 /* Empty the table of files. */
3210 for (size_t i
= 0; i
< cwd_n_used
; i
++)
3212 struct fileinfo
*f
= sorted_file
[i
];
3217 cwd_some_quoted
= false;
3218 any_has_acl
= false;
3219 inode_number_width
= 0;
3220 block_size_width
= 0;
3226 major_device_number_width
= 0;
3227 minor_device_number_width
= 0;
3228 file_size_width
= 0;
3231 /* Return true if ERR implies lack-of-support failure by a
3232 getxattr-calling function like getfilecon or file_has_acl. */
3234 errno_unsupported (int err
)
3236 return (err
== EINVAL
|| err
== ENOSYS
|| is_ENOTSUP (err
));
3239 /* Cache *getfilecon failure, when it's trivial to do so.
3240 Like getfilecon/lgetfilecon, but when F's st_dev says it's doesn't
3241 support getting the security context, fail with ENOTSUP immediately. */
3243 getfilecon_cache (char const *file
, struct fileinfo
*f
, bool deref
)
3245 /* st_dev of the most recently processed device for which we've
3246 found that [l]getfilecon fails indicating lack of support. */
3247 static dev_t unsupported_device
;
3249 if (f
->stat
.st_dev
== unsupported_device
)
3256 if (is_smack_enabled ())
3257 r
= smack_new_label_from_path (file
, "security.SMACK64", deref
,
3262 ? getfilecon (file
, &f
->scontext
)
3263 : lgetfilecon (file
, &f
->scontext
));
3264 if (r
< 0 && errno_unsupported (errno
))
3265 unsupported_device
= f
->stat
.st_dev
;
3269 /* Cache file_has_acl failure, when it's trivial to do.
3270 Like file_has_acl, but when F's st_dev says it's on a file
3271 system lacking ACL support, return 0 with ENOTSUP immediately. */
3273 file_has_acl_cache (char const *file
, struct fileinfo
*f
)
3275 /* st_dev of the most recently processed device for which we've
3276 found that file_has_acl fails indicating lack of support. */
3277 static dev_t unsupported_device
;
3279 if (f
->stat
.st_dev
== unsupported_device
)
3285 /* Zero errno so that we can distinguish between two 0-returning cases:
3286 "has-ACL-support, but only a default ACL" and "no ACL support". */
3288 int n
= file_has_acl (file
, &f
->stat
);
3289 if (n
<= 0 && errno_unsupported (errno
))
3290 unsupported_device
= f
->stat
.st_dev
;
3294 /* Cache has_capability failure, when it's trivial to do.
3295 Like has_capability, but when F's st_dev says it's on a file
3296 system lacking capability support, return 0 with ENOTSUP immediately. */
3298 has_capability_cache (char const *file
, struct fileinfo
*f
)
3300 /* st_dev of the most recently processed device for which we've
3301 found that has_capability fails indicating lack of support. */
3302 static dev_t unsupported_device
;
3304 if (f
->stat
.st_dev
== unsupported_device
)
3310 bool b
= has_capability (file
);
3311 if ( !b
&& errno_unsupported (errno
))
3312 unsupported_device
= f
->stat
.st_dev
;
3317 needs_quoting (char const *name
)
3320 size_t len
= quotearg_buffer (test
, sizeof test
, name
, -1,
3321 filename_quoting_options
);
3322 return *name
!= *test
|| strlen (name
) != len
;
3325 /* Add a file to the current table of files.
3326 Verify that the file exists, and print an error message if it does not.
3327 Return the number of blocks that the file occupies. */
3329 gobble_file (char const *name
, enum filetype type
, ino_t inode
,
3330 bool command_line_arg
, char const *dirname
)
3332 uintmax_t blocks
= 0;
3335 /* An inode value prior to gobble_file necessarily came from readdir,
3336 which is not used for command line arguments. */
3337 assert (! command_line_arg
|| inode
== NOT_AN_INODE_NUMBER
);
3339 if (cwd_n_used
== cwd_n_alloc
)
3341 cwd_file
= xnrealloc (cwd_file
, cwd_n_alloc
, 2 * sizeof *cwd_file
);
3345 f
= &cwd_file
[cwd_n_used
];
3346 memset (f
, '\0', sizeof *f
);
3347 f
->stat
.st_ino
= inode
;
3351 if ((! cwd_some_quoted
) && align_variable_outer_quotes
)
3353 /* Determine if any quoted for padding purposes. */
3354 f
->quoted
= needs_quoting (name
);
3356 cwd_some_quoted
= 1;
3359 if (command_line_arg
3361 || format_needs_stat
3362 /* When coloring a directory (we may know the type from
3363 direct.d_type), we have to stat it in order to indicate
3364 sticky and/or other-writable attributes. */
3365 || (type
== directory
&& print_with_color
3366 && (is_colored (C_OTHER_WRITABLE
)
3367 || is_colored (C_STICKY
)
3368 || is_colored (C_STICKY_OTHER_WRITABLE
)))
3369 /* When dereferencing symlinks, the inode and type must come from
3370 stat, but readdir provides the inode and type of lstat. */
3371 || ((print_inode
|| format_needs_type
)
3372 && (type
== symbolic_link
|| type
== unknown
)
3373 && (dereference
== DEREF_ALWAYS
3374 || color_symlink_as_referent
|| check_symlink_mode
))
3375 /* Command line dereferences are already taken care of by the above
3376 assertion that the inode number is not yet known. */
3377 || (print_inode
&& inode
== NOT_AN_INODE_NUMBER
)
3378 || (format_needs_type
3379 && (type
== unknown
|| command_line_arg
3380 /* --indicator-style=classify (aka -F)
3381 requires that we stat each regular file
3382 to see if it's executable. */
3383 || (type
== normal
&& (indicator_style
== classify
3384 /* This is so that --color ends up
3385 highlighting files with these mode
3386 bits set even when options like -F are
3387 not specified. Note we do a redundant
3388 stat in the very unlikely case where
3389 C_CAP is set but not the others. */
3390 || (print_with_color
3391 && (is_colored (C_EXEC
)
3392 || is_colored (C_SETUID
)
3393 || is_colored (C_SETGID
)
3394 || is_colored (C_CAP
)))
3398 /* Absolute name of this file. */
3403 if (name
[0] == '/' || dirname
[0] == 0)
3404 full_name
= (char *) name
;
3407 full_name
= alloca (strlen (name
) + strlen (dirname
) + 2);
3408 attach (full_name
, dirname
, name
);
3411 if (print_hyperlink
)
3413 f
->absolute_name
= canonicalize_filename_mode (full_name
,
3415 if (! f
->absolute_name
)
3416 file_failure (command_line_arg
,
3417 _("error canonicalizing %s"), full_name
);
3420 switch (dereference
)
3423 err
= do_stat (full_name
, &f
->stat
);
3427 case DEREF_COMMAND_LINE_ARGUMENTS
:
3428 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR
:
3429 if (command_line_arg
)
3432 err
= do_stat (full_name
, &f
->stat
);
3435 if (dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
3438 need_lstat
= (err
< 0
3440 : ! S_ISDIR (f
->stat
.st_mode
));
3444 /* stat failed because of ENOENT, maybe indicating a dangling
3445 symlink. Or stat succeeded, FULL_NAME does not refer to a
3446 directory, and --dereference-command-line-symlink-to-dir is
3447 in effect. Fall through so that we call lstat instead. */
3451 default: /* DEREF_NEVER */
3452 err
= do_lstat (full_name
, &f
->stat
);
3459 /* Failure to stat a command line argument leads to
3460 an exit status of 2. For other files, stat failure
3461 provokes an exit status of 1. */
3462 file_failure (command_line_arg
,
3463 _("cannot access %s"), full_name
);
3465 f
->scontext
= UNKNOWN_SECURITY_CONTEXT
;
3467 if (command_line_arg
)
3470 f
->name
= xstrdup (name
);
3478 /* Note has_capability() adds around 30% runtime to 'ls --color' */
3479 if ((type
== normal
|| S_ISREG (f
->stat
.st_mode
))
3480 && print_with_color
&& is_colored (C_CAP
))
3481 f
->has_capability
= has_capability_cache (full_name
, f
);
3483 if (format
== long_format
|| print_scontext
)
3485 bool have_scontext
= false;
3486 bool have_acl
= false;
3487 int attr_len
= getfilecon_cache (full_name
, f
, do_deref
);
3488 err
= (attr_len
< 0);
3492 if (is_smack_enabled ())
3493 have_scontext
= ! STREQ ("_", f
->scontext
);
3495 have_scontext
= ! STREQ ("unlabeled", f
->scontext
);
3499 f
->scontext
= UNKNOWN_SECURITY_CONTEXT
;
3501 /* When requesting security context information, don't make
3502 ls fail just because the file (even a command line argument)
3503 isn't on the right type of file system. I.e., a getfilecon
3504 failure isn't in the same class as a stat failure. */
3505 if (is_ENOTSUP (errno
) || errno
== ENODATA
)
3509 if (err
== 0 && format
== long_format
)
3511 int n
= file_has_acl_cache (full_name
, f
);
3516 f
->acl_type
= (!have_scontext
&& !have_acl
3518 : (have_scontext
&& !have_acl
3519 ? ACL_T_LSM_CONTEXT_ONLY
3521 any_has_acl
|= f
->acl_type
!= ACL_T_NONE
;
3524 error (0, errno
, "%s", quotef (full_name
));
3527 if (S_ISLNK (f
->stat
.st_mode
)
3528 && (format
== long_format
|| check_symlink_mode
))
3530 struct stat linkstats
;
3532 get_link_name (full_name
, f
, command_line_arg
);
3533 char *linkname
= make_link_name (full_name
, f
->linkname
);
3535 /* Use the slower quoting path for this entry, though
3536 don't update CWD_SOME_QUOTED since alignment not affected. */
3537 if (linkname
&& f
->quoted
== 0 && needs_quoting (f
->linkname
))
3540 /* Avoid following symbolic links when possible, ie, when
3541 they won't be traced and when no indicator is needed. */
3543 && (file_type
<= indicator_style
|| check_symlink_mode
)
3544 && stat_for_mode (linkname
, &linkstats
) == 0)
3547 f
->linkmode
= linkstats
.st_mode
;
3552 if (S_ISLNK (f
->stat
.st_mode
))
3553 f
->filetype
= symbolic_link
;
3554 else if (S_ISDIR (f
->stat
.st_mode
))
3556 if (command_line_arg
&& !immediate_dirs
)
3557 f
->filetype
= arg_directory
;
3559 f
->filetype
= directory
;
3562 f
->filetype
= normal
;
3564 blocks
= ST_NBLOCKS (f
->stat
);
3565 if (format
== long_format
|| print_block_size
)
3567 char buf
[LONGEST_HUMAN_READABLE
+ 1];
3568 int len
= mbswidth (human_readable (blocks
, buf
, human_output_opts
,
3569 ST_NBLOCKSIZE
, output_block_size
),
3571 if (block_size_width
< len
)
3572 block_size_width
= len
;
3575 if (format
== long_format
)
3579 int len
= format_user_width (f
->stat
.st_uid
);
3580 if (owner_width
< len
)
3586 int len
= format_group_width (f
->stat
.st_gid
);
3587 if (group_width
< len
)
3593 int len
= format_user_width (f
->stat
.st_author
);
3594 if (author_width
< len
)
3601 int len
= strlen (f
->scontext
);
3602 if (scontext_width
< len
)
3603 scontext_width
= len
;
3606 if (format
== long_format
)
3608 char b
[INT_BUFSIZE_BOUND (uintmax_t)];
3609 int b_len
= strlen (umaxtostr (f
->stat
.st_nlink
, b
));
3610 if (nlink_width
< b_len
)
3611 nlink_width
= b_len
;
3613 if (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
))
3615 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
3616 int len
= strlen (umaxtostr (major (f
->stat
.st_rdev
), buf
));
3617 if (major_device_number_width
< len
)
3618 major_device_number_width
= len
;
3619 len
= strlen (umaxtostr (minor (f
->stat
.st_rdev
), buf
));
3620 if (minor_device_number_width
< len
)
3621 minor_device_number_width
= len
;
3622 len
= major_device_number_width
+ 2 + minor_device_number_width
;
3623 if (file_size_width
< len
)
3624 file_size_width
= len
;
3628 char buf
[LONGEST_HUMAN_READABLE
+ 1];
3629 uintmax_t size
= unsigned_file_size (f
->stat
.st_size
);
3630 int len
= mbswidth (human_readable (size
, buf
,
3631 file_human_output_opts
,
3632 1, file_output_block_size
),
3634 if (file_size_width
< len
)
3635 file_size_width
= len
;
3642 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
3643 int len
= strlen (umaxtostr (f
->stat
.st_ino
, buf
));
3644 if (inode_number_width
< len
)
3645 inode_number_width
= len
;
3648 f
->name
= xstrdup (name
);
3654 /* Return true if F refers to a directory. */
3656 is_directory (const struct fileinfo
*f
)
3658 return f
->filetype
== directory
|| f
->filetype
== arg_directory
;
3661 /* Return true if F refers to a (symlinked) directory. */
3663 is_linked_directory (const struct fileinfo
*f
)
3665 return f
->filetype
== directory
|| f
->filetype
== arg_directory
3666 || S_ISDIR (f
->linkmode
);
3669 /* Put the name of the file that FILENAME is a symbolic link to
3670 into the LINKNAME field of 'f'. COMMAND_LINE_ARG indicates whether
3671 FILENAME is a command-line argument. */
3674 get_link_name (char const *filename
, struct fileinfo
*f
, bool command_line_arg
)
3676 f
->linkname
= areadlink_with_size (filename
, f
->stat
.st_size
);
3677 if (f
->linkname
== NULL
)
3678 file_failure (command_line_arg
, _("cannot read symbolic link %s"),
3682 /* If LINKNAME is a relative name and NAME contains one or more
3683 leading directories, return LINKNAME with those directories
3684 prepended; otherwise, return a copy of LINKNAME.
3685 If LINKNAME is NULL, return NULL. */
3688 make_link_name (char const *name
, char const *linkname
)
3693 if (IS_ABSOLUTE_FILE_NAME (linkname
))
3694 return xstrdup (linkname
);
3696 /* The link is to a relative name. Prepend any leading directory
3697 in 'name' to the link name. */
3698 size_t prefix_len
= dir_len (name
);
3699 if (prefix_len
== 0)
3700 return xstrdup (linkname
);
3702 char *p
= xmalloc (prefix_len
+ 1 + strlen (linkname
) + 1);
3704 /* PREFIX_LEN usually specifies a string not ending in slash.
3705 In that case, extend it by one, since the next byte *is* a slash.
3706 Otherwise, the prefix is "/", so leave the length unchanged. */
3707 if ( ! ISSLASH (name
[prefix_len
- 1]))
3710 stpcpy (stpncpy (p
, name
, prefix_len
), linkname
);
3714 /* Return true if the last component of NAME is '.' or '..'
3715 This is so we don't try to recurse on '././././. ...' */
3718 basename_is_dot_or_dotdot (char const *name
)
3720 char const *base
= last_component (name
);
3721 return dot_or_dotdot (base
);
3724 /* Remove any entries from CWD_FILE that are for directories,
3725 and queue them to be listed as directories instead.
3726 DIRNAME is the prefix to prepend to each dirname
3727 to make it correct relative to ls's working dir;
3728 if it is null, no prefix is needed and "." and ".." should not be ignored.
3729 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3730 This is desirable when processing directories recursively. */
3733 extract_dirs_from_files (char const *dirname
, bool command_line_arg
)
3737 bool ignore_dot_and_dot_dot
= (dirname
!= NULL
);
3739 if (dirname
&& LOOP_DETECT
)
3741 /* Insert a marker entry first. When we dequeue this marker entry,
3742 we'll know that DIRNAME has been processed and may be removed
3743 from the set of active directories. */
3744 queue_directory (NULL
, dirname
, false);
3747 /* Queue the directories last one first, because queueing reverses the
3749 for (i
= cwd_n_used
; i
-- != 0; )
3751 struct fileinfo
*f
= sorted_file
[i
];
3753 if (is_directory (f
)
3754 && (! ignore_dot_and_dot_dot
3755 || ! basename_is_dot_or_dotdot (f
->name
)))
3757 if (!dirname
|| f
->name
[0] == '/')
3758 queue_directory (f
->name
, f
->linkname
, command_line_arg
);
3761 char *name
= file_name_concat (dirname
, f
->name
, NULL
);
3762 queue_directory (name
, f
->linkname
, command_line_arg
);
3765 if (f
->filetype
== arg_directory
)
3770 /* Now delete the directories from the table, compacting all the remaining
3773 for (i
= 0, j
= 0; i
< cwd_n_used
; i
++)
3775 struct fileinfo
*f
= sorted_file
[i
];
3777 j
+= (f
->filetype
!= arg_directory
);
3782 /* Use strcoll to compare strings in this locale. If an error occurs,
3783 report an error and longjmp to failed_strcoll. */
3785 static jmp_buf failed_strcoll
;
3788 xstrcoll (char const *a
, char const *b
)
3792 diff
= strcoll (a
, b
);
3795 error (0, errno
, _("cannot compare file names %s and %s"),
3796 quote_n (0, a
), quote_n (1, b
));
3797 set_exit_status (false);
3798 longjmp (failed_strcoll
, 1);
3803 /* Comparison routines for sorting the files. */
3805 typedef void const *V
;
3806 typedef int (*qsortFunc
)(V a
, V b
);
3808 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants. */
3810 dirfirst_check (struct fileinfo
const *a
, struct fileinfo
const *b
,
3813 int diff
= is_linked_directory (b
) - is_linked_directory (a
);
3814 return diff
? diff
: cmp (a
, b
);
3817 /* Define the 8 different sort function variants required for each sortkey.
3818 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3819 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3820 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3821 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3822 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3823 /* direct, non-dirfirst versions */ \
3824 static int xstrcoll_##key_name (V a, V b) \
3825 { return key_cmp_func (a, b, xstrcoll); } \
3826 ATTRIBUTE_PURE static int strcmp_##key_name (V a, V b) \
3827 { return key_cmp_func (a, b, strcmp); } \
3829 /* reverse, non-dirfirst versions */ \
3830 static int rev_xstrcoll_##key_name (V a, V b) \
3831 { return key_cmp_func (b, a, xstrcoll); } \
3832 ATTRIBUTE_PURE static int rev_strcmp_##key_name (V a, V b) \
3833 { return key_cmp_func (b, a, strcmp); } \
3835 /* direct, dirfirst versions */ \
3836 static int xstrcoll_df_##key_name (V a, V b) \
3837 { return dirfirst_check (a, b, xstrcoll_##key_name); } \
3838 ATTRIBUTE_PURE static int strcmp_df_##key_name (V a, V b) \
3839 { return dirfirst_check (a, b, strcmp_##key_name); } \
3841 /* reverse, dirfirst versions */ \
3842 static int rev_xstrcoll_df_##key_name (V a, V b) \
3843 { return dirfirst_check (a, b, rev_xstrcoll_##key_name); } \
3844 ATTRIBUTE_PURE static int rev_strcmp_df_##key_name (V a, V b) \
3845 { return dirfirst_check (a, b, rev_strcmp_##key_name); }
3848 cmp_ctime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3849 int (*cmp
) (char const *, char const *))
3851 int diff
= timespec_cmp (get_stat_ctime (&b
->stat
),
3852 get_stat_ctime (&a
->stat
));
3853 return diff
? diff
: cmp (a
->name
, b
->name
);
3857 cmp_mtime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3858 int (*cmp
) (char const *, char const *))
3860 int diff
= timespec_cmp (get_stat_mtime (&b
->stat
),
3861 get_stat_mtime (&a
->stat
));
3862 return diff
? diff
: cmp (a
->name
, b
->name
);
3866 cmp_atime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3867 int (*cmp
) (char const *, char const *))
3869 int diff
= timespec_cmp (get_stat_atime (&b
->stat
),
3870 get_stat_atime (&a
->stat
));
3871 return diff
? diff
: cmp (a
->name
, b
->name
);
3875 cmp_btime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3876 int (*cmp
) (char const *, char const *))
3878 int diff
= timespec_cmp (get_stat_btime (&b
->stat
),
3879 get_stat_btime (&a
->stat
));
3880 return diff
? diff
: cmp (a
->name
, b
->name
);
3884 off_cmp (off_t a
, off_t b
)
3886 return (a
> b
) - (a
< b
);
3890 cmp_size (struct fileinfo
const *a
, struct fileinfo
const *b
,
3891 int (*cmp
) (char const *, char const *))
3893 int diff
= off_cmp (b
->stat
.st_size
, a
->stat
.st_size
);
3894 return diff
? diff
: cmp (a
->name
, b
->name
);
3898 cmp_name (struct fileinfo
const *a
, struct fileinfo
const *b
,
3899 int (*cmp
) (char const *, char const *))
3901 return cmp (a
->name
, b
->name
);
3904 /* Compare file extensions. Files with no extension are 'smallest'.
3905 If extensions are the same, compare by file names instead. */
3908 cmp_extension (struct fileinfo
const *a
, struct fileinfo
const *b
,
3909 int (*cmp
) (char const *, char const *))
3911 char const *base1
= strrchr (a
->name
, '.');
3912 char const *base2
= strrchr (b
->name
, '.');
3913 int diff
= cmp (base1
? base1
: "", base2
? base2
: "");
3914 return diff
? diff
: cmp (a
->name
, b
->name
);
3917 /* Return the (cached) screen width,
3918 for the NAME associated with the passed fileinfo F. */
3921 fileinfo_name_width (struct fileinfo
const *f
)
3925 : quote_name_width (f
->name
, filename_quoting_options
, f
->quoted
);
3929 cmp_width (struct fileinfo
const *a
, struct fileinfo
const *b
,
3930 int (*cmp
) (char const *, char const *))
3932 int diff
= fileinfo_name_width (a
) - fileinfo_name_width (b
);
3933 return diff
? diff
: cmp (a
->name
, b
->name
);
3936 DEFINE_SORT_FUNCTIONS (ctime
, cmp_ctime
)
3937 DEFINE_SORT_FUNCTIONS (mtime
, cmp_mtime
)
3938 DEFINE_SORT_FUNCTIONS (atime
, cmp_atime
)
3939 DEFINE_SORT_FUNCTIONS (btime
, cmp_btime
)
3940 DEFINE_SORT_FUNCTIONS (size
, cmp_size
)
3941 DEFINE_SORT_FUNCTIONS (name
, cmp_name
)
3942 DEFINE_SORT_FUNCTIONS (extension
, cmp_extension
)
3943 DEFINE_SORT_FUNCTIONS (width
, cmp_width
)
3945 /* Compare file versions.
3946 Unlike the other compare functions, cmp_version does not fail
3947 because filevercmp and strcmp do not fail; cmp_version uses strcmp
3948 instead of xstrcoll because filevercmp is locale-independent so
3949 strcmp is its appropriate secondary.
3951 All the other sort options need xstrcoll and strcmp variants,
3952 because they all use xstrcoll (either as the primary or secondary
3953 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3956 cmp_version (struct fileinfo
const *a
, struct fileinfo
const *b
)
3958 int diff
= filevercmp (a
->name
, b
->name
);
3959 return diff
? diff
: strcmp (a
->name
, b
->name
);
3963 xstrcoll_version (V a
, V b
)
3965 return cmp_version (a
, b
);
3968 rev_xstrcoll_version (V a
, V b
)
3970 return cmp_version (b
, a
);
3973 xstrcoll_df_version (V a
, V b
)
3975 return dirfirst_check (a
, b
, xstrcoll_version
);
3978 rev_xstrcoll_df_version (V a
, V b
)
3980 return dirfirst_check (a
, b
, rev_xstrcoll_version
);
3984 /* We have 2^3 different variants for each sort-key function
3985 (for 3 independent sort modes).
3986 The function pointers stored in this array must be dereferenced as:
3988 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3990 Note that the order in which sort keys are listed in the function pointer
3991 array below is defined by the order of the elements in the time_type and
3994 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3997 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3998 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
4001 { strcmp_##key_name, strcmp_df_##key_name }, \
4002 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
4006 static qsortFunc
const sort_functions
[][2][2][2] =
4008 LIST_SORTFUNCTION_VARIANTS (name
),
4009 LIST_SORTFUNCTION_VARIANTS (extension
),
4010 LIST_SORTFUNCTION_VARIANTS (width
),
4011 LIST_SORTFUNCTION_VARIANTS (size
),
4015 { xstrcoll_version
, xstrcoll_df_version
},
4016 { rev_xstrcoll_version
, rev_xstrcoll_df_version
},
4019 /* We use NULL for the strcmp variants of version comparison
4020 since as explained in cmp_version definition, version comparison
4021 does not rely on xstrcoll, so it will never longjmp, and never
4022 need to try the strcmp fallback. */
4029 /* last are time sort functions */
4030 LIST_SORTFUNCTION_VARIANTS (mtime
),
4031 LIST_SORTFUNCTION_VARIANTS (ctime
),
4032 LIST_SORTFUNCTION_VARIANTS (atime
),
4033 LIST_SORTFUNCTION_VARIANTS (btime
)
4036 /* The number of sort keys is calculated as the sum of
4037 the number of elements in the sort_type enum (i.e., sort_numtypes)
4038 -2 because neither sort_time nor sort_none use entries themselves
4039 the number of elements in the time_type enum (i.e., time_numtypes)
4040 This is because when sort_type==sort_time, we have up to
4041 time_numtypes possible sort keys.
4043 This line verifies at compile-time that the array of sort functions has been
4044 initialized for all possible sort keys. */
4045 static_assert (ARRAY_CARDINALITY (sort_functions
)
4046 == sort_numtypes
- 2 + time_numtypes
);
4048 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
4051 initialize_ordering_vector (void)
4053 for (size_t i
= 0; i
< cwd_n_used
; i
++)
4054 sorted_file
[i
] = &cwd_file
[i
];
4057 /* Cache values based on attributes global to all files. */
4060 update_current_files_info (void)
4062 /* Cache screen width of name, if needed multiple times. */
4063 if (sort_type
== sort_width
4064 || (line_length
&& (format
== many_per_line
|| format
== horizontal
)))
4067 for (i
= 0; i
< cwd_n_used
; i
++)
4069 struct fileinfo
*f
= sorted_file
[i
];
4070 f
->width
= fileinfo_name_width (f
);
4075 /* Sort the files now in the table. */
4082 if (sorted_file_alloc
< cwd_n_used
+ cwd_n_used
/ 2)
4085 sorted_file
= xnmalloc (cwd_n_used
, 3 * sizeof *sorted_file
);
4086 sorted_file_alloc
= 3 * cwd_n_used
;
4089 initialize_ordering_vector ();
4091 update_current_files_info ();
4093 if (sort_type
== sort_none
)
4096 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
4097 ignore strcoll failures, as a failing strcoll might be a
4098 comparison function that is not a total order, and if we ignored
4099 the failure this might cause qsort to dump core. */
4101 if (! setjmp (failed_strcoll
))
4102 use_strcmp
= false; /* strcoll() succeeded */
4106 assert (sort_type
!= sort_version
);
4107 initialize_ordering_vector ();
4110 /* When sort_type == sort_time, use time_type as subindex. */
4111 mpsort ((void const **) sorted_file
, cwd_n_used
,
4112 sort_functions
[sort_type
+ (sort_type
== sort_time
? time_type
: 0)]
4113 [use_strcmp
][sort_reverse
]
4114 [directories_first
]);
4117 /* List all the files now in the table. */
4120 print_current_files (void)
4127 for (i
= 0; i
< cwd_n_used
; i
++)
4129 print_file_name_and_frills (sorted_file
[i
], 0);
4136 print_with_separator (' ');
4138 print_many_per_line ();
4143 print_with_separator (' ');
4145 print_horizontal ();
4149 print_with_separator (',');
4153 for (i
= 0; i
< cwd_n_used
; i
++)
4155 set_normal_color ();
4156 print_long_format (sorted_file
[i
]);
4157 dired_outbyte (eolbyte
);
4163 /* Replace the first %b with precomputed aligned month names.
4164 Note on glibc-2.7 at least, this speeds up the whole 'ls -lU'
4165 process by around 17%, compared to letting strftime() handle the %b. */
4168 align_nstrftime (char *buf
, size_t size
, bool recent
, struct tm
const *tm
,
4169 timezone_t tz
, int ns
)
4171 char const *nfmt
= (use_abformat
4172 ? abformat
[recent
][tm
->tm_mon
]
4173 : long_time_format
[recent
]);
4174 return nstrftime (buf
, size
, nfmt
, tm
, tz
, ns
);
4177 /* Return the expected number of columns in a long-format timestamp,
4178 or zero if it cannot be calculated. */
4181 long_time_expected_width (void)
4183 static int width
= -1;
4189 char buf
[TIME_STAMP_LEN_MAXIMUM
+ 1];
4191 /* In case you're wondering if localtime_rz can fail with an input time_t
4192 value of 0, let's just say it's very unlikely, but not inconceivable.
4193 The TZ environment variable would have to specify a time zone that
4194 is 2**31-1900 years or more ahead of UTC. This could happen only on
4195 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
4196 However, this is not possible with Solaris 10 or glibc-2.3.5, since
4197 their implementations limit the offset to 167:59 and 24:00, resp. */
4198 if (localtime_rz (localtz
, &epoch
, &tm
))
4200 size_t len
= align_nstrftime (buf
, sizeof buf
, false,
4203 width
= mbsnwidth (buf
, len
, 0);
4213 /* Print the user or group name NAME, with numeric id ID, using a
4214 print width of WIDTH columns. */
4217 format_user_or_group (char const *name
, uintmax_t id
, int width
)
4221 int width_gap
= width
- mbswidth (name
, 0);
4222 int pad
= MAX (0, width_gap
);
4223 dired_outstring (name
);
4226 dired_outbyte (' ');
4230 dired_pos
+= printf ("%*"PRIuMAX
" ", width
, id
);
4233 /* Print the name or id of the user with id U, using a print width of
4237 format_user (uid_t u
, int width
, bool stat_ok
)
4239 format_user_or_group (! stat_ok
? "?" :
4240 (numeric_ids
? NULL
: getuser (u
)), u
, width
);
4243 /* Likewise, for groups. */
4246 format_group (gid_t g
, int width
, bool stat_ok
)
4248 format_user_or_group (! stat_ok
? "?" :
4249 (numeric_ids
? NULL
: getgroup (g
)), g
, width
);
4252 /* Return the number of columns that format_user_or_group will print. */
4255 format_user_or_group_width (char const *name
, uintmax_t id
)
4259 int len
= mbswidth (name
, 0);
4260 return MAX (0, len
);
4263 return snprintf (NULL
, 0, "%"PRIuMAX
, id
);
4266 /* Return the number of columns that format_user will print. */
4269 format_user_width (uid_t u
)
4271 return format_user_or_group_width (numeric_ids
? NULL
: getuser (u
), u
);
4274 /* Likewise, for groups. */
4277 format_group_width (gid_t g
)
4279 return format_user_or_group_width (numeric_ids
? NULL
: getgroup (g
), g
);
4282 /* Return a pointer to a formatted version of F->stat.st_ino,
4283 possibly using buffer, BUF, of length BUFLEN, which must be at least
4284 INT_BUFSIZE_BOUND (uintmax_t) bytes. */
4286 format_inode (char *buf
, size_t buflen
, const struct fileinfo
*f
)
4288 assert (INT_BUFSIZE_BOUND (uintmax_t) <= buflen
);
4289 return (f
->stat_ok
&& f
->stat
.st_ino
!= NOT_AN_INODE_NUMBER
4290 ? umaxtostr (f
->stat
.st_ino
, buf
)
4294 /* Print information about F in long format. */
4296 print_long_format (const struct fileinfo
*f
)
4300 [LONGEST_HUMAN_READABLE
+ 1 /* inode */
4301 + LONGEST_HUMAN_READABLE
+ 1 /* size in blocks */
4302 + sizeof (modebuf
) - 1 + 1 /* mode string */
4303 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
4304 + LONGEST_HUMAN_READABLE
+ 2 /* major device number */
4305 + LONGEST_HUMAN_READABLE
+ 1 /* minor device number */
4306 + TIME_STAMP_LEN_MAXIMUM
+ 1 /* max length of time/date */
4310 struct timespec when_timespec
;
4311 struct tm when_local
;
4312 bool btime_ok
= true;
4314 /* Compute the mode string, except remove the trailing space if no
4315 file in this directory has an ACL or security context. */
4317 filemodestring (&f
->stat
, modebuf
);
4320 modebuf
[0] = filetype_letter
[f
->filetype
];
4321 memset (modebuf
+ 1, '?', 10);
4326 else if (f
->acl_type
== ACL_T_LSM_CONTEXT_ONLY
)
4328 else if (f
->acl_type
== ACL_T_YES
)
4334 when_timespec
= get_stat_ctime (&f
->stat
);
4337 when_timespec
= get_stat_mtime (&f
->stat
);
4340 when_timespec
= get_stat_atime (&f
->stat
);
4343 when_timespec
= get_stat_btime (&f
->stat
);
4344 if (when_timespec
.tv_sec
== -1 && when_timespec
.tv_nsec
== -1)
4355 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4356 p
+= sprintf (p
, "%*s ", inode_number_width
,
4357 format_inode (hbuf
, sizeof hbuf
, f
));
4360 if (print_block_size
)
4362 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
4363 char const *blocks
=
4366 : human_readable (ST_NBLOCKS (f
->stat
), hbuf
, human_output_opts
,
4367 ST_NBLOCKSIZE
, output_block_size
));
4369 for (pad
= block_size_width
- mbswidth (blocks
, 0); 0 < pad
; pad
--)
4371 while ((*p
++ = *blocks
++))
4376 /* The last byte of the mode string is the POSIX
4377 "optional alternate access method flag". */
4379 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4380 p
+= sprintf (p
, "%s %*s ", modebuf
, nlink_width
,
4381 ! f
->stat_ok
? "?" : umaxtostr (f
->stat
.st_nlink
, hbuf
));
4386 if (print_owner
|| print_group
|| print_author
|| print_scontext
)
4388 dired_outbuf (buf
, p
- buf
);
4391 format_user (f
->stat
.st_uid
, owner_width
, f
->stat_ok
);
4394 format_group (f
->stat
.st_gid
, group_width
, f
->stat_ok
);
4397 format_user (f
->stat
.st_author
, author_width
, f
->stat_ok
);
4400 format_user_or_group (f
->scontext
, 0, scontext_width
);
4406 && (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
)))
4408 char majorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4409 char minorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4410 int blanks_width
= (file_size_width
4411 - (major_device_number_width
+ 2
4412 + minor_device_number_width
));
4413 p
+= sprintf (p
, "%*s, %*s ",
4414 major_device_number_width
+ MAX (0, blanks_width
),
4415 umaxtostr (major (f
->stat
.st_rdev
), majorbuf
),
4416 minor_device_number_width
,
4417 umaxtostr (minor (f
->stat
.st_rdev
), minorbuf
));
4421 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
4425 : human_readable (unsigned_file_size (f
->stat
.st_size
),
4426 hbuf
, file_human_output_opts
, 1,
4427 file_output_block_size
));
4429 for (pad
= file_size_width
- mbswidth (size
, 0); 0 < pad
; pad
--)
4431 while ((*p
++ = *size
++))
4439 if (f
->stat_ok
&& btime_ok
4440 && localtime_rz (localtz
, &when_timespec
.tv_sec
, &when_local
))
4442 struct timespec six_months_ago
;
4445 /* If the file appears to be in the future, update the current
4446 time, in case the file happens to have been modified since
4447 the last time we checked the clock. */
4448 if (timespec_cmp (current_time
, when_timespec
) < 0)
4449 gettime (¤t_time
);
4451 /* Consider a time to be recent if it is within the past six months.
4452 A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952 seconds
4453 on the average. Write this value as an integer constant to
4454 avoid floating point hassles. */
4455 six_months_ago
.tv_sec
= current_time
.tv_sec
- 31556952 / 2;
4456 six_months_ago
.tv_nsec
= current_time
.tv_nsec
;
4458 recent
= (timespec_cmp (six_months_ago
, when_timespec
) < 0
4459 && timespec_cmp (when_timespec
, current_time
) < 0);
4461 /* We assume here that all time zones are offset from UTC by a
4462 whole number of seconds. */
4463 s
= align_nstrftime (p
, TIME_STAMP_LEN_MAXIMUM
+ 1, recent
,
4464 &when_local
, localtz
, when_timespec
.tv_nsec
);
4474 /* The time cannot be converted using the desired format, so
4475 print it as a huge integer number of seconds. */
4476 char hbuf
[INT_BUFSIZE_BOUND (intmax_t)];
4477 p
+= sprintf (p
, "%*s ", long_time_expected_width (),
4478 (! f
->stat_ok
|| ! btime_ok
4480 : timetostr (when_timespec
.tv_sec
, hbuf
)));
4481 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
4484 dired_outbuf (buf
, p
- buf
);
4485 size_t w
= print_name_with_quoting (f
, false, &dired_obstack
, p
- buf
);
4487 if (f
->filetype
== symbolic_link
)
4491 dired_outstring (" -> ");
4492 print_name_with_quoting (f
, true, NULL
, (p
- buf
) + w
+ 4);
4493 if (indicator_style
!= none
)
4494 print_type_indicator (true, f
->linkmode
, unknown
);
4497 else if (indicator_style
!= none
)
4498 print_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
4501 /* Write to *BUF a quoted representation of the file name NAME, if non-NULL,
4502 using OPTIONS to control quoting. *BUF is set to NAME if no quoting
4503 is required. *BUF is allocated if more space required (and the original
4504 *BUF is not deallocated).
4505 Store the number of screen columns occupied by NAME's quoted
4506 representation into WIDTH, if non-NULL.
4507 Store into PAD whether an initial space is needed for padding.
4508 Return the number of bytes in *BUF. */
4511 quote_name_buf (char **inbuf
, size_t bufsize
, char *name
,
4512 struct quoting_options
const *options
,
4513 int needs_general_quoting
, size_t *width
, bool *pad
)
4516 size_t displayed_width
IF_LINT ( = 0);
4520 enum quoting_style qs
= get_quoting_style (options
);
4521 bool needs_further_quoting
= qmark_funny_chars
4522 && (qs
== shell_quoting_style
4523 || qs
== shell_always_quoting_style
4524 || qs
== literal_quoting_style
);
4526 if (needs_general_quoting
!= 0)
4528 len
= quotearg_buffer (buf
, bufsize
, name
, -1, options
);
4531 buf
= xmalloc (len
+ 1);
4532 quotearg_buffer (buf
, len
+ 1, name
, -1, options
);
4535 quoted
= (*name
!= *buf
) || strlen (name
) != len
;
4537 else if (needs_further_quoting
)
4539 len
= strlen (name
);
4541 buf
= xmalloc (len
+ 1);
4542 memcpy (buf
, name
, len
+ 1);
4548 len
= strlen (name
);
4553 if (needs_further_quoting
)
4557 char const *p
= buf
;
4558 char const *plimit
= buf
+ len
;
4560 displayed_width
= 0;
4565 case ' ': case '!': case '"': case '#': case '%':
4566 case '&': case '\'': case '(': case ')': case '*':
4567 case '+': case ',': case '-': case '.': case '/':
4568 case '0': case '1': case '2': case '3': case '4':
4569 case '5': case '6': case '7': case '8': case '9':
4570 case ':': case ';': case '<': case '=': case '>':
4572 case 'A': case 'B': case 'C': case 'D': case 'E':
4573 case 'F': case 'G': case 'H': case 'I': case 'J':
4574 case 'K': case 'L': case 'M': case 'N': case 'O':
4575 case 'P': case 'Q': case 'R': case 'S': case 'T':
4576 case 'U': case 'V': case 'W': case 'X': case 'Y':
4578 case '[': case '\\': case ']': case '^': case '_':
4579 case 'a': case 'b': case 'c': case 'd': case 'e':
4580 case 'f': case 'g': case 'h': case 'i': case 'j':
4581 case 'k': case 'l': case 'm': case 'n': case 'o':
4582 case 'p': case 'q': case 'r': case 's': case 't':
4583 case 'u': case 'v': case 'w': case 'x': case 'y':
4584 case 'z': case '{': case '|': case '}': case '~':
4585 /* These characters are printable ASCII characters. */
4587 displayed_width
+= 1;
4590 /* If we have a multibyte sequence, copy it until we
4591 reach its end, replacing each non-printable multibyte
4592 character with a single question mark. */
4594 mbstate_t mbstate
= { 0, };
4601 bytes
= mbrtowc (&wc
, p
, plimit
- p
, &mbstate
);
4603 if (bytes
== (size_t) -1)
4605 /* An invalid multibyte sequence was
4606 encountered. Skip one input byte, and
4607 put a question mark. */
4610 displayed_width
+= 1;
4614 if (bytes
== (size_t) -2)
4616 /* An incomplete multibyte character
4617 at the end. Replace it entirely with
4621 displayed_width
+= 1;
4626 /* A null wide character was encountered. */
4632 /* A printable multibyte character.
4634 for (; bytes
> 0; --bytes
)
4636 displayed_width
+= w
;
4640 /* An unprintable multibyte character.
4641 Replace it entirely with a question
4645 displayed_width
+= 1;
4648 while (! mbsinit (&mbstate
));
4653 /* The buffer may have shrunk. */
4659 char const *plimit
= buf
+ len
;
4663 if (! isprint (to_uchar (*p
)))
4667 displayed_width
= len
;
4670 else if (width
!= NULL
)
4673 displayed_width
= mbsnwidth (buf
, len
, 0);
4676 char const *p
= buf
;
4677 char const *plimit
= buf
+ len
;
4679 displayed_width
= 0;
4682 if (isprint (to_uchar (*p
)))
4689 /* Set padding to better align quoted items,
4690 and also give a visual indication that quotes are
4691 not actually part of the name. */
4692 *pad
= (align_variable_outer_quotes
&& cwd_some_quoted
&& ! quoted
);
4695 *width
= displayed_width
;
4703 quote_name_width (char const *name
, struct quoting_options
const *options
,
4704 int needs_general_quoting
)
4706 char smallbuf
[BUFSIZ
];
4707 char *buf
= smallbuf
;
4711 quote_name_buf (&buf
, sizeof smallbuf
, (char *) name
, options
,
4712 needs_general_quoting
, &width
, &pad
);
4714 if (buf
!= smallbuf
&& buf
!= name
)
4722 /* %XX escape any input out of range as defined in RFC3986,
4723 and also if PATH, convert all path separators to '/'. */
4725 file_escape (char const *str
, bool path
)
4727 char *esc
= xnmalloc (3, strlen (str
) + 1);
4731 if (path
&& ISSLASH (*str
))
4736 else if (RFC3986
[to_uchar (*str
)])
4739 p
+= sprintf (p
, "%%%02x", to_uchar (*str
++));
4746 quote_name (char const *name
, struct quoting_options
const *options
,
4747 int needs_general_quoting
, const struct bin_str
*color
,
4748 bool allow_pad
, struct obstack
*stack
, char const *absolute_name
)
4750 char smallbuf
[BUFSIZ
];
4751 char *buf
= smallbuf
;
4755 len
= quote_name_buf (&buf
, sizeof smallbuf
, (char *) name
, options
,
4756 needs_general_quoting
, NULL
, &pad
);
4758 if (pad
&& allow_pad
)
4759 dired_outbyte (' ');
4762 print_color_indicator (color
);
4764 /* If we're padding, then don't include the outer quotes in
4765 the --hyperlink, to improve the alignment of those links. */
4766 bool skip_quotes
= false;
4770 if (align_variable_outer_quotes
&& cwd_some_quoted
&& ! pad
)
4775 char *h
= file_escape (hostname
, /* path= */ false);
4776 char *n
= file_escape (absolute_name
, /* path= */ true);
4777 /* TODO: It would be good to be able to define parameters
4778 to give hints to the terminal as how best to render the URI.
4779 For example since ls is outputting a dense block of URIs
4780 it would be best to not underline by default, and only
4781 do so upon hover etc. */
4782 printf ("\033]8;;file://%s%s%s\a", h
, *n
== '/' ? "" : "/", n
);
4788 push_current_dired_pos (stack
);
4790 fwrite (buf
+ skip_quotes
, 1, len
- (skip_quotes
* 2), stdout
);
4795 push_current_dired_pos (stack
);
4799 fputs ("\033]8;;\a", stdout
);
4801 putchar (*(buf
+ len
- 1));
4804 if (buf
!= smallbuf
&& buf
!= name
)
4811 print_name_with_quoting (const struct fileinfo
*f
,
4812 bool symlink_target
,
4813 struct obstack
*stack
,
4816 char const *name
= symlink_target
? f
->linkname
: f
->name
;
4818 const struct bin_str
*color
= print_with_color
?
4819 get_color_indicator (f
, symlink_target
) : NULL
;
4821 bool used_color_this_time
= (print_with_color
4822 && (color
|| is_colored (C_NORM
)));
4824 size_t len
= quote_name (name
, filename_quoting_options
, f
->quoted
,
4825 color
, !symlink_target
, stack
, f
->absolute_name
);
4828 if (used_color_this_time
)
4830 prep_non_filename_text ();
4832 /* We use the byte length rather than display width here as
4833 an optimization to avoid accurately calculating the width,
4834 because we only output the clear to EOL sequence if the name
4835 _might_ wrap to the next line. This may output a sequence
4836 unnecessarily in multi-byte locales for example,
4837 but in that case it's inconsequential to the output. */
4839 && (start_col
/ line_length
!= (start_col
+ len
- 1) / line_length
))
4840 put_indicator (&color_indicator
[C_CLR_TO_EOL
]);
4847 prep_non_filename_text (void)
4849 if (color_indicator
[C_END
].string
!= NULL
)
4850 put_indicator (&color_indicator
[C_END
]);
4853 put_indicator (&color_indicator
[C_LEFT
]);
4854 put_indicator (&color_indicator
[C_RESET
]);
4855 put_indicator (&color_indicator
[C_RIGHT
]);
4859 /* Print the file name of 'f' with appropriate quoting.
4860 Also print file size, inode number, and filetype indicator character,
4861 as requested by switches. */
4864 print_file_name_and_frills (const struct fileinfo
*f
, size_t start_col
)
4866 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
4868 set_normal_color ();
4871 printf ("%*s ", format
== with_commas
? 0 : inode_number_width
,
4872 format_inode (buf
, sizeof buf
, f
));
4874 if (print_block_size
)
4875 printf ("%*s ", format
== with_commas
? 0 : block_size_width
,
4877 : human_readable (ST_NBLOCKS (f
->stat
), buf
, human_output_opts
,
4878 ST_NBLOCKSIZE
, output_block_size
));
4881 printf ("%*s ", format
== with_commas
? 0 : scontext_width
, f
->scontext
);
4883 size_t width
= print_name_with_quoting (f
, false, NULL
, start_col
);
4885 if (indicator_style
!= none
)
4886 width
+= print_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
4891 /* Given these arguments describing a file, return the single-byte
4892 type indicator, or 0. */
4894 get_type_indicator (bool stat_ok
, mode_t mode
, enum filetype type
)
4898 if (stat_ok
? S_ISREG (mode
) : type
== normal
)
4900 if (stat_ok
&& indicator_style
== classify
&& (mode
& S_IXUGO
))
4907 if (stat_ok
? S_ISDIR (mode
) : type
== directory
|| type
== arg_directory
)
4909 else if (indicator_style
== slash
)
4911 else if (stat_ok
? S_ISLNK (mode
) : type
== symbolic_link
)
4913 else if (stat_ok
? S_ISFIFO (mode
) : type
== fifo
)
4915 else if (stat_ok
? S_ISSOCK (mode
) : type
== sock
)
4917 else if (stat_ok
&& S_ISDOOR (mode
))
4926 print_type_indicator (bool stat_ok
, mode_t mode
, enum filetype type
)
4928 char c
= get_type_indicator (stat_ok
, mode
, type
);
4934 /* Returns if color sequence was printed. */
4936 print_color_indicator (const struct bin_str
*ind
)
4940 /* Need to reset so not dealing with attribute combinations */
4941 if (is_colored (C_NORM
))
4942 restore_default_color ();
4943 put_indicator (&color_indicator
[C_LEFT
]);
4944 put_indicator (ind
);
4945 put_indicator (&color_indicator
[C_RIGHT
]);
4951 /* Returns color indicator or NULL if none. */
4953 static const struct bin_str
*
4954 get_color_indicator (const struct fileinfo
*f
, bool symlink_target
)
4956 enum indicator_no type
;
4957 struct color_ext_type
*ext
; /* Color extension */
4958 size_t len
; /* Length of name */
4967 linkok
= f
->linkok
? 0 : -1;
4972 mode
= file_or_link_mode (f
);
4976 /* Is this a nonexistent file? If so, linkok == -1. */
4978 if (linkok
== -1 && is_colored (C_MISSING
))
4980 else if (!f
->stat_ok
)
4982 static enum indicator_no filetype_indicator
[] = FILETYPE_INDICATORS
;
4983 type
= filetype_indicator
[f
->filetype
];
4991 if ((mode
& S_ISUID
) != 0 && is_colored (C_SETUID
))
4993 else if ((mode
& S_ISGID
) != 0 && is_colored (C_SETGID
))
4995 else if (is_colored (C_CAP
) && f
->has_capability
)
4997 else if ((mode
& S_IXUGO
) != 0 && is_colored (C_EXEC
))
4999 else if ((1 < f
->stat
.st_nlink
) && is_colored (C_MULTIHARDLINK
))
5000 type
= C_MULTIHARDLINK
;
5002 else if (S_ISDIR (mode
))
5006 if ((mode
& S_ISVTX
) && (mode
& S_IWOTH
)
5007 && is_colored (C_STICKY_OTHER_WRITABLE
))
5008 type
= C_STICKY_OTHER_WRITABLE
;
5009 else if ((mode
& S_IWOTH
) != 0 && is_colored (C_OTHER_WRITABLE
))
5010 type
= C_OTHER_WRITABLE
;
5011 else if ((mode
& S_ISVTX
) != 0 && is_colored (C_STICKY
))
5014 else if (S_ISLNK (mode
))
5016 else if (S_ISFIFO (mode
))
5018 else if (S_ISSOCK (mode
))
5020 else if (S_ISBLK (mode
))
5022 else if (S_ISCHR (mode
))
5024 else if (S_ISDOOR (mode
))
5028 /* Classify a file of some other type as C_ORPHAN. */
5033 /* Check the file's suffix only if still classified as C_FILE. */
5037 /* Test if NAME has a recognized suffix. */
5039 len
= strlen (name
);
5040 name
+= len
; /* Pointer to final \0. */
5041 for (ext
= color_ext_list
; ext
!= NULL
; ext
= ext
->next
)
5043 if (ext
->ext
.len
<= len
5044 && c_strncasecmp (name
- ext
->ext
.len
, ext
->ext
.string
,
5050 /* Adjust the color for orphaned symlinks. */
5051 if (type
== C_LINK
&& !linkok
)
5053 if (color_symlink_as_referent
|| is_colored (C_ORPHAN
))
5057 const struct bin_str
*const s
5058 = ext
? &(ext
->seq
) : &color_indicator
[type
];
5060 return s
->string
? s
: NULL
;
5063 /* Output a color indicator (which may contain nulls). */
5065 put_indicator (const struct bin_str
*ind
)
5071 /* If the standard output is a controlling terminal, watch out
5072 for signals, so that the colors can be restored to the
5073 default state if "ls" is suspended or interrupted. */
5075 if (0 <= tcgetpgrp (STDOUT_FILENO
))
5078 prep_non_filename_text ();
5081 fwrite (ind
->string
, ind
->len
, 1, stdout
);
5085 length_of_file_name_and_frills (const struct fileinfo
*f
)
5088 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
5091 len
+= 1 + (format
== with_commas
5092 ? strlen (umaxtostr (f
->stat
.st_ino
, buf
))
5093 : inode_number_width
);
5095 if (print_block_size
)
5096 len
+= 1 + (format
== with_commas
5097 ? strlen (! f
->stat_ok
? "?"
5098 : human_readable (ST_NBLOCKS (f
->stat
), buf
,
5099 human_output_opts
, ST_NBLOCKSIZE
,
5101 : block_size_width
);
5104 len
+= 1 + (format
== with_commas
? strlen (f
->scontext
) : scontext_width
);
5106 len
+= fileinfo_name_width (f
);
5108 if (indicator_style
!= none
)
5110 char c
= get_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
5118 print_many_per_line (void)
5120 size_t row
; /* Current row. */
5121 size_t cols
= calculate_columns (true);
5122 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
5124 /* Calculate the number of rows that will be in each column except possibly
5125 for a short column on the right. */
5126 size_t rows
= cwd_n_used
/ cols
+ (cwd_n_used
% cols
!= 0);
5128 for (row
= 0; row
< rows
; row
++)
5131 size_t filesno
= row
;
5134 /* Print the next row. */
5137 struct fileinfo
const *f
= sorted_file
[filesno
];
5138 size_t name_length
= length_of_file_name_and_frills (f
);
5139 size_t max_name_length
= line_fmt
->col_arr
[col
++];
5140 print_file_name_and_frills (f
, pos
);
5143 if (filesno
>= cwd_n_used
)
5146 indent (pos
+ name_length
, pos
+ max_name_length
);
5147 pos
+= max_name_length
;
5154 print_horizontal (void)
5158 size_t cols
= calculate_columns (false);
5159 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
5160 struct fileinfo
const *f
= sorted_file
[0];
5161 size_t name_length
= length_of_file_name_and_frills (f
);
5162 size_t max_name_length
= line_fmt
->col_arr
[0];
5164 /* Print first entry. */
5165 print_file_name_and_frills (f
, 0);
5168 for (filesno
= 1; filesno
< cwd_n_used
; ++filesno
)
5170 size_t col
= filesno
% cols
;
5179 indent (pos
+ name_length
, pos
+ max_name_length
);
5180 pos
+= max_name_length
;
5183 f
= sorted_file
[filesno
];
5184 print_file_name_and_frills (f
, pos
);
5186 name_length
= length_of_file_name_and_frills (f
);
5187 max_name_length
= line_fmt
->col_arr
[col
];
5192 /* Output name + SEP + ' '. */
5195 print_with_separator (char sep
)
5200 for (filesno
= 0; filesno
< cwd_n_used
; filesno
++)
5202 struct fileinfo
const *f
= sorted_file
[filesno
];
5203 size_t len
= line_length
? length_of_file_name_and_frills (f
) : 0;
5210 || ((pos
+ len
+ 2 < line_length
)
5211 && (pos
<= SIZE_MAX
- len
- 2)))
5219 separator
= eolbyte
;
5223 putchar (separator
);
5226 print_file_name_and_frills (f
, pos
);
5232 /* Assuming cursor is at position FROM, indent up to position TO.
5233 Use a TAB character instead of two or more spaces whenever possible. */
5236 indent (size_t from
, size_t to
)
5240 if (tabsize
!= 0 && to
/ tabsize
> (from
+ 1) / tabsize
)
5243 from
+= tabsize
- from
% tabsize
;
5253 /* Put DIRNAME/NAME into DEST, handling '.' and '/' properly. */
5254 /* FIXME: maybe remove this function someday. See about using a
5255 non-malloc'ing version of file_name_concat. */
5258 attach (char *dest
, char const *dirname
, char const *name
)
5260 char const *dirnamep
= dirname
;
5262 /* Copy dirname if it is not ".". */
5263 if (dirname
[0] != '.' || dirname
[1] != 0)
5266 *dest
++ = *dirnamep
++;
5267 /* Add '/' if 'dirname' doesn't already end with it. */
5268 if (dirnamep
> dirname
&& dirnamep
[-1] != '/')
5276 /* Allocate enough column info suitable for the current number of
5277 files and display columns, and initialize the info to represent the
5278 narrowest possible columns. */
5281 init_column_info (size_t max_cols
)
5285 /* Currently allocated columns in column_info. */
5286 static size_t column_info_alloc
;
5288 if (column_info_alloc
< max_cols
)
5290 size_t new_column_info_alloc
;
5293 if (!max_idx
|| max_cols
< max_idx
/ 2)
5295 /* The number of columns is far less than the display width
5296 allows. Grow the allocation, but only so that it's
5297 double the current requirements. If the display is
5298 extremely wide, this avoids allocating a lot of memory
5299 that is never needed. */
5300 column_info
= xnrealloc (column_info
, max_cols
,
5301 2 * sizeof *column_info
);
5302 new_column_info_alloc
= 2 * max_cols
;
5306 column_info
= xnrealloc (column_info
, max_idx
, sizeof *column_info
);
5307 new_column_info_alloc
= max_idx
;
5310 /* Allocate the new size_t objects by computing the triangle
5311 formula n * (n + 1) / 2, except that we don't need to
5312 allocate the part of the triangle that we've already
5313 allocated. Check for address arithmetic overflow. */
5315 size_t column_info_growth
= new_column_info_alloc
- column_info_alloc
;
5316 size_t s
= column_info_alloc
+ 1 + new_column_info_alloc
;
5317 size_t t
= s
* column_info_growth
;
5318 if (s
< new_column_info_alloc
|| t
/ column_info_growth
!= s
)
5320 p
= xnmalloc (t
/ 2, sizeof *p
);
5323 /* Grow the triangle by parceling out the cells just allocated. */
5324 for (i
= column_info_alloc
; i
< new_column_info_alloc
; i
++)
5326 column_info
[i
].col_arr
= p
;
5330 column_info_alloc
= new_column_info_alloc
;
5333 for (i
= 0; i
< max_cols
; ++i
)
5337 column_info
[i
].valid_len
= true;
5338 column_info
[i
].line_len
= (i
+ 1) * MIN_COLUMN_WIDTH
;
5339 for (j
= 0; j
<= i
; ++j
)
5340 column_info
[i
].col_arr
[j
] = MIN_COLUMN_WIDTH
;
5344 /* Calculate the number of columns needed to represent the current set
5345 of files in the current display width. */
5348 calculate_columns (bool by_columns
)
5350 size_t filesno
; /* Index into cwd_file. */
5351 size_t cols
; /* Number of files across. */
5353 /* Normally the maximum number of columns is determined by the
5354 screen width. But if few files are available this might limit it
5356 size_t max_cols
= 0 < max_idx
&& max_idx
< cwd_n_used
? max_idx
: cwd_n_used
;
5358 init_column_info (max_cols
);
5360 /* Compute the maximum number of possible columns. */
5361 for (filesno
= 0; filesno
< cwd_n_used
; ++filesno
)
5363 struct fileinfo
const *f
= sorted_file
[filesno
];
5364 size_t name_length
= length_of_file_name_and_frills (f
);
5366 for (size_t i
= 0; i
< max_cols
; ++i
)
5368 if (column_info
[i
].valid_len
)
5370 size_t idx
= (by_columns
5371 ? filesno
/ ((cwd_n_used
+ i
) / (i
+ 1))
5372 : filesno
% (i
+ 1));
5373 size_t real_length
= name_length
+ (idx
== i
? 0 : 2);
5375 if (column_info
[i
].col_arr
[idx
] < real_length
)
5377 column_info
[i
].line_len
+= (real_length
5378 - column_info
[i
].col_arr
[idx
]);
5379 column_info
[i
].col_arr
[idx
] = real_length
;
5380 column_info
[i
].valid_len
= (column_info
[i
].line_len
5387 /* Find maximum allowed columns. */
5388 for (cols
= max_cols
; 1 < cols
; --cols
)
5390 if (column_info
[cols
- 1].valid_len
)
5400 if (status
!= EXIT_SUCCESS
)
5404 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name
);
5406 List information about the FILEs (the current directory by default).\n\
5407 Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n\
5410 emit_mandatory_arg_note ();
5413 -a, --all do not ignore entries starting with .\n\
5414 -A, --almost-all do not list implied . and ..\n\
5415 --author with -l, print the author of each file\n\
5416 -b, --escape print C-style escapes for nongraphic characters\n\
5419 --block-size=SIZE with -l, scale sizes by SIZE when printing them;\n\
5420 e.g., '--block-size=M'; see SIZE format below\n\
5424 -B, --ignore-backups do not list implied entries ending with ~\n\
5427 -c with -lt: sort by, and show, ctime (time of last\n\
5428 change of file status information);\n\
5429 with -l: show ctime and sort by name;\n\
5430 otherwise: sort by ctime, newest first\n\
5434 -C list entries by columns\n\
5435 --color[=WHEN] color the output WHEN; more info below\n\
5436 -d, --directory list directories themselves, not their contents\n\
5437 -D, --dired generate output designed for Emacs' dired mode\n\
5440 -f list all entries in directory order\n\
5441 -F, --classify[=WHEN] append indicator (one of */=>@|) to entries WHEN\n\
5442 --file-type likewise, except do not append '*'\n\
5445 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
5446 single-column -1, verbose -l, vertical -C\n\
5450 --full-time like -l --time-style=full-iso\n\
5453 -g like -l, but do not list owner\n\
5456 --group-directories-first\n\
5457 group directories before files;\n\
5458 can be augmented with a --sort option, but any\n\
5459 use of --sort=none (-U) disables grouping\n\
5463 -G, --no-group in a long listing, don't print group names\n\
5466 -h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc.\n\
5467 --si likewise, but use powers of 1000 not 1024\n\
5470 -H, --dereference-command-line\n\
5471 follow symbolic links listed on the command line\n\
5474 --dereference-command-line-symlink-to-dir\n\
5475 follow each command line symbolic link\n\
5476 that points to a directory\n\
5480 --hide=PATTERN do not list implied entries matching shell PATTERN\
5482 (overridden by -a or -A)\n\
5486 --hyperlink[=WHEN] hyperlink file names WHEN\n\
5489 --indicator-style=WORD\n\
5490 append indicator with style WORD to entry names:\n\
5491 none (default), slash (-p),\n\
5492 file-type (--file-type), classify (-F)\n\
5496 -i, --inode print the index number of each file\n\
5497 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\
5501 -k, --kibibytes default to 1024-byte blocks for file system usage;\
5503 used only with -s and per directory totals\n\
5507 -l use a long listing format\n\
5510 -L, --dereference when showing file information for a symbolic\n\
5511 link, show information for the file the link\n\
5512 references rather than for the link itself\n\
5516 -m fill width with a comma separated list of entries\
5520 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
5521 -N, --literal print entry names without quoting\n\
5522 -o like -l, but do not list group information\n\
5523 -p, --indicator-style=slash\n\
5524 append / indicator to directories\n\
5527 -q, --hide-control-chars print ? instead of nongraphic characters\n\
5530 --show-control-chars show nongraphic characters as-is (the default,\n\
5531 unless program is 'ls' and output is a terminal)\
5536 -Q, --quote-name enclose entry names in double quotes\n\
5539 --quoting-style=WORD use quoting style WORD for entry names:\n\
5540 literal, locale, shell, shell-always,\n\
5541 shell-escape, shell-escape-always, c, escape\n\
5542 (overrides QUOTING_STYLE environment variable)\n\
5546 -r, --reverse reverse order while sorting\n\
5547 -R, --recursive list subdirectories recursively\n\
5548 -s, --size print the allocated size of each file, in blocks\n\
5551 -S sort by file size, largest first\n\
5554 --sort=WORD sort by WORD instead of name: none (-U), size (-S)\
5556 time (-t), version (-v), extension (-X), width\n\
5560 --time=WORD select which timestamp used to display or sort;\n\
5561 access time (-u): atime, access, use;\n\
5562 metadata change time (-c): ctime, status;\n\
5563 modified time (default): mtime, modification;\n\
5564 birth time: birth, creation;\n\
5565 with -l, WORD determines which time to show;\n\
5566 with --sort=time, sort by WORD (newest first)\n\
5570 --time-style=TIME_STYLE\n\
5571 time/date format with -l; see TIME_STYLE below\n\
5574 -t sort by time, newest first; see --time\n\
5575 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
5578 -u with -lt: sort by, and show, access time;\n\
5579 with -l: show access time and sort by name;\n\
5580 otherwise: sort by access time, newest first\n\
5584 -U do not sort; list entries in directory order\n\
5587 -v natural sort of (version) numbers within text\n\
5590 -w, --width=COLS set output width to COLS. 0 means no limit\n\
5591 -x list entries by lines instead of by columns\n\
5592 -X sort alphabetically by entry extension\n\
5593 -Z, --context print any security context of each file\n\
5594 --zero end each output line with NUL, not newline\n\
5595 -1 list one file per line\n\
5597 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
5598 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
5602 The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT.\n\
5603 FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2,\n\
5604 then FORMAT1 applies to non-recent files and FORMAT2 to recent files.\n\
5605 TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale.\n\
5606 Also the TIME_STYLE environment variable sets the default style to use.\n\
5610 The WHEN argument defaults to 'always' and can also be 'auto' or 'never'.\n\
5614 Using color to distinguish file types is disabled both by default and\n\
5615 with --color=never. With --color=auto, ls emits color codes only when\n\
5616 standard output is connected to a terminal. The LS_COLORS environment\n\
5617 variable can change the settings. Use the dircolors(1) command to set it.\n\
5623 1 if minor problems (e.g., cannot access subdirectory),\n\
5624 2 if serious trouble (e.g., cannot access command-line argument).\n\
5626 emit_ancillary_info (PROGRAM_NAME
);