1 /* 'dir', 'vdir' and 'ls' directory listing programs for GNU.
2 Copyright (C) 1985-2017 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* If ls_mode is LS_MULTI_COL,
18 the multi-column format is the default regardless
19 of the type of output device.
20 This is for the 'dir' program.
22 If ls_mode is LS_LONG_FORMAT,
23 the long format is the default regardless of the
24 type of output device.
25 This is for the 'vdir' program.
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. */
92 #include "filenamecat.h"
93 #include "hard-locale.h"
97 #include "filevercmp.h"
100 #include "mbswidth.h"
105 #include "stat-size.h"
106 #include "stat-time.h"
107 #include "strftime.h"
108 #include "xdectoint.h"
110 #include "areadlink.h"
111 #include "mbsalign.h"
112 #include "dircolors.h"
113 #include "xgethostname.h"
115 #include "canonicalize.h"
117 /* Include <sys/capability.h> last to avoid a clash of <sys/types.h>
118 include guards with some premature versions of libcap.
119 For more details, see <https://bugzilla.redhat.com/483548>. */
121 # include <sys/capability.h>
124 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
125 : (ls_mode == LS_MULTI_COL \
129 proper_name ("Richard M. Stallman"), \
130 proper_name ("David MacKenzie")
132 #define obstack_chunk_alloc malloc
133 #define obstack_chunk_free free
135 /* Return an int indicating the result of comparing two integers.
136 Subtracting doesn't always work, due to overflow. */
137 #define longdiff(a, b) ((a) < (b) ? -1 : (a) > (b))
139 /* Unix-based readdir implementations have historically returned a dirent.d_ino
140 value that is sometimes not equal to the stat-obtained st_ino value for
141 that same entry. This error occurs for a readdir entry that refers
142 to a mount point. readdir's error is to return the inode number of
143 the underlying directory -- one that typically cannot be stat'ed, as
144 long as a file system is mounted on that directory. RELIABLE_D_INO
145 encapsulates whether we can use the more efficient approach of relying
146 on readdir-supplied d_ino values, or whether we must incur the cost of
147 calling stat or lstat to obtain each guaranteed-valid inode number. */
149 #ifndef READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
150 # define READDIR_LIES_ABOUT_MOUNTPOINT_D_INO 1
153 #if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
154 # define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
156 # define RELIABLE_D_INO(dp) D_INO (dp)
159 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
160 # define st_author st_uid
177 /* Display letters and indicators for each filetype.
178 Keep these in sync with enum filetype. */
179 static char const filetype_letter
[] = "?pcdb-lswd";
181 /* Ensure that filetype and filetype_letter have the same
182 number of elements. */
183 verify (sizeof filetype_letter
- 1 == arg_directory
+ 1);
185 #define FILETYPE_INDICATORS \
187 C_ORPHAN, C_FIFO, C_CHR, C_DIR, C_BLK, C_FILE, \
188 C_LINK, C_SOCK, C_FILE, C_DIR \
194 ACL_T_LSM_CONTEXT_ONLY
,
203 /* For symbolic link, name of the file linked to, otherwise zero. */
206 /* For terminal hyperlinks. */
211 enum filetype filetype
;
213 /* For symbolic link and long listing, st_mode of file linked to, otherwise
217 /* security context. */
222 /* For symbolic link and color printing, true if linked-to file
223 exists, otherwise false. */
226 /* For long listings, true if the file has an access control list,
227 or a security context. */
228 enum acl_type acl_type
;
230 /* For color listings, true if a regular file has capability info. */
233 /* Whether file name needs quoting. tri-state with -1 == unknown. */
237 #define LEN_STR_PAIR(s) sizeof (s) - 1, s
239 /* Null is a valid character in a color indicator (think about Epson
240 printers, for example) so we have to use a length/buffer string
245 size_t len
; /* Number of bytes */
246 const char *string
; /* Pointer to the same */
250 # define tcgetpgrp(Fd) 0
253 static size_t quote_name (char const *name
,
254 struct quoting_options
const *options
,
255 int needs_general_quoting
,
256 const struct bin_str
*color
,
257 bool allow_pad
, struct obstack
*stack
,
258 char const *absolute_name
);
259 static size_t quote_name_buf (char **inbuf
, size_t bufsize
, char *name
,
260 struct quoting_options
const *options
,
261 int needs_general_quoting
, size_t *width
,
263 static char *make_link_name (char const *name
, char const *linkname
);
264 static int decode_switches (int argc
, char **argv
);
265 static bool file_ignored (char const *name
);
266 static uintmax_t gobble_file (char const *name
, enum filetype type
,
267 ino_t inode
, bool command_line_arg
,
268 char const *dirname
);
269 static const struct bin_str
* get_color_indicator (const struct fileinfo
*f
,
270 bool symlink_target
);
271 static bool print_color_indicator (const struct bin_str
*ind
);
272 static void put_indicator (const struct bin_str
*ind
);
273 static void add_ignore_pattern (const char *pattern
);
274 static void attach (char *dest
, const char *dirname
, const char *name
);
275 static void clear_files (void);
276 static void extract_dirs_from_files (char const *dirname
,
277 bool command_line_arg
);
278 static void get_link_name (char const *filename
, struct fileinfo
*f
,
279 bool command_line_arg
);
280 static void indent (size_t from
, size_t to
);
281 static size_t calculate_columns (bool by_columns
);
282 static void print_current_files (void);
283 static void print_dir (char const *name
, char const *realname
,
284 bool command_line_arg
);
285 static size_t print_file_name_and_frills (const struct fileinfo
*f
,
287 static void print_horizontal (void);
288 static int format_user_width (uid_t u
);
289 static int format_group_width (gid_t g
);
290 static void print_long_format (const struct fileinfo
*f
);
291 static void print_many_per_line (void);
292 static size_t print_name_with_quoting (const struct fileinfo
*f
,
294 struct obstack
*stack
,
296 static void prep_non_filename_text (void);
297 static bool print_type_indicator (bool stat_ok
, mode_t mode
,
299 static void print_with_separator (char sep
);
300 static void queue_directory (char const *name
, char const *realname
,
301 bool command_line_arg
);
302 static void sort_files (void);
303 static void parse_ls_color (void);
305 static void getenv_quoting_style (void);
307 /* Initial size of hash table.
308 Most hierarchies are likely to be shallower than this. */
309 #define INITIAL_TABLE_SIZE 30
311 /* The set of 'active' directories, from the current command-line argument
312 to the level in the hierarchy at which files are being listed.
313 A directory is represented by its device and inode numbers (struct dev_ino).
314 A directory is added to this set when ls begins listing it or its
315 entries, and it is removed from the set just after ls has finished
316 processing it. This set is used solely to detect loops, e.g., with
317 mkdir loop; cd loop; ln -s ../loop sub; ls -RL */
318 static Hash_table
*active_dir_set
;
320 #define LOOP_DETECT (!!active_dir_set)
322 /* The table of files in the current directory:
324 'cwd_file' points to a vector of 'struct fileinfo', one per file.
325 'cwd_n_alloc' is the number of elements space has been allocated for.
326 'cwd_n_used' is the number actually in use. */
328 /* Address of block containing the files that are described. */
329 static struct fileinfo
*cwd_file
;
331 /* Length of block that 'cwd_file' points to, measured in files. */
332 static size_t cwd_n_alloc
;
334 /* Index of first unused slot in 'cwd_file'. */
335 static size_t cwd_n_used
;
337 /* Whether files needs may need padding due to quoting. */
338 static bool cwd_some_quoted
;
340 /* Whether quoting style _may_ add outer quotes,
341 and whether aligning those is useful. */
342 static bool align_variable_outer_quotes
;
344 /* Vector of pointers to files, in proper sorted order, and the number
345 of entries allocated for it. */
346 static void **sorted_file
;
347 static size_t sorted_file_alloc
;
349 /* When true, in a color listing, color each symlink name according to the
350 type of file it points to. Otherwise, color them according to the 'ln'
351 directive in LS_COLORS. Dangling (orphan) symlinks are treated specially,
352 regardless. This is set when 'ln=target' appears in LS_COLORS. */
354 static bool color_symlink_as_referent
;
356 static char const *hostname
;
358 /* mode of appropriate file for colorization */
359 #define FILE_OR_LINK_MODE(File) \
360 ((color_symlink_as_referent && (File)->linkok) \
361 ? (File)->linkmode : (File)->stat.st_mode)
364 /* Record of one pending directory waiting to be listed. */
369 /* If the directory is actually the file pointed to by a symbolic link we
370 were told to list, 'realname' will contain the name of the symbolic
371 link, otherwise zero. */
373 bool command_line_arg
;
374 struct pending
*next
;
377 static struct pending
*pending_dirs
;
379 /* Current time in seconds and nanoseconds since 1970, updated as
380 needed when deciding whether a file is recent. */
382 static struct timespec current_time
;
384 static bool print_scontext
;
385 static char UNKNOWN_SECURITY_CONTEXT
[] = "?";
387 /* Whether any of the files has an ACL. This affects the width of the
390 static bool any_has_acl
;
392 /* The number of columns to use for columns containing inode numbers,
393 block sizes, link counts, owners, groups, authors, major device
394 numbers, minor device numbers, and file sizes, respectively. */
396 static int inode_number_width
;
397 static int block_size_width
;
398 static int nlink_width
;
399 static int scontext_width
;
400 static int owner_width
;
401 static int group_width
;
402 static int author_width
;
403 static int major_device_number_width
;
404 static int minor_device_number_width
;
405 static int file_size_width
;
409 /* long_format for lots of info, one per line.
410 one_per_line for just names, one per line.
411 many_per_line for just names, many per line, sorted vertically.
412 horizontal for just names, many per line, sorted horizontally.
413 with_commas for just names, many per line, separated by commas.
415 -l (and other options that imply -l), -1, -C, -x and -m control
420 long_format
, /* -l and other options that imply -l */
421 one_per_line
, /* -1 */
422 many_per_line
, /* -C */
427 static enum format format
;
429 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
430 ISO-style timestamps, though shorter than 'full-iso'. 'iso' uses shorter
431 ISO-style timestamps. 'locale' uses locale-dependent timestamps. */
434 full_iso_time_style
, /* --time-style=full-iso */
435 long_iso_time_style
, /* --time-style=long-iso */
436 iso_time_style
, /* --time-style=iso */
437 locale_time_style
/* --time-style=locale */
440 static char const *const time_style_args
[] =
442 "full-iso", "long-iso", "iso", "locale", NULL
444 static enum time_style
const time_style_types
[] =
446 full_iso_time_style
, long_iso_time_style
, iso_time_style
,
449 ARGMATCH_VERIFY (time_style_args
, time_style_types
);
451 /* Type of time to print or sort by. Controlled by -c and -u.
452 The values of each item of this enum are important since they are
453 used as indices in the sort functions array (see sort_files()). */
457 time_mtime
, /* default */
460 time_numtypes
/* the number of elements of this enum */
463 static enum time_type time_type
;
465 /* The file characteristic to sort by. Controlled by -t, -S, -U, -X, -v.
466 The values of each item of this enum are important since they are
467 used as indices in the sort functions array (see sort_files()). */
471 sort_none
= -1, /* -U */
472 sort_name
, /* default */
473 sort_extension
, /* -X */
475 sort_version
, /* -v */
477 sort_numtypes
/* the number of elements of this enum */
480 static enum sort_type sort_type
;
482 /* Direction of sort.
483 false means highest first if numeric,
484 lowest first if alphabetic;
485 these are the defaults.
486 true means the opposite order in each case. -r */
488 static bool sort_reverse
;
490 /* True means to display owner information. -g turns this off. */
492 static bool print_owner
= true;
494 /* True means to display author information. */
496 static bool print_author
;
498 /* True means to display group information. -G and -o turn this off. */
500 static bool print_group
= true;
502 /* True means print the user and group id's as numbers rather
505 static bool numeric_ids
;
507 /* True means mention the size in blocks of each file. -s */
509 static bool print_block_size
;
511 /* Human-readable options for output, when printing block counts. */
512 static int human_output_opts
;
514 /* The units to use when printing block counts. */
515 static uintmax_t output_block_size
;
517 /* Likewise, but for file sizes. */
518 static int file_human_output_opts
;
519 static uintmax_t file_output_block_size
= 1;
521 /* Follow the output with a special string. Using this format,
522 Emacs' dired mode starts up twice as fast, and can handle all
523 strange characters in file names. */
526 /* 'none' means don't mention the type of files.
527 'slash' means mention directories only, with a '/'.
528 'file_type' means mention file types.
529 'classify' means mention file types and mark executables.
531 Controlled by -F, -p, and --indicator-style. */
535 none
, /* --indicator-style=none */
536 slash
, /* -p, --indicator-style=slash */
537 file_type
, /* --indicator-style=file-type */
538 classify
/* -F, --indicator-style=classify */
541 static enum indicator_style indicator_style
;
543 /* Names of indicator styles. */
544 static char const *const indicator_style_args
[] =
546 "none", "slash", "file-type", "classify", NULL
548 static enum indicator_style
const indicator_style_types
[] =
550 none
, slash
, file_type
, classify
552 ARGMATCH_VERIFY (indicator_style_args
, indicator_style_types
);
554 /* True means use colors to mark types. Also define the different
555 colors as well as the stuff for the LS_COLORS environment variable.
556 The LS_COLORS variable is now in a termcap-like format. */
558 static bool print_with_color
;
560 static bool print_hyperlink
;
562 /* Whether we used any colors in the output so far. If so, we will
563 need to restore the default color later. If not, we will need to
564 call prep_non_filename_text before using color for the first time. */
566 static bool used_color
= false;
570 when_never
, /* 0: default or --color=never */
571 when_always
, /* 1: --color=always */
572 when_if_tty
/* 2: --color=tty */
575 enum Dereference_symlink
579 DEREF_COMMAND_LINE_ARGUMENTS
, /* -H */
580 DEREF_COMMAND_LINE_SYMLINK_TO_DIR
, /* the default, in certain cases */
581 DEREF_ALWAYS
/* -L */
586 C_LEFT
, C_RIGHT
, C_END
, C_RESET
, C_NORM
, C_FILE
, C_DIR
, C_LINK
,
588 C_BLK
, C_CHR
, C_MISSING
, C_ORPHAN
, C_EXEC
, C_DOOR
, C_SETUID
, C_SETGID
,
589 C_STICKY
, C_OTHER_WRITABLE
, C_STICKY_OTHER_WRITABLE
, C_CAP
, C_MULTIHARDLINK
,
593 static const char *const indicator_name
[]=
595 "lc", "rc", "ec", "rs", "no", "fi", "di", "ln", "pi", "so",
596 "bd", "cd", "mi", "or", "ex", "do", "su", "sg", "st",
597 "ow", "tw", "ca", "mh", "cl", NULL
600 struct color_ext_type
602 struct bin_str ext
; /* The extension we're looking for */
603 struct bin_str seq
; /* The sequence to output when we do */
604 struct color_ext_type
*next
; /* Next in list */
607 static struct bin_str color_indicator
[] =
609 { LEN_STR_PAIR ("\033[") }, /* lc: Left of color sequence */
610 { LEN_STR_PAIR ("m") }, /* rc: Right of color sequence */
611 { 0, NULL
}, /* ec: End color (replaces lc+rs+rc) */
612 { LEN_STR_PAIR ("0") }, /* rs: Reset to ordinary colors */
613 { 0, NULL
}, /* no: Normal */
614 { 0, NULL
}, /* fi: File: default */
615 { LEN_STR_PAIR ("01;34") }, /* di: Directory: bright blue */
616 { LEN_STR_PAIR ("01;36") }, /* ln: Symlink: bright cyan */
617 { LEN_STR_PAIR ("33") }, /* pi: Pipe: yellow/brown */
618 { LEN_STR_PAIR ("01;35") }, /* so: Socket: bright magenta */
619 { LEN_STR_PAIR ("01;33") }, /* bd: Block device: bright yellow */
620 { LEN_STR_PAIR ("01;33") }, /* cd: Char device: bright yellow */
621 { 0, NULL
}, /* mi: Missing file: undefined */
622 { 0, NULL
}, /* or: Orphaned symlink: undefined */
623 { LEN_STR_PAIR ("01;32") }, /* ex: Executable: bright green */
624 { LEN_STR_PAIR ("01;35") }, /* do: Door: bright magenta */
625 { LEN_STR_PAIR ("37;41") }, /* su: setuid: white on red */
626 { LEN_STR_PAIR ("30;43") }, /* sg: setgid: black on yellow */
627 { LEN_STR_PAIR ("37;44") }, /* st: sticky: black on blue */
628 { LEN_STR_PAIR ("34;42") }, /* ow: other-writable: blue on green */
629 { LEN_STR_PAIR ("30;42") }, /* tw: ow w/ sticky: black on green */
630 { LEN_STR_PAIR ("30;41") }, /* ca: black on red */
631 { 0, NULL
}, /* mh: disabled by default */
632 { LEN_STR_PAIR ("\033[K") }, /* cl: clear to end of line */
636 static struct color_ext_type
*color_ext_list
= NULL
;
638 /* Buffer for color sequences */
639 static char *color_buf
;
641 /* True means to check for orphaned symbolic link, for displaying
644 static bool check_symlink_color
;
646 /* True means mention the inode number of each file. -i */
648 static bool print_inode
;
650 /* What to do with symbolic links. Affected by -d, -F, -H, -l (and
651 other options that imply -l), and -L. */
653 static enum Dereference_symlink dereference
;
655 /* True means when a directory is found, display info on its
658 static bool recursive
;
660 /* True means when an argument is a directory name, display info
663 static bool immediate_dirs
;
665 /* True means that directories are grouped before files. */
667 static bool directories_first
;
669 /* Which files to ignore. */
673 /* Ignore files whose names start with '.', and files specified by
674 --hide and --ignore. */
677 /* Ignore '.', '..', and files specified by --ignore. */
678 IGNORE_DOT_AND_DOTDOT
,
680 /* Ignore only files specified by --ignore. */
684 /* A linked list of shell-style globbing patterns. If a non-argument
685 file name matches any of these patterns, it is ignored.
686 Controlled by -I. Multiple -I options accumulate.
687 The -B option adds '*~' and '.*~' to this list. */
689 struct ignore_pattern
692 struct ignore_pattern
*next
;
695 static struct ignore_pattern
*ignore_patterns
;
697 /* Similar to IGNORE_PATTERNS, except that -a or -A causes this
698 variable itself to be ignored. */
699 static struct ignore_pattern
*hide_patterns
;
701 /* True means output nongraphic chars in file names as '?'.
702 (-q, --hide-control-chars)
703 qmark_funny_chars and the quoting style (-Q, --quoting-style=WORD) are
704 independent. The algorithm is: first, obey the quoting style to get a
705 string representing the file name; then, if qmark_funny_chars is set,
706 replace all nonprintable chars in that string with '?'. It's necessary
707 to replace nonprintable chars even in quoted strings, because we don't
708 want to mess up the terminal if control chars get sent to it, and some
709 quoting methods pass through control chars as-is. */
710 static bool qmark_funny_chars
;
712 /* Quoting options for file and dir name output. */
714 static struct quoting_options
*filename_quoting_options
;
715 static struct quoting_options
*dirname_quoting_options
;
717 /* The number of chars per hardware tab stop. Setting this to zero
718 inhibits the use of TAB characters for separating columns. -T */
719 static size_t tabsize
;
721 /* True means print each directory name before listing it. */
723 static bool print_dir_name
;
725 /* The line length to use for breaking lines in many-per-line format.
726 Can be set with -w. */
728 static size_t line_length
;
730 /* The local time zone rules, as per the TZ environment variable. */
732 static timezone_t localtz
;
734 /* If true, the file listing format requires that stat be called on
737 static bool format_needs_stat
;
739 /* Similar to 'format_needs_stat', but set if only the file type is
742 static bool format_needs_type
;
744 /* An arbitrary limit on the number of bytes in a printed timestamp.
745 This is set to a relatively small value to avoid the need to worry
746 about denial-of-service attacks on servers that run "ls" on behalf
747 of remote clients. 1000 bytes should be enough for any practical
750 enum { TIME_STAMP_LEN_MAXIMUM
= MAX (1000, INT_STRLEN_BOUND (time_t)) };
752 /* strftime formats for non-recent and recent files, respectively, in
755 static char const *long_time_format
[2] =
757 /* strftime format for non-recent files (older than 6 months), in
758 -l output. This should contain the year, month and day (at
759 least), in an order that is understood by people in your
760 locale's territory. Please try to keep the number of used
761 screen columns small, because many people work in windows with
762 only 80 columns. But make this as wide as the other string
763 below, for recent files. */
764 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
765 so be wary of using variable width fields from the locale.
766 Note %b is handled specially by ls and aligned correctly.
767 Note also that specifying a width as in %5b is erroneous as strftime
768 will count bytes rather than characters in multibyte locales. */
770 /* strftime format for recent files (younger than 6 months), in -l
771 output. This should contain the month, day and time (at
772 least), in an order that is understood by people in your
773 locale's territory. Please try to keep the number of used
774 screen columns small, because many people work in windows with
775 only 80 columns. But make this as wide as the other string
776 above, for non-recent files. */
777 /* TRANSLATORS: ls output needs to be aligned for ease of reading,
778 so be wary of using variable width fields from the locale.
779 Note %b is handled specially by ls and aligned correctly.
780 Note also that specifying a width as in %5b is erroneous as strftime
781 will count bytes rather than characters in multibyte locales. */
785 /* The set of signals that are caught. */
787 static sigset_t caught_signals
;
789 /* If nonzero, the value of the pending fatal signal. */
791 static sig_atomic_t volatile interrupt_signal
;
793 /* A count of the number of pending stop signals that have been received. */
795 static sig_atomic_t volatile stop_signal_count
;
797 /* Desired exit status. */
799 static int exit_status
;
804 /* "ls" had a minor problem. E.g., while processing a directory,
805 ls obtained the name of an entry via readdir, yet was later
806 unable to stat that name. This happens when listing a directory
807 in which entries are actively being removed or renamed. */
808 LS_MINOR_PROBLEM
= 1,
810 /* "ls" had more serious trouble (e.g., memory exhausted, invalid
811 option or failure to stat a command line argument. */
815 /* For long options that have no equivalent short option, use a
816 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
819 AUTHOR_OPTION
= CHAR_MAX
+ 1,
822 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
,
823 FILE_TYPE_INDICATOR_OPTION
,
826 GROUP_DIRECTORIES_FIRST_OPTION
,
829 INDICATOR_STYLE_OPTION
,
830 QUOTING_STYLE_OPTION
,
831 SHOW_CONTROL_CHARS_OPTION
,
838 static struct option
const long_options
[] =
840 {"all", no_argument
, NULL
, 'a'},
841 {"escape", no_argument
, NULL
, 'b'},
842 {"directory", no_argument
, NULL
, 'd'},
843 {"dired", no_argument
, NULL
, 'D'},
844 {"full-time", no_argument
, NULL
, FULL_TIME_OPTION
},
845 {"group-directories-first", no_argument
, NULL
,
846 GROUP_DIRECTORIES_FIRST_OPTION
},
847 {"human-readable", no_argument
, NULL
, 'h'},
848 {"inode", no_argument
, NULL
, 'i'},
849 {"kibibytes", no_argument
, NULL
, 'k'},
850 {"numeric-uid-gid", no_argument
, NULL
, 'n'},
851 {"no-group", no_argument
, NULL
, 'G'},
852 {"hide-control-chars", no_argument
, NULL
, 'q'},
853 {"reverse", no_argument
, NULL
, 'r'},
854 {"size", no_argument
, NULL
, 's'},
855 {"width", required_argument
, NULL
, 'w'},
856 {"almost-all", no_argument
, NULL
, 'A'},
857 {"ignore-backups", no_argument
, NULL
, 'B'},
858 {"classify", no_argument
, NULL
, 'F'},
859 {"file-type", no_argument
, NULL
, FILE_TYPE_INDICATOR_OPTION
},
860 {"si", no_argument
, NULL
, SI_OPTION
},
861 {"dereference-command-line", no_argument
, NULL
, 'H'},
862 {"dereference-command-line-symlink-to-dir", no_argument
, NULL
,
863 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
},
864 {"hide", required_argument
, NULL
, HIDE_OPTION
},
865 {"ignore", required_argument
, NULL
, 'I'},
866 {"indicator-style", required_argument
, NULL
, INDICATOR_STYLE_OPTION
},
867 {"dereference", no_argument
, NULL
, 'L'},
868 {"literal", no_argument
, NULL
, 'N'},
869 {"quote-name", no_argument
, NULL
, 'Q'},
870 {"quoting-style", required_argument
, NULL
, QUOTING_STYLE_OPTION
},
871 {"recursive", no_argument
, NULL
, 'R'},
872 {"format", required_argument
, NULL
, FORMAT_OPTION
},
873 {"show-control-chars", no_argument
, NULL
, SHOW_CONTROL_CHARS_OPTION
},
874 {"sort", required_argument
, NULL
, SORT_OPTION
},
875 {"tabsize", required_argument
, NULL
, 'T'},
876 {"time", required_argument
, NULL
, TIME_OPTION
},
877 {"time-style", required_argument
, NULL
, TIME_STYLE_OPTION
},
878 {"color", optional_argument
, NULL
, COLOR_OPTION
},
879 {"hyperlink", optional_argument
, NULL
, HYPERLINK_OPTION
},
880 {"block-size", required_argument
, NULL
, BLOCK_SIZE_OPTION
},
881 {"context", no_argument
, 0, 'Z'},
882 {"author", no_argument
, NULL
, AUTHOR_OPTION
},
883 {GETOPT_HELP_OPTION_DECL
},
884 {GETOPT_VERSION_OPTION_DECL
},
888 static char const *const format_args
[] =
890 "verbose", "long", "commas", "horizontal", "across",
891 "vertical", "single-column", NULL
893 static enum format
const format_types
[] =
895 long_format
, long_format
, with_commas
, horizontal
, horizontal
,
896 many_per_line
, one_per_line
898 ARGMATCH_VERIFY (format_args
, format_types
);
900 static char const *const sort_args
[] =
902 "none", "time", "size", "extension", "version", NULL
904 static enum sort_type
const sort_types
[] =
906 sort_none
, sort_time
, sort_size
, sort_extension
, sort_version
908 ARGMATCH_VERIFY (sort_args
, sort_types
);
910 static char const *const time_args
[] =
912 "atime", "access", "use", "ctime", "status", NULL
914 static enum time_type
const time_types
[] =
916 time_atime
, time_atime
, time_atime
, time_ctime
, time_ctime
918 ARGMATCH_VERIFY (time_args
, time_types
);
920 static char const *const when_args
[] =
922 /* force and none are for compatibility with another color-ls version */
923 "always", "yes", "force",
924 "never", "no", "none",
925 "auto", "tty", "if-tty", NULL
927 static enum when_type
const when_types
[] =
929 when_always
, when_always
, when_always
,
930 when_never
, when_never
, when_never
,
931 when_if_tty
, when_if_tty
, when_if_tty
933 ARGMATCH_VERIFY (when_args
, when_types
);
935 /* Information about filling a column. */
943 /* Array with information about column filledness. */
944 static struct column_info
*column_info
;
946 /* Maximum number of columns ever possible for this display. */
947 static size_t max_idx
;
949 /* The minimum width of a column is 3: 1 character for the name and 2
950 for the separating white space. */
951 #define MIN_COLUMN_WIDTH 3
954 /* This zero-based index is used solely with the --dired option.
955 When that option is in effect, this counter is incremented for each
956 byte of output generated by this program so that the beginning
957 and ending indices (in that output) of every file name can be recorded
958 and later output themselves. */
959 static size_t dired_pos
;
961 #define DIRED_PUTCHAR(c) do {putchar ((c)); ++dired_pos;} while (0)
963 /* Write S to STREAM and increment DIRED_POS by S_LEN. */
964 #define DIRED_FPUTS(s, stream, s_len) \
965 do {fputs (s, stream); dired_pos += s_len;} while (0)
967 /* Like DIRED_FPUTS, but for use when S is a literal string. */
968 #define DIRED_FPUTS_LITERAL(s, stream) \
969 do {fputs (s, stream); dired_pos += sizeof (s) - 1;} while (0)
971 #define DIRED_INDENT() \
975 DIRED_FPUTS_LITERAL (" ", stdout); \
979 /* With --dired, store pairs of beginning and ending indices of file names. */
980 static struct obstack dired_obstack
;
982 /* With --dired, store pairs of beginning and ending indices of any
983 directory names that appear as headers (just before 'total' line)
984 for lists of directory entries. Such directory names are seen when
985 listing hierarchies using -R and when a directory is listed with at
986 least one other command line argument. */
987 static struct obstack subdired_obstack
;
989 /* Save the current index on the specified obstack, OBS. */
990 #define PUSH_CURRENT_DIRED_POS(obs) \
994 obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
998 /* With -R, this stack is used to help detect directory cycles.
999 The device/inode pairs on this stack mirror the pairs in the
1000 active_dir_set hash table. */
1001 static struct obstack dev_ino_obstack
;
1003 /* Push a pair onto the device/inode stack. */
1005 dev_ino_push (dev_t dev
, ino_t ino
)
1009 int dev_ino_size
= sizeof *di
;
1010 obstack_blank (&dev_ino_obstack
, dev_ino_size
);
1011 vdi
= obstack_next_free (&dev_ino_obstack
);
1018 /* Pop a dev/ino struct off the global dev_ino_obstack
1019 and return that struct. */
1020 static struct dev_ino
1025 int dev_ino_size
= sizeof *di
;
1026 assert (dev_ino_size
<= obstack_object_size (&dev_ino_obstack
));
1027 obstack_blank_fast (&dev_ino_obstack
, -dev_ino_size
);
1028 vdi
= obstack_next_free (&dev_ino_obstack
);
1033 /* Note the use commented out below:
1034 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
1039 assert (0 <= stat (Name, &sb)); \
1040 assert (sb.st_dev == Di.st_dev); \
1041 assert (sb.st_ino == Di.st_ino); \
1046 /* Write to standard output PREFIX, followed by the quoting style and
1047 a space-separated list of the integers stored in OS all on one line. */
1050 dired_dump_obstack (const char *prefix
, struct obstack
*os
)
1054 n_pos
= obstack_object_size (os
) / sizeof (dired_pos
);
1057 size_t *pos
= (size_t *) obstack_finish (os
);
1058 fputs (prefix
, stdout
);
1059 for (size_t i
= 0; i
< n_pos
; i
++)
1060 printf (" %lu", (unsigned long int) pos
[i
]);
1065 /* Return the address of the first plain %b spec in FMT, or NULL if
1066 there is no such spec. %5b etc. do not match, so that user
1067 widths/flags are honored. */
1069 static char const * _GL_ATTRIBUTE_PURE
1070 first_percent_b (char const *fmt
)
1076 case 'b': return fmt
;
1077 case '%': fmt
++; break;
1082 static char RFC3986
[256];
1084 file_escape_init (void)
1086 for (int i
= 0; i
< 256; i
++)
1087 RFC3986
[i
] |= c_isalnum (i
) || i
== '~' || i
== '-' || i
== '.' || i
== '_';
1090 /* Read the abbreviated month names from the locale, to align them
1091 and to determine the max width of the field and to truncate names
1092 greater than our max allowed.
1093 Note even though this handles multibyte locales correctly
1094 it's not restricted to them as single byte locales can have
1095 variable width abbreviated months and also precomputing/caching
1096 the names was seen to increase the performance of ls significantly. */
1098 /* max number of display cells to use */
1099 enum { MAX_MON_WIDTH
= 5 };
1100 /* abformat[RECENT][MON] is the format to use for timestamps with
1101 recentness RECENT and month MON. */
1102 enum { ABFORMAT_SIZE
= 128 };
1103 static char abformat
[2][12][ABFORMAT_SIZE
];
1104 /* True if precomputed formats should be used. This can be false if
1105 nl_langinfo fails, if a format or month abbreviation is unusually
1106 long, or if a month abbreviation contains '%'. */
1107 static bool use_abformat
;
1109 /* Store into ABMON the abbreviated month names, suitably aligned.
1110 Return true if successful. */
1113 abmon_init (char abmon
[12][ABFORMAT_SIZE
])
1115 #ifndef HAVE_NL_LANGINFO
1118 size_t required_mon_width
= MAX_MON_WIDTH
;
1119 size_t curr_max_width
;
1122 curr_max_width
= required_mon_width
;
1123 required_mon_width
= 0;
1124 for (int i
= 0; i
< 12; i
++)
1126 size_t width
= curr_max_width
;
1127 char const *abbr
= nl_langinfo (ABMON_1
+ i
);
1128 if (strchr (abbr
, '%'))
1130 size_t req
= mbsalign (abbr
, abmon
[i
], ABFORMAT_SIZE
,
1131 &width
, MBS_ALIGN_LEFT
, 0);
1132 if (! (req
< ABFORMAT_SIZE
))
1134 required_mon_width
= MAX (required_mon_width
, width
);
1137 while (curr_max_width
> required_mon_width
);
1143 /* Initialize ABFORMAT and USE_ABFORMAT. */
1146 abformat_init (void)
1149 for (int recent
= 0; recent
< 2; recent
++)
1150 pb
[recent
] = first_percent_b (long_time_format
[recent
]);
1151 if (! (pb
[0] || pb
[1]))
1154 char abmon
[12][ABFORMAT_SIZE
];
1155 if (! abmon_init (abmon
))
1158 for (int recent
= 0; recent
< 2; recent
++)
1160 char const *fmt
= long_time_format
[recent
];
1161 for (int i
= 0; i
< 12; i
++)
1163 char *nfmt
= abformat
[recent
][i
];
1167 nbytes
= snprintf (nfmt
, ABFORMAT_SIZE
, "%s", fmt
);
1170 if (! (pb
[recent
] - fmt
<= MIN (ABFORMAT_SIZE
, INT_MAX
)))
1172 int prefix_len
= pb
[recent
] - fmt
;
1173 nbytes
= snprintf (nfmt
, ABFORMAT_SIZE
, "%.*s%s%s",
1174 prefix_len
, fmt
, abmon
[i
], pb
[recent
] + 2);
1177 if (! (0 <= nbytes
&& nbytes
< ABFORMAT_SIZE
))
1182 use_abformat
= true;
1186 dev_ino_hash (void const *x
, size_t table_size
)
1188 struct dev_ino
const *p
= x
;
1189 return (uintmax_t) p
->st_ino
% table_size
;
1193 dev_ino_compare (void const *x
, void const *y
)
1195 struct dev_ino
const *a
= x
;
1196 struct dev_ino
const *b
= y
;
1197 return SAME_INODE (*a
, *b
) ? true : false;
1201 dev_ino_free (void *x
)
1206 /* Add the device/inode pair (P->st_dev/P->st_ino) to the set of
1207 active directories. Return true if there is already a matching
1208 entry in the table. */
1211 visit_dir (dev_t dev
, ino_t ino
)
1213 struct dev_ino
*ent
;
1214 struct dev_ino
*ent_from_table
;
1217 ent
= xmalloc (sizeof *ent
);
1221 /* Attempt to insert this entry into the table. */
1222 ent_from_table
= hash_insert (active_dir_set
, ent
);
1224 if (ent_from_table
== NULL
)
1226 /* Insertion failed due to lack of memory. */
1230 found_match
= (ent_from_table
!= ent
);
1234 /* ent was not inserted, so free it. */
1242 free_pending_ent (struct pending
*p
)
1250 is_colored (enum indicator_no type
)
1252 size_t len
= color_indicator
[type
].len
;
1253 char const *s
= color_indicator
[type
].string
;
1255 || (len
== 1 && STRNCMP_LIT (s
, "0") == 0)
1256 || (len
== 2 && STRNCMP_LIT (s
, "00") == 0));
1260 restore_default_color (void)
1262 put_indicator (&color_indicator
[C_LEFT
]);
1263 put_indicator (&color_indicator
[C_RIGHT
]);
1267 set_normal_color (void)
1269 if (print_with_color
&& is_colored (C_NORM
))
1271 put_indicator (&color_indicator
[C_LEFT
]);
1272 put_indicator (&color_indicator
[C_NORM
]);
1273 put_indicator (&color_indicator
[C_RIGHT
]);
1277 /* An ordinary signal was received; arrange for the program to exit. */
1280 sighandler (int sig
)
1283 signal (sig
, SIG_IGN
);
1284 if (! interrupt_signal
)
1285 interrupt_signal
= sig
;
1288 /* A SIGTSTP was received; arrange for the program to suspend itself. */
1291 stophandler (int sig
)
1294 signal (sig
, stophandler
);
1295 if (! interrupt_signal
)
1296 stop_signal_count
++;
1299 /* Process any pending signals. If signals are caught, this function
1300 should be called periodically. Ideally there should never be an
1301 unbounded amount of time when signals are not being processed.
1302 Signal handling can restore the default colors, so callers must
1303 immediately change colors after invoking this function. */
1306 process_signals (void)
1308 while (interrupt_signal
|| stop_signal_count
)
1315 restore_default_color ();
1318 sigprocmask (SIG_BLOCK
, &caught_signals
, &oldset
);
1320 /* Reload interrupt_signal and stop_signal_count, in case a new
1321 signal was handled before sigprocmask took effect. */
1322 sig
= interrupt_signal
;
1323 stops
= stop_signal_count
;
1325 /* SIGTSTP is special, since the application can receive that signal
1326 more than once. In this case, don't set the signal handler to the
1327 default. Instead, just raise the uncatchable SIGSTOP. */
1330 stop_signal_count
= stops
- 1;
1334 signal (sig
, SIG_DFL
);
1336 /* Exit or suspend the program. */
1338 sigprocmask (SIG_SETMASK
, &oldset
, NULL
);
1340 /* If execution reaches here, then the program has been
1341 continued (after being suspended). */
1345 /* Setup signal handlers if INIT is true,
1346 otherwise restore to the default. */
1349 signal_setup (bool init
)
1351 /* The signals that are trapped, and the number of such signals. */
1352 static int const sig
[] =
1354 /* This one is handled specially. */
1357 /* The usual suspects. */
1358 SIGALRM
, SIGHUP
, SIGINT
, SIGPIPE
, SIGQUIT
, SIGTERM
,
1375 enum { nsigs
= ARRAY_CARDINALITY (sig
) };
1378 static bool caught_sig
[nsigs
];
1386 struct sigaction act
;
1388 sigemptyset (&caught_signals
);
1389 for (j
= 0; j
< nsigs
; j
++)
1391 sigaction (sig
[j
], NULL
, &act
);
1392 if (act
.sa_handler
!= SIG_IGN
)
1393 sigaddset (&caught_signals
, sig
[j
]);
1396 act
.sa_mask
= caught_signals
;
1397 act
.sa_flags
= SA_RESTART
;
1399 for (j
= 0; j
< nsigs
; j
++)
1400 if (sigismember (&caught_signals
, sig
[j
]))
1402 act
.sa_handler
= sig
[j
] == SIGTSTP
? stophandler
: sighandler
;
1403 sigaction (sig
[j
], &act
, NULL
);
1406 for (j
= 0; j
< nsigs
; j
++)
1408 caught_sig
[j
] = (signal (sig
[j
], SIG_IGN
) != SIG_IGN
);
1411 signal (sig
[j
], sig
[j
] == SIGTSTP
? stophandler
: sighandler
);
1412 siginterrupt (sig
[j
], 0);
1420 for (j
= 0; j
< nsigs
; j
++)
1421 if (sigismember (&caught_signals
, sig
[j
]))
1422 signal (sig
[j
], SIG_DFL
);
1424 for (j
= 0; j
< nsigs
; j
++)
1426 signal (sig
[j
], SIG_DFL
);
1434 signal_setup (true);
1438 signal_restore (void)
1440 signal_setup (false);
1444 main (int argc
, char **argv
)
1447 struct pending
*thispend
;
1450 initialize_main (&argc
, &argv
);
1451 set_program_name (argv
[0]);
1452 setlocale (LC_ALL
, "");
1453 bindtextdomain (PACKAGE
, LOCALEDIR
);
1454 textdomain (PACKAGE
);
1456 initialize_exit_failure (LS_FAILURE
);
1457 atexit (close_stdout
);
1459 assert (ARRAY_CARDINALITY (color_indicator
) + 1
1460 == ARRAY_CARDINALITY (indicator_name
));
1462 exit_status
= EXIT_SUCCESS
;
1463 print_dir_name
= true;
1464 pending_dirs
= NULL
;
1466 current_time
.tv_sec
= TYPE_MINIMUM (time_t);
1467 current_time
.tv_nsec
= -1;
1469 i
= decode_switches (argc
, argv
);
1471 if (print_with_color
)
1474 /* Test print_with_color again, because the call to parse_ls_color
1475 may have just reset it -- e.g., if LS_COLORS is invalid. */
1476 if (print_with_color
)
1478 /* Avoid following symbolic links when possible. */
1479 if (is_colored (C_ORPHAN
)
1480 || (is_colored (C_EXEC
) && color_symlink_as_referent
)
1481 || (is_colored (C_MISSING
) && format
== long_format
))
1482 check_symlink_color
= true;
1485 if (dereference
== DEREF_UNDEFINED
)
1486 dereference
= ((immediate_dirs
1487 || indicator_style
== classify
1488 || format
== long_format
)
1490 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR
);
1492 /* When using -R, initialize a data structure we'll use to
1493 detect any directory cycles. */
1496 active_dir_set
= hash_initialize (INITIAL_TABLE_SIZE
, NULL
,
1500 if (active_dir_set
== NULL
)
1503 obstack_init (&dev_ino_obstack
);
1506 localtz
= tzalloc (getenv ("TZ"));
1508 format_needs_stat
= sort_type
== sort_time
|| sort_type
== sort_size
1509 || format
== long_format
1511 || print_block_size
;
1512 format_needs_type
= (! format_needs_stat
1515 || indicator_style
!= none
1516 || directories_first
));
1520 obstack_init (&dired_obstack
);
1521 obstack_init (&subdired_obstack
);
1524 if (print_hyperlink
)
1526 file_escape_init ();
1528 hostname
= xgethostname ();
1529 /* The hostname is generally ignored,
1530 so ignore failures obtaining it. */
1536 cwd_file
= xnmalloc (cwd_n_alloc
, sizeof *cwd_file
);
1546 gobble_file (".", directory
, NOT_AN_INODE_NUMBER
, true, "");
1548 queue_directory (".", NULL
, true);
1552 gobble_file (argv
[i
++], unknown
, NOT_AN_INODE_NUMBER
, true, "");
1558 if (!immediate_dirs
)
1559 extract_dirs_from_files (NULL
, true);
1560 /* 'cwd_n_used' might be zero now. */
1563 /* In the following if/else blocks, it is sufficient to test 'pending_dirs'
1564 (and not pending_dirs->name) because there may be no markers in the queue
1565 at this point. A marker may be enqueued when extract_dirs_from_files is
1566 called with a non-empty string or via print_dir. */
1569 print_current_files ();
1571 DIRED_PUTCHAR ('\n');
1573 else if (n_files
<= 1 && pending_dirs
&& pending_dirs
->next
== 0)
1574 print_dir_name
= false;
1576 while (pending_dirs
)
1578 thispend
= pending_dirs
;
1579 pending_dirs
= pending_dirs
->next
;
1583 if (thispend
->name
== NULL
)
1585 /* thispend->name == NULL means this is a marker entry
1586 indicating we've finished processing the directory.
1587 Use its dev/ino numbers to remove the corresponding
1588 entry from the active_dir_set hash table. */
1589 struct dev_ino di
= dev_ino_pop ();
1590 struct dev_ino
*found
= hash_delete (active_dir_set
, &di
);
1591 /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */
1593 dev_ino_free (found
);
1594 free_pending_ent (thispend
);
1599 print_dir (thispend
->name
, thispend
->realname
,
1600 thispend
->command_line_arg
);
1602 free_pending_ent (thispend
);
1603 print_dir_name
= true;
1606 if (print_with_color
&& used_color
)
1610 /* Skip the restore when it would be a no-op, i.e.,
1611 when left is "\033[" and right is "m". */
1612 if (!(color_indicator
[C_LEFT
].len
== 2
1613 && memcmp (color_indicator
[C_LEFT
].string
, "\033[", 2) == 0
1614 && color_indicator
[C_RIGHT
].len
== 1
1615 && color_indicator
[C_RIGHT
].string
[0] == 'm'))
1616 restore_default_color ();
1622 /* Act on any signals that arrived before the default was restored.
1623 This can process signals out of order, but there doesn't seem to
1624 be an easy way to do them in order, and the order isn't that
1625 important anyway. */
1626 for (j
= stop_signal_count
; j
; j
--)
1628 j
= interrupt_signal
;
1635 /* No need to free these since we're about to exit. */
1636 dired_dump_obstack ("//DIRED//", &dired_obstack
);
1637 dired_dump_obstack ("//SUBDIRED//", &subdired_obstack
);
1638 printf ("//DIRED-OPTIONS// --quoting-style=%s\n",
1639 quoting_style_args
[get_quoting_style (filename_quoting_options
)]);
1644 assert (hash_get_n_entries (active_dir_set
) == 0);
1645 hash_free (active_dir_set
);
1651 /* Set the line length to the value given by SPEC. Return true if
1652 successful. 0 means no limit on line length. */
1655 set_line_length (char const *spec
)
1659 /* Treat too-large values as if they were SIZE_MAX, which is
1660 effectively infinity. */
1661 switch (xstrtoumax (spec
, NULL
, 0, &val
, ""))
1664 line_length
= MIN (val
, SIZE_MAX
);
1667 case LONGINT_OVERFLOW
:
1668 line_length
= SIZE_MAX
;
1676 /* Set all the option flags according to the switches specified.
1677 Return the index of the first non-option argument. */
1680 decode_switches (int argc
, char **argv
)
1682 char *time_style_option
= NULL
;
1684 bool sort_type_specified
= false;
1685 bool kibibytes_specified
= false;
1687 qmark_funny_chars
= false;
1689 /* initialize all switches to default settings */
1694 /* This is for the 'dir' program. */
1695 format
= many_per_line
;
1696 set_quoting_style (NULL
, escape_quoting_style
);
1699 case LS_LONG_FORMAT
:
1700 /* This is for the 'vdir' program. */
1701 format
= long_format
;
1702 set_quoting_style (NULL
, escape_quoting_style
);
1706 /* This is for the 'ls' program. */
1707 if (isatty (STDOUT_FILENO
))
1709 format
= many_per_line
;
1710 set_quoting_style (NULL
, shell_escape_quoting_style
);
1711 /* See description of qmark_funny_chars, above. */
1712 qmark_funny_chars
= true;
1716 format
= one_per_line
;
1717 qmark_funny_chars
= false;
1725 time_type
= time_mtime
;
1726 sort_type
= sort_name
;
1727 sort_reverse
= false;
1728 numeric_ids
= false;
1729 print_block_size
= false;
1730 indicator_style
= none
;
1731 print_inode
= false;
1732 dereference
= DEREF_UNDEFINED
;
1734 immediate_dirs
= false;
1735 ignore_mode
= IGNORE_DEFAULT
;
1736 ignore_patterns
= NULL
;
1737 hide_patterns
= NULL
;
1738 print_scontext
= false;
1740 getenv_quoting_style ();
1744 char const *p
= getenv ("COLUMNS");
1745 if (p
&& *p
&& ! set_line_length (p
))
1747 _("ignoring invalid width in environment variable COLUMNS: %s"),
1755 if (ioctl (STDOUT_FILENO
, TIOCGWINSZ
, &ws
) != -1
1756 && 0 < ws
.ws_col
&& ws
.ws_col
== (size_t) ws
.ws_col
)
1757 line_length
= ws
.ws_col
;
1762 char const *p
= getenv ("TABSIZE");
1766 unsigned long int tmp_ulong
;
1767 if (xstrtoul (p
, NULL
, 0, &tmp_ulong
, NULL
) == LONGINT_OK
1768 && tmp_ulong
<= SIZE_MAX
)
1770 tabsize
= tmp_ulong
;
1775 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1784 int c
= getopt_long (argc
, argv
,
1785 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1793 ignore_mode
= IGNORE_MINIMAL
;
1797 set_quoting_style (NULL
, escape_quoting_style
);
1801 time_type
= time_ctime
;
1805 immediate_dirs
= true;
1809 /* Same as enabling -a -U and disabling -l -s. */
1810 ignore_mode
= IGNORE_MINIMAL
;
1811 sort_type
= sort_none
;
1812 sort_type_specified
= true;
1814 if (format
== long_format
)
1815 format
= (isatty (STDOUT_FILENO
) ? many_per_line
: one_per_line
);
1816 print_block_size
= false; /* disable -s */
1817 print_with_color
= false; /* disable --color */
1818 print_hyperlink
= false; /* disable --hyperlink */
1821 case FILE_TYPE_INDICATOR_OPTION
: /* --file-type */
1822 indicator_style
= file_type
;
1826 format
= long_format
;
1827 print_owner
= false;
1831 file_human_output_opts
= human_output_opts
=
1832 human_autoscale
| human_SI
| human_base_1024
;
1833 file_output_block_size
= output_block_size
= 1;
1841 kibibytes_specified
= true;
1845 format
= long_format
;
1849 format
= with_commas
;
1854 format
= long_format
;
1857 case 'o': /* Just like -l, but don't display group info. */
1858 format
= long_format
;
1859 print_group
= false;
1863 indicator_style
= slash
;
1867 qmark_funny_chars
= true;
1871 sort_reverse
= true;
1875 print_block_size
= true;
1879 sort_type
= sort_time
;
1880 sort_type_specified
= true;
1884 time_type
= time_atime
;
1888 sort_type
= sort_version
;
1889 sort_type_specified
= true;
1893 if (! set_line_length (optarg
))
1894 die (LS_FAILURE
, 0, "%s: %s", _("invalid line width"),
1899 format
= horizontal
;
1903 if (ignore_mode
== IGNORE_DEFAULT
)
1904 ignore_mode
= IGNORE_DOT_AND_DOTDOT
;
1908 add_ignore_pattern ("*~");
1909 add_ignore_pattern (".*~");
1913 format
= many_per_line
;
1921 indicator_style
= classify
;
1924 case 'G': /* inhibit display of group info */
1925 print_group
= false;
1929 dereference
= DEREF_COMMAND_LINE_ARGUMENTS
;
1932 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION
:
1933 dereference
= DEREF_COMMAND_LINE_SYMLINK_TO_DIR
;
1937 add_ignore_pattern (optarg
);
1941 dereference
= DEREF_ALWAYS
;
1945 set_quoting_style (NULL
, literal_quoting_style
);
1949 set_quoting_style (NULL
, c_quoting_style
);
1957 sort_type
= sort_size
;
1958 sort_type_specified
= true;
1962 tabsize
= xnumtoumax (optarg
, 0, 0, SIZE_MAX
, "",
1963 _("invalid tab size"), LS_FAILURE
);
1967 sort_type
= sort_none
;
1968 sort_type_specified
= true;
1972 sort_type
= sort_extension
;
1973 sort_type_specified
= true;
1977 /* -1 has no effect after -l. */
1978 if (format
!= long_format
)
1979 format
= one_per_line
;
1983 print_author
= true;
1988 struct ignore_pattern
*hide
= xmalloc (sizeof *hide
);
1989 hide
->pattern
= optarg
;
1990 hide
->next
= hide_patterns
;
1991 hide_patterns
= hide
;
1996 sort_type
= XARGMATCH ("--sort", optarg
, sort_args
, sort_types
);
1997 sort_type_specified
= true;
2000 case GROUP_DIRECTORIES_FIRST_OPTION
:
2001 directories_first
= true;
2005 time_type
= XARGMATCH ("--time", optarg
, time_args
, time_types
);
2009 format
= XARGMATCH ("--format", optarg
, format_args
, format_types
);
2012 case FULL_TIME_OPTION
:
2013 format
= long_format
;
2014 time_style_option
= bad_cast ("full-iso");
2021 i
= XARGMATCH ("--color", optarg
, when_args
, when_types
);
2023 /* Using --color with no argument is equivalent to using
2027 print_with_color
= (i
== when_always
2028 || (i
== when_if_tty
2029 && isatty (STDOUT_FILENO
)));
2031 if (print_with_color
)
2033 /* Don't use TAB characters in output. Some terminal
2034 emulators can't handle the combination of tabs and
2035 color codes on the same line. */
2041 case HYPERLINK_OPTION
:
2045 i
= XARGMATCH ("--hyperlink", optarg
, when_args
, when_types
);
2047 /* Using --hyperlink with no argument is equivalent to using
2048 --hyperlink=always. */
2051 print_hyperlink
= (i
== when_always
2052 || (i
== when_if_tty
2053 && isatty (STDOUT_FILENO
)));
2057 case INDICATOR_STYLE_OPTION
:
2058 indicator_style
= XARGMATCH ("--indicator-style", optarg
,
2059 indicator_style_args
,
2060 indicator_style_types
);
2063 case QUOTING_STYLE_OPTION
:
2064 set_quoting_style (NULL
,
2065 XARGMATCH ("--quoting-style", optarg
,
2067 quoting_style_vals
));
2070 case TIME_STYLE_OPTION
:
2071 time_style_option
= optarg
;
2074 case SHOW_CONTROL_CHARS_OPTION
:
2075 qmark_funny_chars
= false;
2078 case BLOCK_SIZE_OPTION
:
2080 enum strtol_error e
= human_options (optarg
, &human_output_opts
,
2081 &output_block_size
);
2082 if (e
!= LONGINT_OK
)
2083 xstrtol_fatal (e
, oi
, 0, long_options
, optarg
);
2084 file_human_output_opts
= human_output_opts
;
2085 file_output_block_size
= output_block_size
;
2090 file_human_output_opts
= human_output_opts
=
2091 human_autoscale
| human_SI
;
2092 file_output_block_size
= output_block_size
= 1;
2096 print_scontext
= true;
2099 case_GETOPT_HELP_CHAR
;
2101 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
2108 if (! output_block_size
)
2110 char const *ls_block_size
= getenv ("LS_BLOCK_SIZE");
2111 human_options (ls_block_size
,
2112 &human_output_opts
, &output_block_size
);
2113 if (ls_block_size
|| getenv ("BLOCK_SIZE"))
2115 file_human_output_opts
= human_output_opts
;
2116 file_output_block_size
= output_block_size
;
2118 if (kibibytes_specified
)
2120 human_output_opts
= 0;
2121 output_block_size
= 1024;
2125 /* Determine the max possible number of display columns. */
2126 max_idx
= line_length
/ MIN_COLUMN_WIDTH
;
2127 /* Account for first display column not having a separator,
2128 or line_lengths shorter than MIN_COLUMN_WIDTH. */
2129 max_idx
+= line_length
% MIN_COLUMN_WIDTH
!= 0;
2131 enum quoting_style qs
= get_quoting_style (NULL
);
2132 align_variable_outer_quotes
= format
!= with_commas
2133 && format
!= one_per_line
2134 && (line_length
|| format
== long_format
)
2135 && (qs
== shell_quoting_style
2136 || qs
== shell_escape_quoting_style
2137 || qs
== c_maybe_quoting_style
);
2138 filename_quoting_options
= clone_quoting_options (NULL
);
2139 if (qs
== escape_quoting_style
)
2140 set_char_quoting (filename_quoting_options
, ' ', 1);
2141 if (file_type
<= indicator_style
)
2144 for (p
= &"*=>@|"[indicator_style
- file_type
]; *p
; p
++)
2145 set_char_quoting (filename_quoting_options
, *p
, 1);
2148 dirname_quoting_options
= clone_quoting_options (NULL
);
2149 set_char_quoting (dirname_quoting_options
, ':', 1);
2151 /* --dired is meaningful only with --format=long (-l).
2152 Otherwise, ignore it. FIXME: warn about this?
2153 Alternatively, make --dired imply --format=long? */
2154 if (dired
&& (format
!= long_format
|| print_hyperlink
))
2157 /* If -c or -u is specified and not -l (or any other option that implies -l),
2158 and no sort-type was specified, then sort by the ctime (-c) or atime (-u).
2159 The behavior of ls when using either -c or -u but with neither -l nor -t
2160 appears to be unspecified by POSIX. So, with GNU ls, '-u' alone means
2161 sort by atime (this is the one that's not specified by the POSIX spec),
2162 -lu means show atime and sort by name, -lut means show atime and sort
2165 if ((time_type
== time_ctime
|| time_type
== time_atime
)
2166 && !sort_type_specified
&& format
!= long_format
)
2168 sort_type
= sort_time
;
2171 if (format
== long_format
)
2173 char *style
= time_style_option
;
2174 static char const posix_prefix
[] = "posix-";
2177 if (! (style
= getenv ("TIME_STYLE")))
2178 style
= bad_cast ("locale");
2180 while (STREQ_LEN (style
, posix_prefix
, sizeof posix_prefix
- 1))
2182 if (! hard_locale (LC_TIME
))
2184 style
+= sizeof posix_prefix
- 1;
2189 char *p0
= style
+ 1;
2190 char *p1
= strchr (p0
, '\n');
2195 if (strchr (p1
+ 1, '\n'))
2196 die (LS_FAILURE
, 0, _("invalid time style format %s"),
2200 long_time_format
[0] = p0
;
2201 long_time_format
[1] = p1
;
2205 ptrdiff_t res
= argmatch (style
, time_style_args
,
2206 (char const *) time_style_types
,
2207 sizeof (*time_style_types
));
2210 /* This whole block used to be a simple use of XARGMATCH.
2211 but that didn't print the "posix-"-prefixed variants or
2212 the "+"-prefixed format string option upon failure. */
2213 argmatch_invalid ("time style", style
, res
);
2215 /* The following is a manual expansion of argmatch_valid,
2216 but with the added "+ ..." description and the [posix-]
2217 prefixes prepended. Note that this simplification works
2218 only because all four existing time_style_types values
2220 fputs (_("Valid arguments are:\n"), stderr
);
2221 char const *const *p
= time_style_args
;
2223 fprintf (stderr
, " - [posix-]%s\n", *p
++);
2224 fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
2225 " format\n"), stderr
);
2230 case full_iso_time_style
:
2231 long_time_format
[0] = long_time_format
[1] =
2232 "%Y-%m-%d %H:%M:%S.%N %z";
2235 case long_iso_time_style
:
2236 long_time_format
[0] = long_time_format
[1] = "%Y-%m-%d %H:%M";
2239 case iso_time_style
:
2240 long_time_format
[0] = "%Y-%m-%d ";
2241 long_time_format
[1] = "%m-%d %H:%M";
2244 case locale_time_style
:
2245 if (hard_locale (LC_TIME
))
2247 for (int i
= 0; i
< 2; i
++)
2248 long_time_format
[i
] =
2249 dcgettext (NULL
, long_time_format
[i
], LC_TIME
);
2260 /* Parse a string as part of the LS_COLORS variable; this may involve
2261 decoding all kinds of escape characters. If equals_end is set an
2262 unescaped equal sign ends the string, otherwise only a : or \0
2263 does. Set *OUTPUT_COUNT to the number of bytes output. Return
2266 The resulting string is *not* null-terminated, but may contain
2269 Note that both dest and src are char **; on return they point to
2270 the first free byte after the array and the character that ended
2271 the input string, respectively. */
2274 get_funky_string (char **dest
, const char **src
, bool equals_end
,
2275 size_t *output_count
)
2277 char num
; /* For numerical codes */
2278 size_t count
; /* Something to count with */
2280 ST_GND
, ST_BACKSLASH
, ST_OCTAL
, ST_HEX
, ST_CARET
, ST_END
, ST_ERROR
2285 p
= *src
; /* We don't want to double-indirect */
2286 q
= *dest
; /* the whole darn time. */
2288 count
= 0; /* No characters counted in yet. */
2291 state
= ST_GND
; /* Start in ground state. */
2292 while (state
< ST_END
)
2296 case ST_GND
: /* Ground state (no escapes) */
2301 state
= ST_END
; /* End of string */
2304 state
= ST_BACKSLASH
; /* Backslash escape sequence */
2308 state
= ST_CARET
; /* Caret escape */
2314 state
= ST_END
; /* End */
2325 case ST_BACKSLASH
: /* Backslash escaped character */
2336 state
= ST_OCTAL
; /* Octal sequence */
2341 state
= ST_HEX
; /* Hex sequence */
2344 case 'a': /* Bell */
2347 case 'b': /* Backspace */
2350 case 'e': /* Escape */
2353 case 'f': /* Form feed */
2356 case 'n': /* Newline */
2359 case 'r': /* Carriage return */
2365 case 'v': /* Vtab */
2368 case '?': /* Delete */
2371 case '_': /* Space */
2374 case '\0': /* End of string */
2375 state
= ST_ERROR
; /* Error! */
2377 default: /* Escaped character like \ ^ : = */
2381 if (state
== ST_BACKSLASH
)
2390 case ST_OCTAL
: /* Octal sequence */
2391 if (*p
< '0' || *p
> '7')
2398 num
= (num
<< 3) + (*(p
++) - '0');
2401 case ST_HEX
: /* Hex sequence */
2414 num
= (num
<< 4) + (*(p
++) - '0');
2422 num
= (num
<< 4) + (*(p
++) - 'a') + 10;
2430 num
= (num
<< 4) + (*(p
++) - 'A') + 10;
2440 case ST_CARET
: /* Caret escape */
2441 state
= ST_GND
; /* Should be the next state... */
2442 if (*p
>= '@' && *p
<= '~')
2444 *(q
++) = *(p
++) & 037;
2463 *output_count
= count
;
2465 return state
!= ST_ERROR
;
2479 /* Check if the content of TERM is a valid name in dircolors. */
2482 known_term_type (void)
2484 char const *term
= getenv ("TERM");
2485 if (! term
|| ! *term
)
2488 char const *line
= G_line
;
2489 while (line
- G_line
< sizeof (G_line
))
2491 if (STRNCMP_LIT (line
, "TERM ") == 0)
2493 if (fnmatch (line
+ 5, term
, 0) == 0)
2496 line
+= strlen (line
) + 1;
2503 parse_ls_color (void)
2505 const char *p
; /* Pointer to character being parsed */
2506 char *buf
; /* color_buf buffer pointer */
2507 int ind_no
; /* Indicator number */
2508 char label
[3]; /* Indicator label */
2509 struct color_ext_type
*ext
; /* Extension we are working on */
2511 if ((p
= getenv ("LS_COLORS")) == NULL
|| *p
== '\0')
2513 /* LS_COLORS takes precedence, but if that's not set then
2514 honor the COLORTERM and TERM env variables so that
2515 we only go with the internal ANSI color codes if the
2516 former is non empty or the latter is set to a known value. */
2517 char const *colorterm
= getenv ("COLORTERM");
2518 if (! (colorterm
&& *colorterm
) && ! known_term_type ())
2519 print_with_color
= false;
2524 strcpy (label
, "??");
2526 /* This is an overly conservative estimate, but any possible
2527 LS_COLORS string will *not* generate a color_buf longer than
2528 itself, so it is a safe way of allocating a buffer in
2530 buf
= color_buf
= xstrdup (p
);
2532 enum parse_state state
= PS_START
;
2537 case PS_START
: /* First label character */
2545 /* Allocate new extension block and add to head of
2546 linked list (this way a later definition will
2547 override an earlier one, which can be useful for
2548 having terminal-specific defs override global). */
2550 ext
= xmalloc (sizeof *ext
);
2551 ext
->next
= color_ext_list
;
2552 color_ext_list
= ext
;
2555 ext
->ext
.string
= buf
;
2557 state
= (get_funky_string (&buf
, &p
, true, &ext
->ext
.len
)
2562 state
= PS_DONE
; /* Done! */
2565 default: /* Assume it is file type label */
2572 case PS_2
: /* Second label character */
2579 state
= PS_FAIL
; /* Error */
2582 case PS_3
: /* Equal sign after indicator label */
2583 state
= PS_FAIL
; /* Assume failure... */
2584 if (*(p
++) == '=')/* It *should* be... */
2586 for (ind_no
= 0; indicator_name
[ind_no
] != NULL
; ++ind_no
)
2588 if (STREQ (label
, indicator_name
[ind_no
]))
2590 color_indicator
[ind_no
].string
= buf
;
2591 state
= (get_funky_string (&buf
, &p
, false,
2592 &color_indicator
[ind_no
].len
)
2593 ? PS_START
: PS_FAIL
);
2597 if (state
== PS_FAIL
)
2598 error (0, 0, _("unrecognized prefix: %s"), quote (label
));
2602 case PS_4
: /* Equal sign after *.ext */
2605 ext
->seq
.string
= buf
;
2606 state
= (get_funky_string (&buf
, &p
, false, &ext
->seq
.len
)
2607 ? PS_START
: PS_FAIL
);
2622 if (state
== PS_FAIL
)
2624 struct color_ext_type
*e
;
2625 struct color_ext_type
*e2
;
2628 _("unparsable value for LS_COLORS environment variable"));
2630 for (e
= color_ext_list
; e
!= NULL
; /* empty */)
2636 print_with_color
= false;
2639 if (color_indicator
[C_LINK
].len
== 6
2640 && !STRNCMP_LIT (color_indicator
[C_LINK
].string
, "target"))
2641 color_symlink_as_referent
= true;
2644 /* Set the quoting style default if the environment variable
2645 QUOTING_STYLE is set. */
2648 getenv_quoting_style (void)
2650 char const *q_style
= getenv ("QUOTING_STYLE");
2653 int i
= ARGMATCH (q_style
, quoting_style_args
, quoting_style_vals
);
2655 set_quoting_style (NULL
, quoting_style_vals
[i
]);
2658 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
2663 /* Set the exit status to report a failure. If SERIOUS, it is a
2664 serious failure; otherwise, it is merely a minor problem. */
2667 set_exit_status (bool serious
)
2670 exit_status
= LS_FAILURE
;
2671 else if (exit_status
== EXIT_SUCCESS
)
2672 exit_status
= LS_MINOR_PROBLEM
;
2675 /* Assuming a failure is serious if SERIOUS, use the printf-style
2676 MESSAGE to report the failure to access a file named FILE. Assume
2677 errno is set appropriately for the failure. */
2680 file_failure (bool serious
, char const *message
, char const *file
)
2682 error (0, errno
, message
, quoteaf (file
));
2683 set_exit_status (serious
);
2686 /* Request that the directory named NAME have its contents listed later.
2687 If REALNAME is nonzero, it will be used instead of NAME when the
2688 directory name is printed. This allows symbolic links to directories
2689 to be treated as regular directories but still be listed under their
2690 real names. NAME == NULL is used to insert a marker entry for the
2691 directory named in REALNAME.
2692 If NAME is non-NULL, we use its dev/ino information to save
2693 a call to stat -- when doing a recursive (-R) traversal.
2694 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2697 queue_directory (char const *name
, char const *realname
, bool command_line_arg
)
2699 struct pending
*new = xmalloc (sizeof *new);
2700 new->realname
= realname
? xstrdup (realname
) : NULL
;
2701 new->name
= name
? xstrdup (name
) : NULL
;
2702 new->command_line_arg
= command_line_arg
;
2703 new->next
= pending_dirs
;
2707 /* Read directory NAME, and list the files in it.
2708 If REALNAME is nonzero, print its name instead of NAME;
2709 this is used for symbolic links to directories.
2710 COMMAND_LINE_ARG means this directory was mentioned on the command line. */
2713 print_dir (char const *name
, char const *realname
, bool command_line_arg
)
2716 struct dirent
*next
;
2717 uintmax_t total_blocks
= 0;
2718 static bool first
= true;
2721 dirp
= opendir (name
);
2724 file_failure (command_line_arg
, _("cannot open directory %s"), name
);
2730 struct stat dir_stat
;
2731 int fd
= dirfd (dirp
);
2733 /* If dirfd failed, endure the overhead of using stat. */
2735 ? fstat (fd
, &dir_stat
)
2736 : stat (name
, &dir_stat
)) < 0)
2738 file_failure (command_line_arg
,
2739 _("cannot determine device and inode of %s"), name
);
2744 /* If we've already visited this dev/inode pair, warn that
2745 we've found a loop, and do not process this directory. */
2746 if (visit_dir (dir_stat
.st_dev
, dir_stat
.st_ino
))
2748 error (0, 0, _("%s: not listing already-listed directory"),
2751 set_exit_status (true);
2755 dev_ino_push (dir_stat
.st_dev
, dir_stat
.st_ino
);
2760 if (recursive
|| print_dir_name
)
2763 DIRED_PUTCHAR ('\n');
2767 char *absolute_name
= NULL
;
2768 if (print_hyperlink
)
2770 absolute_name
= canonicalize_filename_mode (name
, CAN_MISSING
);
2771 if (! absolute_name
)
2772 file_failure (command_line_arg
,
2773 _("error canonicalizing %s"), name
);
2775 quote_name (realname
? realname
: name
, dirname_quoting_options
, -1,
2776 NULL
, true, &subdired_obstack
, absolute_name
);
2778 free (absolute_name
);
2780 DIRED_FPUTS_LITERAL (":\n", stdout
);
2783 /* Read the directory entries, and insert the subfiles into the 'cwd_file'
2788 /* Set errno to zero so we can distinguish between a readdir failure
2789 and when readdir simply finds that there are no more entries. */
2791 next
= readdir (dirp
);
2794 if (! file_ignored (next
->d_name
))
2796 enum filetype type
= unknown
;
2798 #if HAVE_STRUCT_DIRENT_D_TYPE
2799 switch (next
->d_type
)
2801 case DT_BLK
: type
= blockdev
; break;
2802 case DT_CHR
: type
= chardev
; break;
2803 case DT_DIR
: type
= directory
; break;
2804 case DT_FIFO
: type
= fifo
; break;
2805 case DT_LNK
: type
= symbolic_link
; break;
2806 case DT_REG
: type
= normal
; break;
2807 case DT_SOCK
: type
= sock
; break;
2809 case DT_WHT
: type
= whiteout
; break;
2813 total_blocks
+= gobble_file (next
->d_name
, type
,
2814 RELIABLE_D_INO (next
),
2817 /* In this narrow case, print out each name right away, so
2818 ls uses constant memory while processing the entries of
2819 this directory. Useful when there are many (millions)
2820 of entries in a directory. */
2821 if (format
== one_per_line
&& sort_type
== sort_none
2822 && !print_block_size
&& !recursive
)
2824 /* We must call sort_files in spite of
2825 "sort_type == sort_none" for its initialization
2826 of the sorted_file vector. */
2828 print_current_files ();
2833 else if (errno
!= 0)
2835 file_failure (command_line_arg
, _("reading directory %s"), name
);
2836 if (errno
!= EOVERFLOW
)
2842 /* When processing a very large directory, and since we've inhibited
2843 interrupts, this loop would take so long that ls would be annoyingly
2844 uninterruptible. This ensures that it handles signals promptly. */
2848 if (closedir (dirp
) != 0)
2850 file_failure (command_line_arg
, _("closing directory %s"), name
);
2851 /* Don't return; print whatever we got. */
2854 /* Sort the directory contents. */
2857 /* If any member files are subdirectories, perhaps they should have their
2858 contents listed rather than being mentioned here as files. */
2861 extract_dirs_from_files (name
, false);
2863 if (format
== long_format
|| print_block_size
)
2866 char buf
[LONGEST_HUMAN_READABLE
+ 1];
2870 DIRED_FPUTS (p
, stdout
, strlen (p
));
2871 DIRED_PUTCHAR (' ');
2872 p
= human_readable (total_blocks
, buf
, human_output_opts
,
2873 ST_NBLOCKSIZE
, output_block_size
);
2874 DIRED_FPUTS (p
, stdout
, strlen (p
));
2875 DIRED_PUTCHAR ('\n');
2879 print_current_files ();
2882 /* Add 'pattern' to the list of patterns for which files that match are
2886 add_ignore_pattern (const char *pattern
)
2888 struct ignore_pattern
*ignore
;
2890 ignore
= xmalloc (sizeof *ignore
);
2891 ignore
->pattern
= pattern
;
2892 /* Add it to the head of the linked list. */
2893 ignore
->next
= ignore_patterns
;
2894 ignore_patterns
= ignore
;
2897 /* Return true if one of the PATTERNS matches FILE. */
2900 patterns_match (struct ignore_pattern
const *patterns
, char const *file
)
2902 struct ignore_pattern
const *p
;
2903 for (p
= patterns
; p
; p
= p
->next
)
2904 if (fnmatch (p
->pattern
, file
, FNM_PERIOD
) == 0)
2909 /* Return true if FILE should be ignored. */
2912 file_ignored (char const *name
)
2914 return ((ignore_mode
!= IGNORE_MINIMAL
2916 && (ignore_mode
== IGNORE_DEFAULT
|| ! name
[1 + (name
[1] == '.')]))
2917 || (ignore_mode
== IGNORE_DEFAULT
2918 && patterns_match (hide_patterns
, name
))
2919 || patterns_match (ignore_patterns
, name
));
2922 /* POSIX requires that a file size be printed without a sign, even
2923 when negative. Assume the typical case where negative sizes are
2924 actually positive values that have wrapped around. */
2927 unsigned_file_size (off_t size
)
2929 return size
+ (size
< 0) * ((uintmax_t) OFF_T_MAX
- OFF_T_MIN
+ 1);
2933 /* Return true if NAME has a capability (see linux/capability.h) */
2935 has_capability (char const *name
)
2940 cap_t cap_d
= cap_get_file (name
);
2944 result
= cap_to_text (cap_d
, NULL
);
2949 /* check if human-readable capability string is empty */
2950 has_cap
= !!*result
;
2957 has_capability (char const *name _GL_UNUSED
)
2964 /* Enter and remove entries in the table 'cwd_file'. */
2967 free_ent (struct fileinfo
*f
)
2971 free (f
->absolute_name
);
2972 if (f
->scontext
!= UNKNOWN_SECURITY_CONTEXT
)
2974 if (is_smack_enabled ())
2977 freecon (f
->scontext
);
2981 /* Empty the table of files. */
2985 for (size_t i
= 0; i
< cwd_n_used
; i
++)
2987 struct fileinfo
*f
= sorted_file
[i
];
2992 cwd_some_quoted
= false;
2993 any_has_acl
= false;
2994 inode_number_width
= 0;
2995 block_size_width
= 0;
3001 major_device_number_width
= 0;
3002 minor_device_number_width
= 0;
3003 file_size_width
= 0;
3006 /* Return true if ERR implies lack-of-support failure by a
3007 getxattr-calling function like getfilecon or file_has_acl. */
3009 errno_unsupported (int err
)
3011 return (err
== EINVAL
|| err
== ENOSYS
|| is_ENOTSUP (err
));
3014 /* Cache *getfilecon failure, when it's trivial to do so.
3015 Like getfilecon/lgetfilecon, but when F's st_dev says it's doesn't
3016 support getting the security context, fail with ENOTSUP immediately. */
3018 getfilecon_cache (char const *file
, struct fileinfo
*f
, bool deref
)
3020 /* st_dev of the most recently processed device for which we've
3021 found that [l]getfilecon fails indicating lack of support. */
3022 static dev_t unsupported_device
;
3024 if (f
->stat
.st_dev
== unsupported_device
)
3031 if (is_smack_enabled ())
3032 r
= smack_new_label_from_path (file
, "security.SMACK64", deref
,
3037 ? getfilecon (file
, &f
->scontext
)
3038 : lgetfilecon (file
, &f
->scontext
));
3039 if (r
< 0 && errno_unsupported (errno
))
3040 unsupported_device
= f
->stat
.st_dev
;
3044 /* Cache file_has_acl failure, when it's trivial to do.
3045 Like file_has_acl, but when F's st_dev says it's on a file
3046 system lacking ACL support, return 0 with ENOTSUP immediately. */
3048 file_has_acl_cache (char const *file
, struct fileinfo
*f
)
3050 /* st_dev of the most recently processed device for which we've
3051 found that file_has_acl fails indicating lack of support. */
3052 static dev_t unsupported_device
;
3054 if (f
->stat
.st_dev
== unsupported_device
)
3060 /* Zero errno so that we can distinguish between two 0-returning cases:
3061 "has-ACL-support, but only a default ACL" and "no ACL support". */
3063 int n
= file_has_acl (file
, &f
->stat
);
3064 if (n
<= 0 && errno_unsupported (errno
))
3065 unsupported_device
= f
->stat
.st_dev
;
3069 /* Cache has_capability failure, when it's trivial to do.
3070 Like has_capability, but when F's st_dev says it's on a file
3071 system lacking capability support, return 0 with ENOTSUP immediately. */
3073 has_capability_cache (char const *file
, struct fileinfo
*f
)
3075 /* st_dev of the most recently processed device for which we've
3076 found that has_capability fails indicating lack of support. */
3077 static dev_t unsupported_device
;
3079 if (f
->stat
.st_dev
== unsupported_device
)
3085 bool b
= has_capability (file
);
3086 if ( !b
&& errno_unsupported (errno
))
3087 unsupported_device
= f
->stat
.st_dev
;
3092 needs_quoting (char const* name
)
3095 size_t len
= quotearg_buffer (test
, sizeof test
, name
, -1,
3096 filename_quoting_options
);
3097 return *name
!= *test
|| strlen (name
) != len
;
3100 /* Add a file to the current table of files.
3101 Verify that the file exists, and print an error message if it does not.
3102 Return the number of blocks that the file occupies. */
3104 gobble_file (char const *name
, enum filetype type
, ino_t inode
,
3105 bool command_line_arg
, char const *dirname
)
3107 uintmax_t blocks
= 0;
3110 /* An inode value prior to gobble_file necessarily came from readdir,
3111 which is not used for command line arguments. */
3112 assert (! command_line_arg
|| inode
== NOT_AN_INODE_NUMBER
);
3114 if (cwd_n_used
== cwd_n_alloc
)
3116 cwd_file
= xnrealloc (cwd_file
, cwd_n_alloc
, 2 * sizeof *cwd_file
);
3120 f
= &cwd_file
[cwd_n_used
];
3121 memset (f
, '\0', sizeof *f
);
3122 f
->stat
.st_ino
= inode
;
3126 if ((! cwd_some_quoted
) && align_variable_outer_quotes
)
3128 /* Determine if any quoted for padding purposes. */
3129 f
->quoted
= needs_quoting (name
);
3131 cwd_some_quoted
= 1;
3134 if (command_line_arg
3136 || format_needs_stat
3137 /* When coloring a directory (we may know the type from
3138 direct.d_type), we have to stat it in order to indicate
3139 sticky and/or other-writable attributes. */
3140 || (type
== directory
&& print_with_color
3141 && (is_colored (C_OTHER_WRITABLE
)
3142 || is_colored (C_STICKY
)
3143 || is_colored (C_STICKY_OTHER_WRITABLE
)))
3144 /* When dereferencing symlinks, the inode and type must come from
3145 stat, but readdir provides the inode and type of lstat. */
3146 || ((print_inode
|| format_needs_type
)
3147 && (type
== symbolic_link
|| type
== unknown
)
3148 && (dereference
== DEREF_ALWAYS
3149 || color_symlink_as_referent
|| check_symlink_color
))
3150 /* Command line dereferences are already taken care of by the above
3151 assertion that the inode number is not yet known. */
3152 || (print_inode
&& inode
== NOT_AN_INODE_NUMBER
)
3153 || (format_needs_type
3154 && (type
== unknown
|| command_line_arg
3155 /* --indicator-style=classify (aka -F)
3156 requires that we stat each regular file
3157 to see if it's executable. */
3158 || (type
== normal
&& (indicator_style
== classify
3159 /* This is so that --color ends up
3160 highlighting files with these mode
3161 bits set even when options like -F are
3162 not specified. Note we do a redundant
3163 stat in the very unlikely case where
3164 C_CAP is set but not the others. */
3165 || (print_with_color
3166 && (is_colored (C_EXEC
)
3167 || is_colored (C_SETUID
)
3168 || is_colored (C_SETGID
)
3169 || is_colored (C_CAP
)))
3173 /* Absolute name of this file. */
3178 if (name
[0] == '/' || dirname
[0] == 0)
3179 full_name
= (char *) name
;
3182 full_name
= alloca (strlen (name
) + strlen (dirname
) + 2);
3183 attach (full_name
, dirname
, name
);
3186 if (print_hyperlink
)
3188 f
->absolute_name
= canonicalize_filename_mode (full_name
,
3190 if (! f
->absolute_name
)
3191 file_failure (command_line_arg
,
3192 _("error canonicalizing %s"), full_name
);
3195 switch (dereference
)
3198 err
= stat (full_name
, &f
->stat
);
3202 case DEREF_COMMAND_LINE_ARGUMENTS
:
3203 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR
:
3204 if (command_line_arg
)
3207 err
= stat (full_name
, &f
->stat
);
3210 if (dereference
== DEREF_COMMAND_LINE_ARGUMENTS
)
3213 need_lstat
= (err
< 0
3215 : ! S_ISDIR (f
->stat
.st_mode
));
3219 /* stat failed because of ENOENT, maybe indicating a dangling
3220 symlink. Or stat succeeded, FULL_NAME does not refer to a
3221 directory, and --dereference-command-line-symlink-to-dir is
3222 in effect. Fall through so that we call lstat instead. */
3226 default: /* DEREF_NEVER */
3227 err
= lstat (full_name
, &f
->stat
);
3234 /* Failure to stat a command line argument leads to
3235 an exit status of 2. For other files, stat failure
3236 provokes an exit status of 1. */
3237 file_failure (command_line_arg
,
3238 _("cannot access %s"), full_name
);
3239 if (command_line_arg
)
3242 f
->name
= xstrdup (name
);
3250 /* Note has_capability() adds around 30% runtime to 'ls --color' */
3251 if ((type
== normal
|| S_ISREG (f
->stat
.st_mode
))
3252 && print_with_color
&& is_colored (C_CAP
))
3253 f
->has_capability
= has_capability_cache (full_name
, f
);
3255 if (format
== long_format
|| print_scontext
)
3257 bool have_scontext
= false;
3258 bool have_acl
= false;
3259 int attr_len
= getfilecon_cache (full_name
, f
, do_deref
);
3260 err
= (attr_len
< 0);
3264 if (is_smack_enabled ())
3265 have_scontext
= ! STREQ ("_", f
->scontext
);
3267 have_scontext
= ! STREQ ("unlabeled", f
->scontext
);
3271 f
->scontext
= UNKNOWN_SECURITY_CONTEXT
;
3273 /* When requesting security context information, don't make
3274 ls fail just because the file (even a command line argument)
3275 isn't on the right type of file system. I.e., a getfilecon
3276 failure isn't in the same class as a stat failure. */
3277 if (is_ENOTSUP (errno
) || errno
== ENODATA
)
3281 if (err
== 0 && format
== long_format
)
3283 int n
= file_has_acl_cache (full_name
, f
);
3288 f
->acl_type
= (!have_scontext
&& !have_acl
3290 : (have_scontext
&& !have_acl
3291 ? ACL_T_LSM_CONTEXT_ONLY
3293 any_has_acl
|= f
->acl_type
!= ACL_T_NONE
;
3296 error (0, errno
, "%s", quotef (full_name
));
3299 if (S_ISLNK (f
->stat
.st_mode
)
3300 && (format
== long_format
|| check_symlink_color
))
3302 struct stat linkstats
;
3304 get_link_name (full_name
, f
, command_line_arg
);
3305 char *linkname
= make_link_name (full_name
, f
->linkname
);
3307 /* Use the slower quoting path for this entry, though
3308 don't update CWD_SOME_QUOTED since alignment not affected. */
3309 if (linkname
&& f
->quoted
== 0 && needs_quoting (f
->linkname
))
3312 /* Avoid following symbolic links when possible, ie, when
3313 they won't be traced and when no indicator is needed. */
3315 && (file_type
<= indicator_style
|| check_symlink_color
)
3316 && stat (linkname
, &linkstats
) == 0)
3320 /* Symbolic links to directories that are mentioned on the
3321 command line are automatically traced if not being
3323 if (!command_line_arg
|| format
== long_format
3324 || !S_ISDIR (linkstats
.st_mode
))
3326 /* Get the linked-to file's mode for the filetype indicator
3327 in long listings. */
3328 f
->linkmode
= linkstats
.st_mode
;
3334 if (S_ISLNK (f
->stat
.st_mode
))
3335 f
->filetype
= symbolic_link
;
3336 else if (S_ISDIR (f
->stat
.st_mode
))
3338 if (command_line_arg
&& !immediate_dirs
)
3339 f
->filetype
= arg_directory
;
3341 f
->filetype
= directory
;
3344 f
->filetype
= normal
;
3346 blocks
= ST_NBLOCKS (f
->stat
);
3347 if (format
== long_format
|| print_block_size
)
3349 char buf
[LONGEST_HUMAN_READABLE
+ 1];
3350 int len
= mbswidth (human_readable (blocks
, buf
, human_output_opts
,
3351 ST_NBLOCKSIZE
, output_block_size
),
3353 if (block_size_width
< len
)
3354 block_size_width
= len
;
3357 if (format
== long_format
)
3361 int len
= format_user_width (f
->stat
.st_uid
);
3362 if (owner_width
< len
)
3368 int len
= format_group_width (f
->stat
.st_gid
);
3369 if (group_width
< len
)
3375 int len
= format_user_width (f
->stat
.st_author
);
3376 if (author_width
< len
)
3383 int len
= strlen (f
->scontext
);
3384 if (scontext_width
< len
)
3385 scontext_width
= len
;
3388 if (format
== long_format
)
3390 char b
[INT_BUFSIZE_BOUND (uintmax_t)];
3391 int b_len
= strlen (umaxtostr (f
->stat
.st_nlink
, b
));
3392 if (nlink_width
< b_len
)
3393 nlink_width
= b_len
;
3395 if (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
))
3397 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
3398 int len
= strlen (umaxtostr (major (f
->stat
.st_rdev
), buf
));
3399 if (major_device_number_width
< len
)
3400 major_device_number_width
= len
;
3401 len
= strlen (umaxtostr (minor (f
->stat
.st_rdev
), buf
));
3402 if (minor_device_number_width
< len
)
3403 minor_device_number_width
= len
;
3404 len
= major_device_number_width
+ 2 + minor_device_number_width
;
3405 if (file_size_width
< len
)
3406 file_size_width
= len
;
3410 char buf
[LONGEST_HUMAN_READABLE
+ 1];
3411 uintmax_t size
= unsigned_file_size (f
->stat
.st_size
);
3412 int len
= mbswidth (human_readable (size
, buf
,
3413 file_human_output_opts
,
3414 1, file_output_block_size
),
3416 if (file_size_width
< len
)
3417 file_size_width
= len
;
3424 char buf
[INT_BUFSIZE_BOUND (uintmax_t)];
3425 int len
= strlen (umaxtostr (f
->stat
.st_ino
, buf
));
3426 if (inode_number_width
< len
)
3427 inode_number_width
= len
;
3430 f
->name
= xstrdup (name
);
3436 /* Return true if F refers to a directory. */
3438 is_directory (const struct fileinfo
*f
)
3440 return f
->filetype
== directory
|| f
->filetype
== arg_directory
;
3443 /* Put the name of the file that FILENAME is a symbolic link to
3444 into the LINKNAME field of 'f'. COMMAND_LINE_ARG indicates whether
3445 FILENAME is a command-line argument. */
3448 get_link_name (char const *filename
, struct fileinfo
*f
, bool command_line_arg
)
3450 f
->linkname
= areadlink_with_size (filename
, f
->stat
.st_size
);
3451 if (f
->linkname
== NULL
)
3452 file_failure (command_line_arg
, _("cannot read symbolic link %s"),
3456 /* If LINKNAME is a relative name and NAME contains one or more
3457 leading directories, return LINKNAME with those directories
3458 prepended; otherwise, return a copy of LINKNAME.
3459 If LINKNAME is NULL, return NULL. */
3462 make_link_name (char const *name
, char const *linkname
)
3467 if (IS_ABSOLUTE_FILE_NAME (linkname
))
3468 return xstrdup (linkname
);
3470 /* The link is to a relative name. Prepend any leading directory
3471 in 'name' to the link name. */
3472 size_t prefix_len
= dir_len (name
);
3473 if (prefix_len
== 0)
3474 return xstrdup (linkname
);
3476 char *p
= xmalloc (prefix_len
+ 1 + strlen (linkname
) + 1);
3478 /* PREFIX_LEN usually specifies a string not ending in slash.
3479 In that case, extend it by one, since the next byte *is* a slash.
3480 Otherwise, the prefix is "/", so leave the length unchanged. */
3481 if ( ! ISSLASH (name
[prefix_len
- 1]))
3484 stpcpy (stpncpy (p
, name
, prefix_len
), linkname
);
3488 /* Return true if the last component of NAME is '.' or '..'
3489 This is so we don't try to recurse on '././././. ...' */
3492 basename_is_dot_or_dotdot (const char *name
)
3494 char const *base
= last_component (name
);
3495 return dot_or_dotdot (base
);
3498 /* Remove any entries from CWD_FILE that are for directories,
3499 and queue them to be listed as directories instead.
3500 DIRNAME is the prefix to prepend to each dirname
3501 to make it correct relative to ls's working dir;
3502 if it is null, no prefix is needed and "." and ".." should not be ignored.
3503 If COMMAND_LINE_ARG is true, this directory was mentioned at the top level,
3504 This is desirable when processing directories recursively. */
3507 extract_dirs_from_files (char const *dirname
, bool command_line_arg
)
3511 bool ignore_dot_and_dot_dot
= (dirname
!= NULL
);
3513 if (dirname
&& LOOP_DETECT
)
3515 /* Insert a marker entry first. When we dequeue this marker entry,
3516 we'll know that DIRNAME has been processed and may be removed
3517 from the set of active directories. */
3518 queue_directory (NULL
, dirname
, false);
3521 /* Queue the directories last one first, because queueing reverses the
3523 for (i
= cwd_n_used
; i
-- != 0; )
3525 struct fileinfo
*f
= sorted_file
[i
];
3527 if (is_directory (f
)
3528 && (! ignore_dot_and_dot_dot
3529 || ! basename_is_dot_or_dotdot (f
->name
)))
3531 if (!dirname
|| f
->name
[0] == '/')
3532 queue_directory (f
->name
, f
->linkname
, command_line_arg
);
3535 char *name
= file_name_concat (dirname
, f
->name
, NULL
);
3536 queue_directory (name
, f
->linkname
, command_line_arg
);
3539 if (f
->filetype
== arg_directory
)
3544 /* Now delete the directories from the table, compacting all the remaining
3547 for (i
= 0, j
= 0; i
< cwd_n_used
; i
++)
3549 struct fileinfo
*f
= sorted_file
[i
];
3551 j
+= (f
->filetype
!= arg_directory
);
3556 /* Use strcoll to compare strings in this locale. If an error occurs,
3557 report an error and longjmp to failed_strcoll. */
3559 static jmp_buf failed_strcoll
;
3562 xstrcoll (char const *a
, char const *b
)
3566 diff
= strcoll (a
, b
);
3569 error (0, errno
, _("cannot compare file names %s and %s"),
3570 quote_n (0, a
), quote_n (1, b
));
3571 set_exit_status (false);
3572 longjmp (failed_strcoll
, 1);
3577 /* Comparison routines for sorting the files. */
3579 typedef void const *V
;
3580 typedef int (*qsortFunc
)(V a
, V b
);
3582 /* Used below in DEFINE_SORT_FUNCTIONS for _df_ sort function variants.
3583 The do { ... } while(0) makes it possible to use the macro more like
3584 a statement, without violating C89 rules: */
3585 #define DIRFIRST_CHECK(a, b) \
3588 bool a_is_dir = is_directory ((struct fileinfo const *) a); \
3589 bool b_is_dir = is_directory ((struct fileinfo const *) b); \
3590 if (a_is_dir && !b_is_dir) \
3591 return -1; /* a goes before b */ \
3592 if (!a_is_dir && b_is_dir) \
3593 return 1; /* b goes before a */ \
3597 /* Define the 8 different sort function variants required for each sortkey.
3598 KEY_NAME is a token describing the sort key, e.g., ctime, atime, size.
3599 KEY_CMP_FUNC is a function to compare records based on that key, e.g.,
3600 ctime_cmp, atime_cmp, size_cmp. Append KEY_NAME to the string,
3601 '[rev_][x]str{cmp|coll}[_df]_', to create each function name. */
3602 #define DEFINE_SORT_FUNCTIONS(key_name, key_cmp_func) \
3603 /* direct, non-dirfirst versions */ \
3604 static int xstrcoll_##key_name (V a, V b) \
3605 { return key_cmp_func (a, b, xstrcoll); } \
3606 static int strcmp_##key_name (V a, V b) \
3607 { return key_cmp_func (a, b, strcmp); } \
3609 /* reverse, non-dirfirst versions */ \
3610 static int rev_xstrcoll_##key_name (V a, V b) \
3611 { return key_cmp_func (b, a, xstrcoll); } \
3612 static int rev_strcmp_##key_name (V a, V b) \
3613 { return key_cmp_func (b, a, strcmp); } \
3615 /* direct, dirfirst versions */ \
3616 static int xstrcoll_df_##key_name (V a, V b) \
3617 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \
3618 static int strcmp_df_##key_name (V a, V b) \
3619 { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \
3621 /* reverse, dirfirst versions */ \
3622 static int rev_xstrcoll_df_##key_name (V a, V b) \
3623 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \
3624 static int rev_strcmp_df_##key_name (V a, V b) \
3625 { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, strcmp); }
3628 cmp_ctime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3629 int (*cmp
) (char const *, char const *))
3631 int diff
= timespec_cmp (get_stat_ctime (&b
->stat
),
3632 get_stat_ctime (&a
->stat
));
3633 return diff
? diff
: cmp (a
->name
, b
->name
);
3637 cmp_mtime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3638 int (*cmp
) (char const *, char const *))
3640 int diff
= timespec_cmp (get_stat_mtime (&b
->stat
),
3641 get_stat_mtime (&a
->stat
));
3642 return diff
? diff
: cmp (a
->name
, b
->name
);
3646 cmp_atime (struct fileinfo
const *a
, struct fileinfo
const *b
,
3647 int (*cmp
) (char const *, char const *))
3649 int diff
= timespec_cmp (get_stat_atime (&b
->stat
),
3650 get_stat_atime (&a
->stat
));
3651 return diff
? diff
: cmp (a
->name
, b
->name
);
3655 cmp_size (struct fileinfo
const *a
, struct fileinfo
const *b
,
3656 int (*cmp
) (char const *, char const *))
3658 int diff
= longdiff (b
->stat
.st_size
, a
->stat
.st_size
);
3659 return diff
? diff
: cmp (a
->name
, b
->name
);
3663 cmp_name (struct fileinfo
const *a
, struct fileinfo
const *b
,
3664 int (*cmp
) (char const *, char const *))
3666 return cmp (a
->name
, b
->name
);
3669 /* Compare file extensions. Files with no extension are 'smallest'.
3670 If extensions are the same, compare by file names instead. */
3673 cmp_extension (struct fileinfo
const *a
, struct fileinfo
const *b
,
3674 int (*cmp
) (char const *, char const *))
3676 char const *base1
= strrchr (a
->name
, '.');
3677 char const *base2
= strrchr (b
->name
, '.');
3678 int diff
= cmp (base1
? base1
: "", base2
? base2
: "");
3679 return diff
? diff
: cmp (a
->name
, b
->name
);
3682 DEFINE_SORT_FUNCTIONS (ctime
, cmp_ctime
)
3683 DEFINE_SORT_FUNCTIONS (mtime
, cmp_mtime
)
3684 DEFINE_SORT_FUNCTIONS (atime
, cmp_atime
)
3685 DEFINE_SORT_FUNCTIONS (size
, cmp_size
)
3686 DEFINE_SORT_FUNCTIONS (name
, cmp_name
)
3687 DEFINE_SORT_FUNCTIONS (extension
, cmp_extension
)
3689 /* Compare file versions.
3690 Unlike all other compare functions above, cmp_version depends only
3691 on filevercmp, which does not fail (even for locale reasons), and does not
3692 need a secondary sort key. See lib/filevercmp.h for function description.
3694 All the other sort options, in fact, need xstrcoll and strcmp variants,
3695 because they all use a string comparison (either as the primary or secondary
3696 sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
3697 locale reasons. Lastly, filevercmp is ALWAYS available with gnulib. */
3699 cmp_version (struct fileinfo
const *a
, struct fileinfo
const *b
)
3701 return filevercmp (a
->name
, b
->name
);
3704 static int xstrcoll_version (V a
, V b
)
3705 { return cmp_version (a
, b
); }
3706 static int rev_xstrcoll_version (V a
, V b
)
3707 { return cmp_version (b
, a
); }
3708 static int xstrcoll_df_version (V a
, V b
)
3709 { DIRFIRST_CHECK (a
, b
); return cmp_version (a
, b
); }
3710 static int rev_xstrcoll_df_version (V a
, V b
)
3711 { DIRFIRST_CHECK (a
, b
); return cmp_version (b
, a
); }
3714 /* We have 2^3 different variants for each sort-key function
3715 (for 3 independent sort modes).
3716 The function pointers stored in this array must be dereferenced as:
3718 sort_variants[sort_key][use_strcmp][reverse][dirs_first]
3720 Note that the order in which sort keys are listed in the function pointer
3721 array below is defined by the order of the elements in the time_type and
3724 #define LIST_SORTFUNCTION_VARIANTS(key_name) \
3727 { xstrcoll_##key_name, xstrcoll_df_##key_name }, \
3728 { rev_xstrcoll_##key_name, rev_xstrcoll_df_##key_name }, \
3731 { strcmp_##key_name, strcmp_df_##key_name }, \
3732 { rev_strcmp_##key_name, rev_strcmp_df_##key_name }, \
3736 static qsortFunc
const sort_functions
[][2][2][2] =
3738 LIST_SORTFUNCTION_VARIANTS (name
),
3739 LIST_SORTFUNCTION_VARIANTS (extension
),
3740 LIST_SORTFUNCTION_VARIANTS (size
),
3744 { xstrcoll_version
, xstrcoll_df_version
},
3745 { rev_xstrcoll_version
, rev_xstrcoll_df_version
},
3748 /* We use NULL for the strcmp variants of version comparison
3749 since as explained in cmp_version definition, version comparison
3750 does not rely on xstrcoll, so it will never longjmp, and never
3751 need to try the strcmp fallback. */
3758 /* last are time sort functions */
3759 LIST_SORTFUNCTION_VARIANTS (mtime
),
3760 LIST_SORTFUNCTION_VARIANTS (ctime
),
3761 LIST_SORTFUNCTION_VARIANTS (atime
)
3764 /* The number of sort keys is calculated as the sum of
3765 the number of elements in the sort_type enum (i.e., sort_numtypes)
3766 the number of elements in the time_type enum (i.e., time_numtypes) - 1
3767 This is because when sort_type==sort_time, we have up to
3768 time_numtypes possible sort keys.
3770 This line verifies at compile-time that the array of sort functions has been
3771 initialized for all possible sort keys. */
3772 verify (ARRAY_CARDINALITY (sort_functions
)
3773 == sort_numtypes
+ time_numtypes
- 1 );
3775 /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */
3778 initialize_ordering_vector (void)
3780 for (size_t i
= 0; i
< cwd_n_used
; i
++)
3781 sorted_file
[i
] = &cwd_file
[i
];
3784 /* Sort the files now in the table. */
3791 if (sorted_file_alloc
< cwd_n_used
+ cwd_n_used
/ 2)
3794 sorted_file
= xnmalloc (cwd_n_used
, 3 * sizeof *sorted_file
);
3795 sorted_file_alloc
= 3 * cwd_n_used
;
3798 initialize_ordering_vector ();
3800 if (sort_type
== sort_none
)
3803 /* Try strcoll. If it fails, fall back on strcmp. We can't safely
3804 ignore strcoll failures, as a failing strcoll might be a
3805 comparison function that is not a total order, and if we ignored
3806 the failure this might cause qsort to dump core. */
3808 if (! setjmp (failed_strcoll
))
3809 use_strcmp
= false; /* strcoll() succeeded */
3813 assert (sort_type
!= sort_version
);
3814 initialize_ordering_vector ();
3817 /* When sort_type == sort_time, use time_type as subindex. */
3818 mpsort ((void const **) sorted_file
, cwd_n_used
,
3819 sort_functions
[sort_type
+ (sort_type
== sort_time
? time_type
: 0)]
3820 [use_strcmp
][sort_reverse
]
3821 [directories_first
]);
3824 /* List all the files now in the table. */
3827 print_current_files (void)
3834 for (i
= 0; i
< cwd_n_used
; i
++)
3836 print_file_name_and_frills (sorted_file
[i
], 0);
3843 print_with_separator (' ');
3845 print_many_per_line ();
3850 print_with_separator (' ');
3852 print_horizontal ();
3856 print_with_separator (',');
3860 for (i
= 0; i
< cwd_n_used
; i
++)
3862 set_normal_color ();
3863 print_long_format (sorted_file
[i
]);
3864 DIRED_PUTCHAR ('\n');
3870 /* Replace the first %b with precomputed aligned month names.
3871 Note on glibc-2.7 at least, this speeds up the whole 'ls -lU'
3872 process by around 17%, compared to letting strftime() handle the %b. */
3875 align_nstrftime (char *buf
, size_t size
, bool recent
, struct tm
const *tm
,
3876 timezone_t tz
, int ns
)
3878 char const *nfmt
= (use_abformat
3879 ? abformat
[recent
][tm
->tm_mon
]
3880 : long_time_format
[recent
]);
3881 return nstrftime (buf
, size
, nfmt
, tm
, tz
, ns
);
3884 /* Return the expected number of columns in a long-format timestamp,
3885 or zero if it cannot be calculated. */
3888 long_time_expected_width (void)
3890 static int width
= -1;
3896 char buf
[TIME_STAMP_LEN_MAXIMUM
+ 1];
3898 /* In case you're wondering if localtime_rz can fail with an input time_t
3899 value of 0, let's just say it's very unlikely, but not inconceivable.
3900 The TZ environment variable would have to specify a time zone that
3901 is 2**31-1900 years or more ahead of UTC. This could happen only on
3902 a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000.
3903 However, this is not possible with Solaris 10 or glibc-2.3.5, since
3904 their implementations limit the offset to 167:59 and 24:00, resp. */
3905 if (localtime_rz (localtz
, &epoch
, &tm
))
3907 size_t len
= align_nstrftime (buf
, sizeof buf
, false,
3910 width
= mbsnwidth (buf
, len
, 0);
3920 /* Print the user or group name NAME, with numeric id ID, using a
3921 print width of WIDTH columns. */
3924 format_user_or_group (char const *name
, unsigned long int id
, int width
)
3930 int width_gap
= width
- mbswidth (name
, 0);
3931 int pad
= MAX (0, width_gap
);
3932 fputs (name
, stdout
);
3933 len
= strlen (name
) + pad
;
3941 printf ("%*lu ", width
, id
);
3945 dired_pos
+= len
+ 1;
3948 /* Print the name or id of the user with id U, using a print width of
3952 format_user (uid_t u
, int width
, bool stat_ok
)
3954 format_user_or_group (! stat_ok
? "?" :
3955 (numeric_ids
? NULL
: getuser (u
)), u
, width
);
3958 /* Likewise, for groups. */
3961 format_group (gid_t g
, int width
, bool stat_ok
)
3963 format_user_or_group (! stat_ok
? "?" :
3964 (numeric_ids
? NULL
: getgroup (g
)), g
, width
);
3967 /* Return the number of columns that format_user_or_group will print. */
3970 format_user_or_group_width (char const *name
, unsigned long int id
)
3974 int len
= mbswidth (name
, 0);
3975 return MAX (0, len
);
3979 char buf
[INT_BUFSIZE_BOUND (id
)];
3980 sprintf (buf
, "%lu", id
);
3981 return strlen (buf
);
3985 /* Return the number of columns that format_user will print. */
3988 format_user_width (uid_t u
)
3990 return format_user_or_group_width (numeric_ids
? NULL
: getuser (u
), u
);
3993 /* Likewise, for groups. */
3996 format_group_width (gid_t g
)
3998 return format_user_or_group_width (numeric_ids
? NULL
: getgroup (g
), g
);
4001 /* Return a pointer to a formatted version of F->stat.st_ino,
4002 possibly using buffer, BUF, of length BUFLEN, which must be at least
4003 INT_BUFSIZE_BOUND (uintmax_t) bytes. */
4005 format_inode (char *buf
, size_t buflen
, const struct fileinfo
*f
)
4007 assert (INT_BUFSIZE_BOUND (uintmax_t) <= buflen
);
4008 return (f
->stat_ok
&& f
->stat
.st_ino
!= NOT_AN_INODE_NUMBER
4009 ? umaxtostr (f
->stat
.st_ino
, buf
)
4013 /* Print information about F in long format. */
4015 print_long_format (const struct fileinfo
*f
)
4019 [LONGEST_HUMAN_READABLE
+ 1 /* inode */
4020 + LONGEST_HUMAN_READABLE
+ 1 /* size in blocks */
4021 + sizeof (modebuf
) - 1 + 1 /* mode string */
4022 + INT_BUFSIZE_BOUND (uintmax_t) /* st_nlink */
4023 + LONGEST_HUMAN_READABLE
+ 2 /* major device number */
4024 + LONGEST_HUMAN_READABLE
+ 1 /* minor device number */
4025 + TIME_STAMP_LEN_MAXIMUM
+ 1 /* max length of time/date */
4029 struct timespec when_timespec
;
4030 struct tm when_local
;
4032 /* Compute the mode string, except remove the trailing space if no
4033 file in this directory has an ACL or security context. */
4035 filemodestring (&f
->stat
, modebuf
);
4038 modebuf
[0] = filetype_letter
[f
->filetype
];
4039 memset (modebuf
+ 1, '?', 10);
4044 else if (f
->acl_type
== ACL_T_LSM_CONTEXT_ONLY
)
4046 else if (f
->acl_type
== ACL_T_YES
)
4052 when_timespec
= get_stat_ctime (&f
->stat
);
4055 when_timespec
= get_stat_mtime (&f
->stat
);
4058 when_timespec
= get_stat_atime (&f
->stat
);
4068 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4069 sprintf (p
, "%*s ", inode_number_width
,
4070 format_inode (hbuf
, sizeof hbuf
, f
));
4071 /* Increment by strlen (p) here, rather than by inode_number_width + 1.
4072 The latter is wrong when inode_number_width is zero. */
4076 if (print_block_size
)
4078 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
4079 char const *blocks
=
4082 : human_readable (ST_NBLOCKS (f
->stat
), hbuf
, human_output_opts
,
4083 ST_NBLOCKSIZE
, output_block_size
));
4085 for (pad
= block_size_width
- mbswidth (blocks
, 0); 0 < pad
; pad
--)
4087 while ((*p
++ = *blocks
++))
4092 /* The last byte of the mode string is the POSIX
4093 "optional alternate access method flag". */
4095 char hbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4096 sprintf (p
, "%s %*s ", modebuf
, nlink_width
,
4097 ! f
->stat_ok
? "?" : umaxtostr (f
->stat
.st_nlink
, hbuf
));
4099 /* Increment by strlen (p) here, rather than by, e.g.,
4100 sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1.
4101 The latter is wrong when nlink_width is zero. */
4106 if (print_owner
|| print_group
|| print_author
|| print_scontext
)
4108 DIRED_FPUTS (buf
, stdout
, p
- buf
);
4111 format_user (f
->stat
.st_uid
, owner_width
, f
->stat_ok
);
4114 format_group (f
->stat
.st_gid
, group_width
, f
->stat_ok
);
4117 format_user (f
->stat
.st_author
, author_width
, f
->stat_ok
);
4120 format_user_or_group (f
->scontext
, 0, scontext_width
);
4126 && (S_ISCHR (f
->stat
.st_mode
) || S_ISBLK (f
->stat
.st_mode
)))
4128 char majorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4129 char minorbuf
[INT_BUFSIZE_BOUND (uintmax_t)];
4130 int blanks_width
= (file_size_width
4131 - (major_device_number_width
+ 2
4132 + minor_device_number_width
));
4133 sprintf (p
, "%*s, %*s ",
4134 major_device_number_width
+ MAX (0, blanks_width
),
4135 umaxtostr (major (f
->stat
.st_rdev
), majorbuf
),
4136 minor_device_number_width
,
4137 umaxtostr (minor (f
->stat
.st_rdev
), minorbuf
));
4138 p
+= file_size_width
+ 1;
4142 char hbuf
[LONGEST_HUMAN_READABLE
+ 1];
4146 : human_readable (unsigned_file_size (f
->stat
.st_size
),
4147 hbuf
, file_human_output_opts
, 1,
4148 file_output_block_size
));
4150 for (pad
= file_size_width
- mbswidth (size
, 0); 0 < pad
; pad
--)
4152 while ((*p
++ = *size
++))
4160 if (f
->stat_ok
&& localtime_rz (localtz
, &when_timespec
.tv_sec
, &when_local
))
4162 struct timespec six_months_ago
;
4165 /* If the file appears to be in the future, update the current
4166 time, in case the file happens to have been modified since
4167 the last time we checked the clock. */
4168 if (timespec_cmp (current_time
, when_timespec
) < 0)
4169 gettime (¤t_time
);
4171 /* Consider a time to be recent if it is within the past six months.
4172 A Gregorian year has 365.2425 * 24 * 60 * 60 == 31556952 seconds
4173 on the average. Write this value as an integer constant to
4174 avoid floating point hassles. */
4175 six_months_ago
.tv_sec
= current_time
.tv_sec
- 31556952 / 2;
4176 six_months_ago
.tv_nsec
= current_time
.tv_nsec
;
4178 recent
= (timespec_cmp (six_months_ago
, when_timespec
) < 0
4179 && (timespec_cmp (when_timespec
, current_time
) < 0));
4181 /* We assume here that all time zones are offset from UTC by a
4182 whole number of seconds. */
4183 s
= align_nstrftime (p
, TIME_STAMP_LEN_MAXIMUM
+ 1, recent
,
4184 &when_local
, localtz
, when_timespec
.tv_nsec
);
4192 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
4197 /* The time cannot be converted using the desired format, so
4198 print it as a huge integer number of seconds. */
4199 char hbuf
[INT_BUFSIZE_BOUND (intmax_t)];
4200 sprintf (p
, "%*s ", long_time_expected_width (),
4203 : timetostr (when_timespec
.tv_sec
, hbuf
)));
4204 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
4208 DIRED_FPUTS (buf
, stdout
, p
- buf
);
4209 size_t w
= print_name_with_quoting (f
, false, &dired_obstack
, p
- buf
);
4211 if (f
->filetype
== symbolic_link
)
4215 DIRED_FPUTS_LITERAL (" -> ", stdout
);
4216 print_name_with_quoting (f
, true, NULL
, (p
- buf
) + w
+ 4);
4217 if (indicator_style
!= none
)
4218 print_type_indicator (true, f
->linkmode
, unknown
);
4221 else if (indicator_style
!= none
)
4222 print_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
4225 /* Write to *BUF a quoted representation of the file name NAME, if non-NULL,
4226 using OPTIONS to control quoting. *BUF is set to NAME if no quoting
4227 is required. *BUF is allocated if more space required (and the original
4228 *BUF is not deallocated).
4229 Store the number of screen columns occupied by NAME's quoted
4230 representation into WIDTH, if non-NULL.
4231 Store into PAD whether an initial space is needed for padding.
4232 Return the number of bytes in *BUF. */
4235 quote_name_buf (char **inbuf
, size_t bufsize
, char *name
,
4236 struct quoting_options
const *options
,
4237 int needs_general_quoting
, size_t *width
, bool *pad
)
4240 size_t displayed_width
IF_LINT ( = 0);
4244 enum quoting_style qs
= get_quoting_style (options
);
4245 bool needs_further_quoting
= qmark_funny_chars
4246 && (qs
== shell_quoting_style
4247 || qs
== shell_always_quoting_style
4248 || qs
== literal_quoting_style
);
4250 if (needs_general_quoting
!= 0)
4252 len
= quotearg_buffer (buf
, bufsize
, name
, -1, options
);
4255 buf
= xmalloc (len
+ 1);
4256 quotearg_buffer (buf
, len
+ 1, name
, -1, options
);
4259 quoted
= (*name
!= *buf
) || strlen (name
) != len
;
4261 else if (needs_further_quoting
)
4263 len
= strlen (name
);
4265 buf
= xmalloc (len
+ 1);
4266 memcpy (buf
, name
, len
+ 1);
4272 len
= strlen (name
);
4277 if (needs_further_quoting
)
4281 char const *p
= buf
;
4282 char const *plimit
= buf
+ len
;
4284 displayed_width
= 0;
4289 case ' ': case '!': case '"': case '#': case '%':
4290 case '&': case '\'': case '(': case ')': case '*':
4291 case '+': case ',': case '-': case '.': case '/':
4292 case '0': case '1': case '2': case '3': case '4':
4293 case '5': case '6': case '7': case '8': case '9':
4294 case ':': case ';': case '<': case '=': case '>':
4296 case 'A': case 'B': case 'C': case 'D': case 'E':
4297 case 'F': case 'G': case 'H': case 'I': case 'J':
4298 case 'K': case 'L': case 'M': case 'N': case 'O':
4299 case 'P': case 'Q': case 'R': case 'S': case 'T':
4300 case 'U': case 'V': case 'W': case 'X': case 'Y':
4302 case '[': case '\\': case ']': case '^': case '_':
4303 case 'a': case 'b': case 'c': case 'd': case 'e':
4304 case 'f': case 'g': case 'h': case 'i': case 'j':
4305 case 'k': case 'l': case 'm': case 'n': case 'o':
4306 case 'p': case 'q': case 'r': case 's': case 't':
4307 case 'u': case 'v': case 'w': case 'x': case 'y':
4308 case 'z': case '{': case '|': case '}': case '~':
4309 /* These characters are printable ASCII characters. */
4311 displayed_width
+= 1;
4314 /* If we have a multibyte sequence, copy it until we
4315 reach its end, replacing each non-printable multibyte
4316 character with a single question mark. */
4318 mbstate_t mbstate
= { 0, };
4325 bytes
= mbrtowc (&wc
, p
, plimit
- p
, &mbstate
);
4327 if (bytes
== (size_t) -1)
4329 /* An invalid multibyte sequence was
4330 encountered. Skip one input byte, and
4331 put a question mark. */
4334 displayed_width
+= 1;
4338 if (bytes
== (size_t) -2)
4340 /* An incomplete multibyte character
4341 at the end. Replace it entirely with
4345 displayed_width
+= 1;
4350 /* A null wide character was encountered. */
4356 /* A printable multibyte character.
4358 for (; bytes
> 0; --bytes
)
4360 displayed_width
+= w
;
4364 /* An unprintable multibyte character.
4365 Replace it entirely with a question
4369 displayed_width
+= 1;
4372 while (! mbsinit (&mbstate
));
4377 /* The buffer may have shrunk. */
4383 char const *plimit
= buf
+ len
;
4387 if (! isprint (to_uchar (*p
)))
4391 displayed_width
= len
;
4394 else if (width
!= NULL
)
4397 displayed_width
= mbsnwidth (buf
, len
, 0);
4400 char const *p
= buf
;
4401 char const *plimit
= buf
+ len
;
4403 displayed_width
= 0;
4406 if (isprint (to_uchar (*p
)))
4413 /* Set padding to better align quoted items,
4414 and also give a visual indication that quotes are
4415 not actually part of the name. */
4416 *pad
= (align_variable_outer_quotes
&& cwd_some_quoted
&& ! quoted
);
4419 *width
= displayed_width
;
4427 quote_name_width (const char *name
, struct quoting_options
const *options
,
4428 int needs_general_quoting
)
4430 char smallbuf
[BUFSIZ
];
4431 char *buf
= smallbuf
;
4435 quote_name_buf (&buf
, sizeof smallbuf
, (char *) name
, options
,
4436 needs_general_quoting
, &width
, &pad
);
4438 if (buf
!= smallbuf
&& buf
!= name
)
4446 /* %XX escape any input out of range as defined in RFC3986,
4447 and also if PATH, convert all path separators to '/'. */
4449 file_escape (const char *str
, bool path
)
4451 char *esc
= xnmalloc (3, strlen (str
) + 1);
4455 if (path
&& ISSLASH (*str
))
4460 else if (RFC3986
[to_uchar (*str
)])
4463 p
+= sprintf (p
, "%%%02x", to_uchar (*str
++));
4470 quote_name (char const *name
, struct quoting_options
const *options
,
4471 int needs_general_quoting
, const struct bin_str
*color
,
4472 bool allow_pad
, struct obstack
*stack
, char const *absolute_name
)
4474 char smallbuf
[BUFSIZ
];
4475 char *buf
= smallbuf
;
4479 len
= quote_name_buf (&buf
, sizeof smallbuf
, (char *) name
, options
,
4480 needs_general_quoting
, NULL
, &pad
);
4482 if (pad
&& allow_pad
)
4483 DIRED_PUTCHAR (' ');
4486 print_color_indicator (color
);
4488 /* If we're padding, then don't include the outer quotes in
4489 the --hyperlink, to improve the alignment of those links. */
4490 bool skip_quotes
= false;
4494 if (align_variable_outer_quotes
&& cwd_some_quoted
&& ! pad
)
4499 char *h
= file_escape (hostname
, /* path= */ false);
4500 char *n
= file_escape (absolute_name
, /* path= */ true);
4501 /* TODO: It would be good to be able to define parameters
4502 to give hints to the terminal as how best to render the URI.
4503 For example since ls is outputting a dense block of URIs
4504 it would be best to not underline by default, and only
4505 do so upon hover etc. */
4506 printf ("\033]8;;file://%s%s%s\a", h
, *n
== '/' ? "" : "/", n
);
4512 PUSH_CURRENT_DIRED_POS (stack
);
4514 fwrite (buf
+ skip_quotes
, 1, len
- (skip_quotes
* 2), stdout
);
4519 PUSH_CURRENT_DIRED_POS (stack
);
4523 fputs ("\033]8;;\a", stdout
);
4525 putchar (*(buf
+ len
- 1));
4528 if (buf
!= smallbuf
&& buf
!= name
)
4535 print_name_with_quoting (const struct fileinfo
*f
,
4536 bool symlink_target
,
4537 struct obstack
*stack
,
4540 const char* name
= symlink_target
? f
->linkname
: f
->name
;
4542 const struct bin_str
*color
= print_with_color
?
4543 get_color_indicator (f
, symlink_target
) : NULL
;
4545 bool used_color_this_time
= (print_with_color
4546 && (color
|| is_colored (C_NORM
)));
4548 size_t len
= quote_name (name
, filename_quoting_options
, f
->quoted
,
4549 color
, !symlink_target
, stack
, f
->absolute_name
);
4552 if (used_color_this_time
)
4554 prep_non_filename_text ();
4556 /* We use the byte length rather than display width here as
4557 an optimization to avoid accurately calculating the width,
4558 because we only output the clear to EOL sequence if the name
4559 _might_ wrap to the next line. This may output a sequence
4560 unnecessarily in multi-byte locales for example,
4561 but in that case it's inconsequential to the output. */
4563 && (start_col
/ line_length
!= (start_col
+ len
- 1) / line_length
))
4564 put_indicator (&color_indicator
[C_CLR_TO_EOL
]);
4571 prep_non_filename_text (void)
4573 if (color_indicator
[C_END
].string
!= NULL
)
4574 put_indicator (&color_indicator
[C_END
]);
4577 put_indicator (&color_indicator
[C_LEFT
]);
4578 put_indicator (&color_indicator
[C_RESET
]);
4579 put_indicator (&color_indicator
[C_RIGHT
]);
4583 /* Print the file name of 'f' with appropriate quoting.
4584 Also print file size, inode number, and filetype indicator character,
4585 as requested by switches. */
4588 print_file_name_and_frills (const struct fileinfo
*f
, size_t start_col
)
4590 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
4592 set_normal_color ();
4595 printf ("%*s ", format
== with_commas
? 0 : inode_number_width
,
4596 format_inode (buf
, sizeof buf
, f
));
4598 if (print_block_size
)
4599 printf ("%*s ", format
== with_commas
? 0 : block_size_width
,
4601 : human_readable (ST_NBLOCKS (f
->stat
), buf
, human_output_opts
,
4602 ST_NBLOCKSIZE
, output_block_size
));
4605 printf ("%*s ", format
== with_commas
? 0 : scontext_width
, f
->scontext
);
4607 size_t width
= print_name_with_quoting (f
, false, NULL
, start_col
);
4609 if (indicator_style
!= none
)
4610 width
+= print_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
4615 /* Given these arguments describing a file, return the single-byte
4616 type indicator, or 0. */
4618 get_type_indicator (bool stat_ok
, mode_t mode
, enum filetype type
)
4622 if (stat_ok
? S_ISREG (mode
) : type
== normal
)
4624 if (stat_ok
&& indicator_style
== classify
&& (mode
& S_IXUGO
))
4631 if (stat_ok
? S_ISDIR (mode
) : type
== directory
|| type
== arg_directory
)
4633 else if (indicator_style
== slash
)
4635 else if (stat_ok
? S_ISLNK (mode
) : type
== symbolic_link
)
4637 else if (stat_ok
? S_ISFIFO (mode
) : type
== fifo
)
4639 else if (stat_ok
? S_ISSOCK (mode
) : type
== sock
)
4641 else if (stat_ok
&& S_ISDOOR (mode
))
4650 print_type_indicator (bool stat_ok
, mode_t mode
, enum filetype type
)
4652 char c
= get_type_indicator (stat_ok
, mode
, type
);
4658 /* Returns if color sequence was printed. */
4660 print_color_indicator (const struct bin_str
*ind
)
4664 /* Need to reset so not dealing with attribute combinations */
4665 if (is_colored (C_NORM
))
4666 restore_default_color ();
4667 put_indicator (&color_indicator
[C_LEFT
]);
4668 put_indicator (ind
);
4669 put_indicator (&color_indicator
[C_RIGHT
]);
4675 /* Returns color indicator or NULL if none. */
4676 static const struct bin_str
* _GL_ATTRIBUTE_PURE
4677 get_color_indicator (const struct fileinfo
*f
, bool symlink_target
)
4679 enum indicator_no type
;
4680 struct color_ext_type
*ext
; /* Color extension */
4681 size_t len
; /* Length of name */
4690 linkok
= f
->linkok
? 0 : -1;
4695 mode
= FILE_OR_LINK_MODE (f
);
4699 /* Is this a nonexistent file? If so, linkok == -1. */
4701 if (linkok
== -1 && is_colored (C_MISSING
))
4703 else if (!f
->stat_ok
)
4705 static enum indicator_no filetype_indicator
[] = FILETYPE_INDICATORS
;
4706 type
= filetype_indicator
[f
->filetype
];
4714 if ((mode
& S_ISUID
) != 0 && is_colored (C_SETUID
))
4716 else if ((mode
& S_ISGID
) != 0 && is_colored (C_SETGID
))
4718 else if (is_colored (C_CAP
) && f
->has_capability
)
4720 else if ((mode
& S_IXUGO
) != 0 && is_colored (C_EXEC
))
4722 else if ((1 < f
->stat
.st_nlink
) && is_colored (C_MULTIHARDLINK
))
4723 type
= C_MULTIHARDLINK
;
4725 else if (S_ISDIR (mode
))
4729 if ((mode
& S_ISVTX
) && (mode
& S_IWOTH
)
4730 && is_colored (C_STICKY_OTHER_WRITABLE
))
4731 type
= C_STICKY_OTHER_WRITABLE
;
4732 else if ((mode
& S_IWOTH
) != 0 && is_colored (C_OTHER_WRITABLE
))
4733 type
= C_OTHER_WRITABLE
;
4734 else if ((mode
& S_ISVTX
) != 0 && is_colored (C_STICKY
))
4737 else if (S_ISLNK (mode
))
4739 else if (S_ISFIFO (mode
))
4741 else if (S_ISSOCK (mode
))
4743 else if (S_ISBLK (mode
))
4745 else if (S_ISCHR (mode
))
4747 else if (S_ISDOOR (mode
))
4751 /* Classify a file of some other type as C_ORPHAN. */
4756 /* Check the file's suffix only if still classified as C_FILE. */
4760 /* Test if NAME has a recognized suffix. */
4762 len
= strlen (name
);
4763 name
+= len
; /* Pointer to final \0. */
4764 for (ext
= color_ext_list
; ext
!= NULL
; ext
= ext
->next
)
4766 if (ext
->ext
.len
<= len
4767 && STREQ_LEN (name
- ext
->ext
.len
, ext
->ext
.string
,
4773 /* Adjust the color for orphaned symlinks. */
4774 if (type
== C_LINK
&& !linkok
)
4776 if (color_symlink_as_referent
|| is_colored (C_ORPHAN
))
4780 const struct bin_str
*const s
4781 = ext
? &(ext
->seq
) : &color_indicator
[type
];
4783 return s
->string
? s
: NULL
;
4786 /* Output a color indicator (which may contain nulls). */
4788 put_indicator (const struct bin_str
*ind
)
4794 /* If the standard output is a controlling terminal, watch out
4795 for signals, so that the colors can be restored to the
4796 default state if "ls" is suspended or interrupted. */
4798 if (0 <= tcgetpgrp (STDOUT_FILENO
))
4801 prep_non_filename_text ();
4804 fwrite (ind
->string
, ind
->len
, 1, stdout
);
4808 length_of_file_name_and_frills (const struct fileinfo
*f
)
4811 char buf
[MAX (LONGEST_HUMAN_READABLE
+ 1, INT_BUFSIZE_BOUND (uintmax_t))];
4814 len
+= 1 + (format
== with_commas
4815 ? strlen (umaxtostr (f
->stat
.st_ino
, buf
))
4816 : inode_number_width
);
4818 if (print_block_size
)
4819 len
+= 1 + (format
== with_commas
4820 ? strlen (! f
->stat_ok
? "?"
4821 : human_readable (ST_NBLOCKS (f
->stat
), buf
,
4822 human_output_opts
, ST_NBLOCKSIZE
,
4824 : block_size_width
);
4827 len
+= 1 + (format
== with_commas
? strlen (f
->scontext
) : scontext_width
);
4829 len
+= quote_name_width (f
->name
, filename_quoting_options
, f
->quoted
);
4831 if (indicator_style
!= none
)
4833 char c
= get_type_indicator (f
->stat_ok
, f
->stat
.st_mode
, f
->filetype
);
4841 print_many_per_line (void)
4843 size_t row
; /* Current row. */
4844 size_t cols
= calculate_columns (true);
4845 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
4847 /* Calculate the number of rows that will be in each column except possibly
4848 for a short column on the right. */
4849 size_t rows
= cwd_n_used
/ cols
+ (cwd_n_used
% cols
!= 0);
4851 for (row
= 0; row
< rows
; row
++)
4854 size_t filesno
= row
;
4857 /* Print the next row. */
4860 struct fileinfo
const *f
= sorted_file
[filesno
];
4861 size_t name_length
= length_of_file_name_and_frills (f
);
4862 size_t max_name_length
= line_fmt
->col_arr
[col
++];
4863 print_file_name_and_frills (f
, pos
);
4866 if (filesno
>= cwd_n_used
)
4869 indent (pos
+ name_length
, pos
+ max_name_length
);
4870 pos
+= max_name_length
;
4877 print_horizontal (void)
4881 size_t cols
= calculate_columns (false);
4882 struct column_info
const *line_fmt
= &column_info
[cols
- 1];
4883 struct fileinfo
const *f
= sorted_file
[0];
4884 size_t name_length
= length_of_file_name_and_frills (f
);
4885 size_t max_name_length
= line_fmt
->col_arr
[0];
4887 /* Print first entry. */
4888 print_file_name_and_frills (f
, 0);
4891 for (filesno
= 1; filesno
< cwd_n_used
; ++filesno
)
4893 size_t col
= filesno
% cols
;
4902 indent (pos
+ name_length
, pos
+ max_name_length
);
4903 pos
+= max_name_length
;
4906 f
= sorted_file
[filesno
];
4907 print_file_name_and_frills (f
, pos
);
4909 name_length
= length_of_file_name_and_frills (f
);
4910 max_name_length
= line_fmt
->col_arr
[col
];
4915 /* Output name + SEP + ' '. */
4918 print_with_separator (char sep
)
4923 for (filesno
= 0; filesno
< cwd_n_used
; filesno
++)
4925 struct fileinfo
const *f
= sorted_file
[filesno
];
4926 size_t len
= line_length
? length_of_file_name_and_frills (f
) : 0;
4933 || ((pos
+ len
+ 2 < line_length
)
4934 && (pos
<= SIZE_MAX
- len
- 2)))
4946 putchar (separator
);
4949 print_file_name_and_frills (f
, pos
);
4955 /* Assuming cursor is at position FROM, indent up to position TO.
4956 Use a TAB character instead of two or more spaces whenever possible. */
4959 indent (size_t from
, size_t to
)
4963 if (tabsize
!= 0 && to
/ tabsize
> (from
+ 1) / tabsize
)
4966 from
+= tabsize
- from
% tabsize
;
4976 /* Put DIRNAME/NAME into DEST, handling '.' and '/' properly. */
4977 /* FIXME: maybe remove this function someday. See about using a
4978 non-malloc'ing version of file_name_concat. */
4981 attach (char *dest
, const char *dirname
, const char *name
)
4983 const char *dirnamep
= dirname
;
4985 /* Copy dirname if it is not ".". */
4986 if (dirname
[0] != '.' || dirname
[1] != 0)
4989 *dest
++ = *dirnamep
++;
4990 /* Add '/' if 'dirname' doesn't already end with it. */
4991 if (dirnamep
> dirname
&& dirnamep
[-1] != '/')
4999 /* Allocate enough column info suitable for the current number of
5000 files and display columns, and initialize the info to represent the
5001 narrowest possible columns. */
5004 init_column_info (void)
5007 size_t max_cols
= MIN (max_idx
, cwd_n_used
);
5009 /* Currently allocated columns in column_info. */
5010 static size_t column_info_alloc
;
5012 if (column_info_alloc
< max_cols
)
5014 size_t new_column_info_alloc
;
5017 if (max_cols
< max_idx
/ 2)
5019 /* The number of columns is far less than the display width
5020 allows. Grow the allocation, but only so that it's
5021 double the current requirements. If the display is
5022 extremely wide, this avoids allocating a lot of memory
5023 that is never needed. */
5024 column_info
= xnrealloc (column_info
, max_cols
,
5025 2 * sizeof *column_info
);
5026 new_column_info_alloc
= 2 * max_cols
;
5030 column_info
= xnrealloc (column_info
, max_idx
, sizeof *column_info
);
5031 new_column_info_alloc
= max_idx
;
5034 /* Allocate the new size_t objects by computing the triangle
5035 formula n * (n + 1) / 2, except that we don't need to
5036 allocate the part of the triangle that we've already
5037 allocated. Check for address arithmetic overflow. */
5039 size_t column_info_growth
= new_column_info_alloc
- column_info_alloc
;
5040 size_t s
= column_info_alloc
+ 1 + new_column_info_alloc
;
5041 size_t t
= s
* column_info_growth
;
5042 if (s
< new_column_info_alloc
|| t
/ column_info_growth
!= s
)
5044 p
= xnmalloc (t
/ 2, sizeof *p
);
5047 /* Grow the triangle by parceling out the cells just allocated. */
5048 for (i
= column_info_alloc
; i
< new_column_info_alloc
; i
++)
5050 column_info
[i
].col_arr
= p
;
5054 column_info_alloc
= new_column_info_alloc
;
5057 for (i
= 0; i
< max_cols
; ++i
)
5061 column_info
[i
].valid_len
= true;
5062 column_info
[i
].line_len
= (i
+ 1) * MIN_COLUMN_WIDTH
;
5063 for (j
= 0; j
<= i
; ++j
)
5064 column_info
[i
].col_arr
[j
] = MIN_COLUMN_WIDTH
;
5068 /* Calculate the number of columns needed to represent the current set
5069 of files in the current display width. */
5072 calculate_columns (bool by_columns
)
5074 size_t filesno
; /* Index into cwd_file. */
5075 size_t cols
; /* Number of files across. */
5077 /* Normally the maximum number of columns is determined by the
5078 screen width. But if few files are available this might limit it
5080 size_t max_cols
= MIN (max_idx
, cwd_n_used
);
5082 init_column_info ();
5084 /* Compute the maximum number of possible columns. */
5085 for (filesno
= 0; filesno
< cwd_n_used
; ++filesno
)
5087 struct fileinfo
const *f
= sorted_file
[filesno
];
5088 size_t name_length
= length_of_file_name_and_frills (f
);
5090 for (size_t i
= 0; i
< max_cols
; ++i
)
5092 if (column_info
[i
].valid_len
)
5094 size_t idx
= (by_columns
5095 ? filesno
/ ((cwd_n_used
+ i
) / (i
+ 1))
5096 : filesno
% (i
+ 1));
5097 size_t real_length
= name_length
+ (idx
== i
? 0 : 2);
5099 if (column_info
[i
].col_arr
[idx
] < real_length
)
5101 column_info
[i
].line_len
+= (real_length
5102 - column_info
[i
].col_arr
[idx
]);
5103 column_info
[i
].col_arr
[idx
] = real_length
;
5104 column_info
[i
].valid_len
= (column_info
[i
].line_len
5111 /* Find maximum allowed columns. */
5112 for (cols
= max_cols
; 1 < cols
; --cols
)
5114 if (column_info
[cols
- 1].valid_len
)
5124 if (status
!= EXIT_SUCCESS
)
5128 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name
);
5130 List information about the FILEs (the current directory by default).\n\
5131 Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.\n\
5134 emit_mandatory_arg_note ();
5137 -a, --all do not ignore entries starting with .\n\
5138 -A, --almost-all do not list implied . and ..\n\
5139 --author with -l, print the author of each file\n\
5140 -b, --escape print C-style escapes for nongraphic characters\n\
5143 --block-size=SIZE scale sizes by SIZE before printing them; e.g.,\n\
5144 '--block-size=M' prints sizes in units of\n\
5145 1,048,576 bytes; see SIZE format below\n\
5146 -B, --ignore-backups do not list implied entries ending with ~\n\
5147 -c with -lt: sort by, and show, ctime (time of last\n\
5148 modification of file status information);\n\
5149 with -l: show ctime and sort by name;\n\
5150 otherwise: sort by ctime, newest first\n\
5153 -C list entries by columns\n\
5154 --color[=WHEN] colorize the output; WHEN can be 'always' (default\
5156 if omitted), 'auto', or 'never'; more info below\
5158 -d, --directory list directories themselves, not their contents\n\
5159 -D, --dired generate output designed for Emacs' dired mode\n\
5162 -f do not sort, enable -aU, disable -ls --color\n\
5163 -F, --classify append indicator (one of */=>@|) to entries\n\
5164 --file-type likewise, except do not append '*'\n\
5165 --format=WORD across -x, commas -m, horizontal -x, long -l,\n\
5166 single-column -1, verbose -l, vertical -C\n\
5167 --full-time like -l --time-style=full-iso\n\
5170 -g like -l, but do not list owner\n\
5173 --group-directories-first\n\
5174 group directories before files;\n\
5175 can be augmented with a --sort option, but any\n\
5176 use of --sort=none (-U) disables grouping\n\
5179 -G, --no-group in a long listing, don't print group names\n\
5180 -h, --human-readable with -l and/or -s, print human readable sizes\n\
5181 (e.g., 1K 234M 2G)\n\
5182 --si likewise, but use powers of 1000 not 1024\n\
5185 -H, --dereference-command-line\n\
5186 follow symbolic links listed on the command line\n\
5187 --dereference-command-line-symlink-to-dir\n\
5188 follow each command line symbolic link\n\
5189 that points to a directory\n\
5190 --hide=PATTERN do not list implied entries matching shell PATTERN\
5192 (overridden by -a or -A)\n\
5195 --hyperlink[=WHEN] hyperlink file names; WHEN can be 'always'\n\
5196 (default if omitted), 'auto', or 'never'\n\
5199 --indicator-style=WORD append indicator with style WORD to entry names:\
5201 none (default), slash (-p),\n\
5202 file-type (--file-type), classify (-F)\n\
5203 -i, --inode print the index number of each file\n\
5204 -I, --ignore=PATTERN do not list implied entries matching shell PATTERN\
5206 -k, --kibibytes default to 1024-byte blocks for disk usage\n\
5209 -l use a long listing format\n\
5210 -L, --dereference when showing file information for a symbolic\n\
5211 link, show information for the file the link\n\
5212 references rather than for the link itself\n\
5213 -m fill width with a comma separated list of entries\
5217 -n, --numeric-uid-gid like -l, but list numeric user and group IDs\n\
5218 -N, --literal print entry names without quoting\n\
5219 -o like -l, but do not list group information\n\
5220 -p, --indicator-style=slash\n\
5221 append / indicator to directories\n\
5224 -q, --hide-control-chars print ? instead of nongraphic characters\n\
5225 --show-control-chars show nongraphic characters as-is (the default,\n\
5226 unless program is 'ls' and output is a terminal)\
5228 -Q, --quote-name enclose entry names in double quotes\n\
5229 --quoting-style=WORD use quoting style WORD for entry names:\n\
5230 literal, locale, shell, shell-always,\n\
5231 shell-escape, shell-escape-always, c, escape\n\
5234 -r, --reverse reverse order while sorting\n\
5235 -R, --recursive list subdirectories recursively\n\
5236 -s, --size print the allocated size of each file, in blocks\n\
5239 -S sort by file size, largest first\n\
5240 --sort=WORD sort by WORD instead of name: none (-U), size (-S)\
5242 time (-t), version (-v), extension (-X)\n\
5243 --time=WORD with -l, show time as WORD instead of default\n\
5244 modification time: atime or access or use (-u);\
5246 ctime or status (-c); also use specified time\n\
5247 as sort key if --sort=time (newest first)\n\
5250 --time-style=STYLE with -l, show times using style STYLE:\n\
5251 full-iso, long-iso, iso, locale, or +FORMAT;\n\
5252 FORMAT is interpreted like in 'date'; if FORMAT\
5254 is FORMAT1<newline>FORMAT2, then FORMAT1 applies\
5256 to non-recent files and FORMAT2 to recent files;\
5258 if STYLE is prefixed with 'posix-', STYLE\n\
5259 takes effect only outside the POSIX locale\n\
5262 -t sort by modification time, newest first\n\
5263 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
5266 -u with -lt: sort by, and show, access time;\n\
5267 with -l: show access time and sort by name;\n\
5268 otherwise: sort by access time, newest first\n\
5269 -U do not sort; list entries in directory order\n\
5270 -v natural sort of (version) numbers within text\n\
5273 -w, --width=COLS set output width to COLS. 0 means no limit\n\
5274 -x list entries by lines instead of by columns\n\
5275 -X sort alphabetically by entry extension\n\
5276 -Z, --context print any security context of each file\n\
5277 -1 list one file per line. Avoid '\\n' with -q or -b\
5280 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
5281 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
5285 Using color to distinguish file types is disabled both by default and\n\
5286 with --color=never. With --color=auto, ls emits color codes only when\n\
5287 standard output is connected to a terminal. The LS_COLORS environment\n\
5288 variable can change the settings. Use the dircolors command to set it.\n\
5294 1 if minor problems (e.g., cannot access subdirectory),\n\
5295 2 if serious trouble (e.g., cannot access command-line argument).\n\
5297 emit_ancillary_info (PROGRAM_NAME
);