all: update gnulib submodule to latest
[coreutils.git] / src / ls.c
blob745c65f7b3df458f6dccb32a28cdd7d1cd35aa0b
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.
27 If ls_mode is LS_LS,
28 the output format depends on whether the output
29 device is a terminal.
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>. */
38 #include <config.h>
39 #include <sys/types.h>
41 #include <termios.h>
42 #if HAVE_STROPTS_H
43 # include <stropts.h>
44 #endif
45 #include <sys/ioctl.h>
47 #ifdef WINSIZE_IN_PTEM
48 # include <sys/stream.h>
49 # include <sys/ptem.h>
50 #endif
52 #include <stdio.h>
53 #include <assert.h>
54 #include <setjmp.h>
55 #include <pwd.h>
56 #include <getopt.h>
57 #include <signal.h>
58 #include <selinux/selinux.h>
59 #include <wchar.h>
61 #if HAVE_LANGINFO_CODESET
62 # include <langinfo.h>
63 #endif
65 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
66 present. */
67 #ifndef SA_NOCLDSTOP
68 # define SA_NOCLDSTOP 0
69 # define sigprocmask(How, Set, Oset) /* empty */
70 # define sigset_t int
71 # if ! HAVE_SIGINTERRUPT
72 # define siginterrupt(sig, flag) /* empty */
73 # endif
74 #endif
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. */
80 #ifndef SA_RESTART
81 # define SA_RESTART 0
82 #endif
84 #include "system.h"
85 #include <fnmatch.h>
87 #include "acl.h"
88 #include "argmatch.h"
89 #include "dev-ino.h"
90 #include "die.h"
91 #include "error.h"
92 #include "filenamecat.h"
93 #include "hard-locale.h"
94 #include "hash.h"
95 #include "human.h"
96 #include "filemode.h"
97 #include "filevercmp.h"
98 #include "idcache.h"
99 #include "ls.h"
100 #include "mbswidth.h"
101 #include "mpsort.h"
102 #include "obstack.h"
103 #include "quote.h"
104 #include "smack.h"
105 #include "stat-size.h"
106 #include "stat-time.h"
107 #include "strftime.h"
108 #include "xdectoint.h"
109 #include "xstrtol.h"
110 #include "areadlink.h"
111 #include "mbsalign.h"
112 #include "dircolors.h"
113 #include "xgethostname.h"
114 #include "c-ctype.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>. */
120 #ifdef HAVE_CAP
121 # include <sys/capability.h>
122 #endif
124 #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \
125 : (ls_mode == LS_MULTI_COL \
126 ? "dir" : "vdir"))
128 #define AUTHORS \
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
151 #endif
153 #if READDIR_LIES_ABOUT_MOUNTPOINT_D_INO
154 # define RELIABLE_D_INO(dp) NOT_AN_INODE_NUMBER
155 #else
156 # define RELIABLE_D_INO(dp) D_INO (dp)
157 #endif
159 #if ! HAVE_STRUCT_STAT_ST_AUTHOR
160 # define st_author st_uid
161 #endif
163 enum filetype
165 unknown,
166 fifo,
167 chardev,
168 directory,
169 blockdev,
170 normal,
171 symbolic_link,
172 sock,
173 whiteout,
174 arg_directory
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 \
191 enum acl_type
193 ACL_T_NONE,
194 ACL_T_LSM_CONTEXT_ONLY,
195 ACL_T_YES
198 struct fileinfo
200 /* The file name. */
201 char *name;
203 /* For symbolic link, name of the file linked to, otherwise zero. */
204 char *linkname;
206 /* For terminal hyperlinks. */
207 char *absolute_name;
209 struct stat stat;
211 enum filetype filetype;
213 /* For symbolic link and long listing, st_mode of file linked to, otherwise
214 zero. */
215 mode_t linkmode;
217 /* security context. */
218 char *scontext;
220 bool stat_ok;
222 /* For symbolic link and color printing, true if linked-to file
223 exists, otherwise false. */
224 bool linkok;
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. */
231 bool has_capability;
233 /* Whether file name needs quoting. tri-state with -1 == unknown. */
234 int quoted;
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
241 type. */
243 struct bin_str
245 size_t len; /* Number of bytes */
246 const char *string; /* Pointer to the same */
249 #if ! HAVE_TCGETPGRP
250 # define tcgetpgrp(Fd) 0
251 #endif
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,
262 bool *pad);
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,
286 size_t start_col);
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,
293 bool symlink_target,
294 struct obstack *stack,
295 size_t start_col);
296 static void prep_non_filename_text (void);
297 static bool print_type_indicator (bool stat_ok, mode_t mode,
298 enum filetype type);
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. */
366 struct pending
368 char *name;
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. */
372 char *realname;
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
388 mode column. */
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;
407 /* Option flags */
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
416 this parameter. */
418 enum format
420 long_format, /* -l and other options that imply -l */
421 one_per_line, /* -1 */
422 many_per_line, /* -C */
423 horizontal, /* -x */
424 with_commas /* -m */
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. */
432 enum time_style
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,
447 locale_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()). */
455 enum time_type
457 time_mtime, /* default */
458 time_ctime, /* -c */
459 time_atime, /* -u */
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()). */
469 enum sort_type
471 sort_none = -1, /* -U */
472 sort_name, /* default */
473 sort_extension, /* -X */
474 sort_size, /* -S */
475 sort_version, /* -v */
476 sort_time, /* -t */
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
503 than as names. -n */
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. */
524 static bool dired;
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. */
533 enum 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;
568 enum when_type
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
577 DEREF_UNDEFINED = 1,
578 DEREF_NEVER,
579 DEREF_COMMAND_LINE_ARGUMENTS, /* -H */
580 DEREF_COMMAND_LINE_SYMLINK_TO_DIR, /* the default, in certain cases */
581 DEREF_ALWAYS /* -L */
584 enum indicator_no
586 C_LEFT, C_RIGHT, C_END, C_RESET, C_NORM, C_FILE, C_DIR, C_LINK,
587 C_FIFO, C_SOCK,
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,
590 C_CLR_TO_EOL
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 */
635 /* FIXME: comment */
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
642 colors. */
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
656 contents. -R */
658 static bool recursive;
660 /* True means when an argument is a directory name, display info
661 on it itself. -d */
663 static bool immediate_dirs;
665 /* True means that directories are grouped before files. */
667 static bool directories_first;
669 /* Which files to ignore. */
671 static enum
673 /* Ignore files whose names start with '.', and files specified by
674 --hide and --ignore. */
675 IGNORE_DEFAULT,
677 /* Ignore '.', '..', and files specified by --ignore. */
678 IGNORE_DOT_AND_DOTDOT,
680 /* Ignore only files specified by --ignore. */
681 IGNORE_MINIMAL
682 } ignore_mode;
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
691 const char *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
735 each file. */
737 static bool format_needs_stat;
739 /* Similar to 'format_needs_stat', but set if only the file type is
740 needed. */
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
748 timestamp format. */
750 enum { TIME_STAMP_LEN_MAXIMUM = MAX (1000, INT_STRLEN_BOUND (time_t)) };
752 /* strftime formats for non-recent and recent files, respectively, in
753 -l output. */
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. */
769 N_("%b %e %Y"),
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. */
782 N_("%b %e %H:%M")
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;
801 /* Exit statuses. */
802 enum
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. */
812 LS_FAILURE = 2
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. */
817 enum
819 AUTHOR_OPTION = CHAR_MAX + 1,
820 BLOCK_SIZE_OPTION,
821 COLOR_OPTION,
822 DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION,
823 FILE_TYPE_INDICATOR_OPTION,
824 FORMAT_OPTION,
825 FULL_TIME_OPTION,
826 GROUP_DIRECTORIES_FIRST_OPTION,
827 HIDE_OPTION,
828 HYPERLINK_OPTION,
829 INDICATOR_STYLE_OPTION,
830 QUOTING_STYLE_OPTION,
831 SHOW_CONTROL_CHARS_OPTION,
832 SI_OPTION,
833 SORT_OPTION,
834 TIME_OPTION,
835 TIME_STYLE_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},
885 {NULL, 0, NULL, 0}
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. */
936 struct column_info
938 bool valid_len;
939 size_t line_len;
940 size_t *col_arr;
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() \
972 do \
974 if (dired) \
975 DIRED_FPUTS_LITERAL (" ", stdout); \
977 while (0)
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) \
991 do \
993 if (dired) \
994 obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \
996 while (0)
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. */
1004 static void
1005 dev_ino_push (dev_t dev, ino_t ino)
1007 void *vdi;
1008 struct dev_ino *di;
1009 int dev_ino_size = sizeof *di;
1010 obstack_blank (&dev_ino_obstack, dev_ino_size);
1011 vdi = obstack_next_free (&dev_ino_obstack);
1012 di = vdi;
1013 di--;
1014 di->st_dev = dev;
1015 di->st_ino = ino;
1018 /* Pop a dev/ino struct off the global dev_ino_obstack
1019 and return that struct. */
1020 static struct dev_ino
1021 dev_ino_pop (void)
1023 void *vdi;
1024 struct dev_ino *di;
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);
1029 di = vdi;
1030 return *di;
1033 /* Note the use commented out below:
1034 #define ASSERT_MATCHING_DEV_INO(Name, Di) \
1035 do \
1037 struct stat sb; \
1038 assert (Name); \
1039 assert (0 <= stat (Name, &sb)); \
1040 assert (sb.st_dev == Di.st_dev); \
1041 assert (sb.st_ino == Di.st_ino); \
1043 while (0)
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. */
1049 static void
1050 dired_dump_obstack (const char *prefix, struct obstack *os)
1052 size_t n_pos;
1054 n_pos = obstack_object_size (os) / sizeof (dired_pos);
1055 if (n_pos > 0)
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]);
1061 putchar ('\n');
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)
1072 for (; *fmt; fmt++)
1073 if (fmt[0] == '%')
1074 switch (fmt[1])
1076 case 'b': return fmt;
1077 case '%': fmt++; break;
1079 return NULL;
1082 static char RFC3986[256];
1083 static void
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. */
1112 static bool
1113 abmon_init (char abmon[12][ABFORMAT_SIZE])
1115 #ifndef HAVE_NL_LANGINFO
1116 return false;
1117 #else
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, '%'))
1129 return false;
1130 size_t req = mbsalign (abbr, abmon[i], ABFORMAT_SIZE,
1131 &width, MBS_ALIGN_LEFT, 0);
1132 if (! (req < ABFORMAT_SIZE))
1133 return false;
1134 required_mon_width = MAX (required_mon_width, width);
1137 while (curr_max_width > required_mon_width);
1139 return true;
1140 #endif
1143 /* Initialize ABFORMAT and USE_ABFORMAT. */
1145 static void
1146 abformat_init (void)
1148 char const *pb[2];
1149 for (int recent = 0; recent < 2; recent++)
1150 pb[recent] = first_percent_b (long_time_format[recent]);
1151 if (! (pb[0] || pb[1]))
1152 return;
1154 char abmon[12][ABFORMAT_SIZE];
1155 if (! abmon_init (abmon))
1156 return;
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];
1164 int nbytes;
1166 if (! pb[recent])
1167 nbytes = snprintf (nfmt, ABFORMAT_SIZE, "%s", fmt);
1168 else
1170 if (! (pb[recent] - fmt <= MIN (ABFORMAT_SIZE, INT_MAX)))
1171 return;
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))
1178 return;
1182 use_abformat = true;
1185 static size_t
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;
1192 static bool
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;
1200 static void
1201 dev_ino_free (void *x)
1203 free (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. */
1210 static bool
1211 visit_dir (dev_t dev, ino_t ino)
1213 struct dev_ino *ent;
1214 struct dev_ino *ent_from_table;
1215 bool found_match;
1217 ent = xmalloc (sizeof *ent);
1218 ent->st_ino = ino;
1219 ent->st_dev = dev;
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. */
1227 xalloc_die ();
1230 found_match = (ent_from_table != ent);
1232 if (found_match)
1234 /* ent was not inserted, so free it. */
1235 free (ent);
1238 return found_match;
1241 static void
1242 free_pending_ent (struct pending *p)
1244 free (p->name);
1245 free (p->realname);
1246 free (p);
1249 static bool
1250 is_colored (enum indicator_no type)
1252 size_t len = color_indicator[type].len;
1253 char const *s = color_indicator[type].string;
1254 return ! (len == 0
1255 || (len == 1 && STRNCMP_LIT (s, "0") == 0)
1256 || (len == 2 && STRNCMP_LIT (s, "00") == 0));
1259 static void
1260 restore_default_color (void)
1262 put_indicator (&color_indicator[C_LEFT]);
1263 put_indicator (&color_indicator[C_RIGHT]);
1266 static void
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. */
1279 static void
1280 sighandler (int sig)
1282 if (! SA_NOCLDSTOP)
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. */
1290 static void
1291 stophandler (int sig)
1293 if (! SA_NOCLDSTOP)
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. */
1305 static void
1306 process_signals (void)
1308 while (interrupt_signal || stop_signal_count)
1310 int sig;
1311 int stops;
1312 sigset_t oldset;
1314 if (used_color)
1315 restore_default_color ();
1316 fflush (stdout);
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. */
1328 if (stops)
1330 stop_signal_count = stops - 1;
1331 sig = SIGSTOP;
1333 else
1334 signal (sig, SIG_DFL);
1336 /* Exit or suspend the program. */
1337 raise (sig);
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. */
1348 static void
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. */
1355 SIGTSTP,
1357 /* The usual suspects. */
1358 SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM,
1359 #ifdef SIGPOLL
1360 SIGPOLL,
1361 #endif
1362 #ifdef SIGPROF
1363 SIGPROF,
1364 #endif
1365 #ifdef SIGVTALRM
1366 SIGVTALRM,
1367 #endif
1368 #ifdef SIGXCPU
1369 SIGXCPU,
1370 #endif
1371 #ifdef SIGXFSZ
1372 SIGXFSZ,
1373 #endif
1375 enum { nsigs = ARRAY_CARDINALITY (sig) };
1377 #if ! SA_NOCLDSTOP
1378 static bool caught_sig[nsigs];
1379 #endif
1381 int j;
1383 if (init)
1385 #if SA_NOCLDSTOP
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);
1405 #else
1406 for (j = 0; j < nsigs; j++)
1408 caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN);
1409 if (caught_sig[j])
1411 signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler);
1412 siginterrupt (sig[j], 0);
1415 #endif
1417 else /* restore. */
1419 #if SA_NOCLDSTOP
1420 for (j = 0; j < nsigs; j++)
1421 if (sigismember (&caught_signals, sig[j]))
1422 signal (sig[j], SIG_DFL);
1423 #else
1424 for (j = 0; j < nsigs; j++)
1425 if (caught_sig[j])
1426 signal (sig[j], SIG_DFL);
1427 #endif
1431 static inline void
1432 signal_init (void)
1434 signal_setup (true);
1437 static inline void
1438 signal_restore (void)
1440 signal_setup (false);
1444 main (int argc, char **argv)
1446 int i;
1447 struct pending *thispend;
1448 int n_files;
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)
1472 parse_ls_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)
1489 ? DEREF_NEVER
1490 : DEREF_COMMAND_LINE_SYMLINK_TO_DIR);
1492 /* When using -R, initialize a data structure we'll use to
1493 detect any directory cycles. */
1494 if (recursive)
1496 active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL,
1497 dev_ino_hash,
1498 dev_ino_compare,
1499 dev_ino_free);
1500 if (active_dir_set == NULL)
1501 xalloc_die ();
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
1510 || print_scontext
1511 || print_block_size;
1512 format_needs_type = (! format_needs_stat
1513 && (recursive
1514 || print_with_color
1515 || indicator_style != none
1516 || directories_first));
1518 if (dired)
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. */
1531 if (! hostname)
1532 hostname = "";
1535 cwd_n_alloc = 100;
1536 cwd_file = xnmalloc (cwd_n_alloc, sizeof *cwd_file);
1537 cwd_n_used = 0;
1539 clear_files ();
1541 n_files = argc - i;
1543 if (n_files <= 0)
1545 if (immediate_dirs)
1546 gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, "");
1547 else
1548 queue_directory (".", NULL, true);
1550 else
1552 gobble_file (argv[i++], unknown, NOT_AN_INODE_NUMBER, true, "");
1553 while (i < argc);
1555 if (cwd_n_used)
1557 sort_files ();
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. */
1567 if (cwd_n_used)
1569 print_current_files ();
1570 if (pending_dirs)
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;
1581 if (LOOP_DETECT)
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); */
1592 assert (found);
1593 dev_ino_free (found);
1594 free_pending_ent (thispend);
1595 continue;
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)
1608 int j;
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 ();
1618 fflush (stdout);
1620 signal_restore ();
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--)
1627 raise (SIGSTOP);
1628 j = interrupt_signal;
1629 if (j)
1630 raise (j);
1633 if (dired)
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)]);
1642 if (LOOP_DETECT)
1644 assert (hash_get_n_entries (active_dir_set) == 0);
1645 hash_free (active_dir_set);
1648 return exit_status;
1651 /* Set the line length to the value given by SPEC. Return true if
1652 successful. 0 means no limit on line length. */
1654 static bool
1655 set_line_length (char const *spec)
1657 uintmax_t val;
1659 /* Treat too-large values as if they were SIZE_MAX, which is
1660 effectively infinity. */
1661 switch (xstrtoumax (spec, NULL, 0, &val, ""))
1663 case LONGINT_OK:
1664 line_length = MIN (val, SIZE_MAX);
1665 return true;
1667 case LONGINT_OVERFLOW:
1668 line_length = SIZE_MAX;
1669 return true;
1671 default:
1672 return false;
1676 /* Set all the option flags according to the switches specified.
1677 Return the index of the first non-option argument. */
1679 static int
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 */
1691 switch (ls_mode)
1693 case LS_MULTI_COL:
1694 /* This is for the 'dir' program. */
1695 format = many_per_line;
1696 set_quoting_style (NULL, escape_quoting_style);
1697 break;
1699 case LS_LONG_FORMAT:
1700 /* This is for the 'vdir' program. */
1701 format = long_format;
1702 set_quoting_style (NULL, escape_quoting_style);
1703 break;
1705 case LS_LS:
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;
1714 else
1716 format = one_per_line;
1717 qmark_funny_chars = false;
1719 break;
1721 default:
1722 abort ();
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;
1733 recursive = false;
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 ();
1742 line_length = 80;
1744 char const *p = getenv ("COLUMNS");
1745 if (p && *p && ! set_line_length (p))
1746 error (0, 0,
1747 _("ignoring invalid width in environment variable COLUMNS: %s"),
1748 quote (p));
1751 #ifdef TIOCGWINSZ
1753 struct winsize ws;
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;
1759 #endif
1762 char const *p = getenv ("TABSIZE");
1763 tabsize = 8;
1764 if (p)
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;
1772 else
1774 error (0, 0,
1775 _("ignoring invalid tab size in environment variable TABSIZE: %s"),
1776 quote (p));
1781 while (true)
1783 int oi = -1;
1784 int c = getopt_long (argc, argv,
1785 "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1",
1786 long_options, &oi);
1787 if (c == -1)
1788 break;
1790 switch (c)
1792 case 'a':
1793 ignore_mode = IGNORE_MINIMAL;
1794 break;
1796 case 'b':
1797 set_quoting_style (NULL, escape_quoting_style);
1798 break;
1800 case 'c':
1801 time_type = time_ctime;
1802 break;
1804 case 'd':
1805 immediate_dirs = true;
1806 break;
1808 case 'f':
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;
1813 /* disable -l */
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 */
1819 break;
1821 case FILE_TYPE_INDICATOR_OPTION: /* --file-type */
1822 indicator_style = file_type;
1823 break;
1825 case 'g':
1826 format = long_format;
1827 print_owner = false;
1828 break;
1830 case 'h':
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;
1834 break;
1836 case 'i':
1837 print_inode = true;
1838 break;
1840 case 'k':
1841 kibibytes_specified = true;
1842 break;
1844 case 'l':
1845 format = long_format;
1846 break;
1848 case 'm':
1849 format = with_commas;
1850 break;
1852 case 'n':
1853 numeric_ids = true;
1854 format = long_format;
1855 break;
1857 case 'o': /* Just like -l, but don't display group info. */
1858 format = long_format;
1859 print_group = false;
1860 break;
1862 case 'p':
1863 indicator_style = slash;
1864 break;
1866 case 'q':
1867 qmark_funny_chars = true;
1868 break;
1870 case 'r':
1871 sort_reverse = true;
1872 break;
1874 case 's':
1875 print_block_size = true;
1876 break;
1878 case 't':
1879 sort_type = sort_time;
1880 sort_type_specified = true;
1881 break;
1883 case 'u':
1884 time_type = time_atime;
1885 break;
1887 case 'v':
1888 sort_type = sort_version;
1889 sort_type_specified = true;
1890 break;
1892 case 'w':
1893 if (! set_line_length (optarg))
1894 die (LS_FAILURE, 0, "%s: %s", _("invalid line width"),
1895 quote (optarg));
1896 break;
1898 case 'x':
1899 format = horizontal;
1900 break;
1902 case 'A':
1903 if (ignore_mode == IGNORE_DEFAULT)
1904 ignore_mode = IGNORE_DOT_AND_DOTDOT;
1905 break;
1907 case 'B':
1908 add_ignore_pattern ("*~");
1909 add_ignore_pattern (".*~");
1910 break;
1912 case 'C':
1913 format = many_per_line;
1914 break;
1916 case 'D':
1917 dired = true;
1918 break;
1920 case 'F':
1921 indicator_style = classify;
1922 break;
1924 case 'G': /* inhibit display of group info */
1925 print_group = false;
1926 break;
1928 case 'H':
1929 dereference = DEREF_COMMAND_LINE_ARGUMENTS;
1930 break;
1932 case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION:
1933 dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR;
1934 break;
1936 case 'I':
1937 add_ignore_pattern (optarg);
1938 break;
1940 case 'L':
1941 dereference = DEREF_ALWAYS;
1942 break;
1944 case 'N':
1945 set_quoting_style (NULL, literal_quoting_style);
1946 break;
1948 case 'Q':
1949 set_quoting_style (NULL, c_quoting_style);
1950 break;
1952 case 'R':
1953 recursive = true;
1954 break;
1956 case 'S':
1957 sort_type = sort_size;
1958 sort_type_specified = true;
1959 break;
1961 case 'T':
1962 tabsize = xnumtoumax (optarg, 0, 0, SIZE_MAX, "",
1963 _("invalid tab size"), LS_FAILURE);
1964 break;
1966 case 'U':
1967 sort_type = sort_none;
1968 sort_type_specified = true;
1969 break;
1971 case 'X':
1972 sort_type = sort_extension;
1973 sort_type_specified = true;
1974 break;
1976 case '1':
1977 /* -1 has no effect after -l. */
1978 if (format != long_format)
1979 format = one_per_line;
1980 break;
1982 case AUTHOR_OPTION:
1983 print_author = true;
1984 break;
1986 case HIDE_OPTION:
1988 struct ignore_pattern *hide = xmalloc (sizeof *hide);
1989 hide->pattern = optarg;
1990 hide->next = hide_patterns;
1991 hide_patterns = hide;
1993 break;
1995 case SORT_OPTION:
1996 sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types);
1997 sort_type_specified = true;
1998 break;
2000 case GROUP_DIRECTORIES_FIRST_OPTION:
2001 directories_first = true;
2002 break;
2004 case TIME_OPTION:
2005 time_type = XARGMATCH ("--time", optarg, time_args, time_types);
2006 break;
2008 case FORMAT_OPTION:
2009 format = XARGMATCH ("--format", optarg, format_args, format_types);
2010 break;
2012 case FULL_TIME_OPTION:
2013 format = long_format;
2014 time_style_option = bad_cast ("full-iso");
2015 break;
2017 case COLOR_OPTION:
2019 int i;
2020 if (optarg)
2021 i = XARGMATCH ("--color", optarg, when_args, when_types);
2022 else
2023 /* Using --color with no argument is equivalent to using
2024 --color=always. */
2025 i = when_always;
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. */
2036 tabsize = 0;
2038 break;
2041 case HYPERLINK_OPTION:
2043 int i;
2044 if (optarg)
2045 i = XARGMATCH ("--hyperlink", optarg, when_args, when_types);
2046 else
2047 /* Using --hyperlink with no argument is equivalent to using
2048 --hyperlink=always. */
2049 i = when_always;
2051 print_hyperlink = (i == when_always
2052 || (i == when_if_tty
2053 && isatty (STDOUT_FILENO)));
2054 break;
2057 case INDICATOR_STYLE_OPTION:
2058 indicator_style = XARGMATCH ("--indicator-style", optarg,
2059 indicator_style_args,
2060 indicator_style_types);
2061 break;
2063 case QUOTING_STYLE_OPTION:
2064 set_quoting_style (NULL,
2065 XARGMATCH ("--quoting-style", optarg,
2066 quoting_style_args,
2067 quoting_style_vals));
2068 break;
2070 case TIME_STYLE_OPTION:
2071 time_style_option = optarg;
2072 break;
2074 case SHOW_CONTROL_CHARS_OPTION:
2075 qmark_funny_chars = false;
2076 break;
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;
2087 break;
2089 case SI_OPTION:
2090 file_human_output_opts = human_output_opts =
2091 human_autoscale | human_SI;
2092 file_output_block_size = output_block_size = 1;
2093 break;
2095 case 'Z':
2096 print_scontext = true;
2097 break;
2099 case_GETOPT_HELP_CHAR;
2101 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
2103 default:
2104 usage (LS_FAILURE);
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)
2143 char const *p;
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))
2155 dired = false;
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
2163 by atime. */
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-";
2176 if (! style)
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))
2183 return optind;
2184 style += sizeof posix_prefix - 1;
2187 if (*style == '+')
2189 char *p0 = style + 1;
2190 char *p1 = strchr (p0, '\n');
2191 if (! p1)
2192 p1 = p0;
2193 else
2195 if (strchr (p1 + 1, '\n'))
2196 die (LS_FAILURE, 0, _("invalid time style format %s"),
2197 quote (p0));
2198 *p1++ = '\0';
2200 long_time_format[0] = p0;
2201 long_time_format[1] = p1;
2203 else
2205 ptrdiff_t res = argmatch (style, time_style_args,
2206 (char const *) time_style_types,
2207 sizeof (*time_style_types));
2208 if (res < 0)
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
2219 are distinct. */
2220 fputs (_("Valid arguments are:\n"), stderr);
2221 char const *const *p = time_style_args;
2222 while (*p)
2223 fprintf (stderr, " - [posix-]%s\n", *p++);
2224 fputs (_(" - +FORMAT (e.g., +%H:%M) for a 'date'-style"
2225 " format\n"), stderr);
2226 usage (LS_FAILURE);
2228 switch (res)
2230 case full_iso_time_style:
2231 long_time_format[0] = long_time_format[1] =
2232 "%Y-%m-%d %H:%M:%S.%N %z";
2233 break;
2235 case long_iso_time_style:
2236 long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M";
2237 break;
2239 case iso_time_style:
2240 long_time_format[0] = "%Y-%m-%d ";
2241 long_time_format[1] = "%m-%d %H:%M";
2242 break;
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);
2254 abformat_init ();
2257 return optind;
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
2264 true if successful.
2266 The resulting string is *not* null-terminated, but may contain
2267 embedded nulls.
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. */
2273 static bool
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 */
2279 enum {
2280 ST_GND, ST_BACKSLASH, ST_OCTAL, ST_HEX, ST_CARET, ST_END, ST_ERROR
2281 } state;
2282 const char *p;
2283 char *q;
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. */
2289 num = 0;
2291 state = ST_GND; /* Start in ground state. */
2292 while (state < ST_END)
2294 switch (state)
2296 case ST_GND: /* Ground state (no escapes) */
2297 switch (*p)
2299 case ':':
2300 case '\0':
2301 state = ST_END; /* End of string */
2302 break;
2303 case '\\':
2304 state = ST_BACKSLASH; /* Backslash escape sequence */
2305 ++p;
2306 break;
2307 case '^':
2308 state = ST_CARET; /* Caret escape */
2309 ++p;
2310 break;
2311 case '=':
2312 if (equals_end)
2314 state = ST_END; /* End */
2315 break;
2317 FALLTHROUGH;
2318 default:
2319 *(q++) = *(p++);
2320 ++count;
2321 break;
2323 break;
2325 case ST_BACKSLASH: /* Backslash escaped character */
2326 switch (*p)
2328 case '0':
2329 case '1':
2330 case '2':
2331 case '3':
2332 case '4':
2333 case '5':
2334 case '6':
2335 case '7':
2336 state = ST_OCTAL; /* Octal sequence */
2337 num = *p - '0';
2338 break;
2339 case 'x':
2340 case 'X':
2341 state = ST_HEX; /* Hex sequence */
2342 num = 0;
2343 break;
2344 case 'a': /* Bell */
2345 num = '\a';
2346 break;
2347 case 'b': /* Backspace */
2348 num = '\b';
2349 break;
2350 case 'e': /* Escape */
2351 num = 27;
2352 break;
2353 case 'f': /* Form feed */
2354 num = '\f';
2355 break;
2356 case 'n': /* Newline */
2357 num = '\n';
2358 break;
2359 case 'r': /* Carriage return */
2360 num = '\r';
2361 break;
2362 case 't': /* Tab */
2363 num = '\t';
2364 break;
2365 case 'v': /* Vtab */
2366 num = '\v';
2367 break;
2368 case '?': /* Delete */
2369 num = 127;
2370 break;
2371 case '_': /* Space */
2372 num = ' ';
2373 break;
2374 case '\0': /* End of string */
2375 state = ST_ERROR; /* Error! */
2376 break;
2377 default: /* Escaped character like \ ^ : = */
2378 num = *p;
2379 break;
2381 if (state == ST_BACKSLASH)
2383 *(q++) = num;
2384 ++count;
2385 state = ST_GND;
2387 ++p;
2388 break;
2390 case ST_OCTAL: /* Octal sequence */
2391 if (*p < '0' || *p > '7')
2393 *(q++) = num;
2394 ++count;
2395 state = ST_GND;
2397 else
2398 num = (num << 3) + (*(p++) - '0');
2399 break;
2401 case ST_HEX: /* Hex sequence */
2402 switch (*p)
2404 case '0':
2405 case '1':
2406 case '2':
2407 case '3':
2408 case '4':
2409 case '5':
2410 case '6':
2411 case '7':
2412 case '8':
2413 case '9':
2414 num = (num << 4) + (*(p++) - '0');
2415 break;
2416 case 'a':
2417 case 'b':
2418 case 'c':
2419 case 'd':
2420 case 'e':
2421 case 'f':
2422 num = (num << 4) + (*(p++) - 'a') + 10;
2423 break;
2424 case 'A':
2425 case 'B':
2426 case 'C':
2427 case 'D':
2428 case 'E':
2429 case 'F':
2430 num = (num << 4) + (*(p++) - 'A') + 10;
2431 break;
2432 default:
2433 *(q++) = num;
2434 ++count;
2435 state = ST_GND;
2436 break;
2438 break;
2440 case ST_CARET: /* Caret escape */
2441 state = ST_GND; /* Should be the next state... */
2442 if (*p >= '@' && *p <= '~')
2444 *(q++) = *(p++) & 037;
2445 ++count;
2447 else if (*p == '?')
2449 *(q++) = 127;
2450 ++count;
2452 else
2453 state = ST_ERROR;
2454 break;
2456 default:
2457 abort ();
2461 *dest = q;
2462 *src = p;
2463 *output_count = count;
2465 return state != ST_ERROR;
2468 enum parse_state
2470 PS_START = 1,
2471 PS_2,
2472 PS_3,
2473 PS_4,
2474 PS_DONE,
2475 PS_FAIL
2479 /* Check if the content of TERM is a valid name in dircolors. */
2481 static bool
2482 known_term_type (void)
2484 char const *term = getenv ("TERM");
2485 if (! term || ! *term)
2486 return false;
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)
2494 return true;
2496 line += strlen (line) + 1;
2499 return false;
2502 static void
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;
2520 return;
2523 ext = NULL;
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
2529 advance. */
2530 buf = color_buf = xstrdup (p);
2532 enum parse_state state = PS_START;
2533 while (true)
2535 switch (state)
2537 case PS_START: /* First label character */
2538 switch (*p)
2540 case ':':
2541 ++p;
2542 break;
2544 case '*':
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;
2554 ++p;
2555 ext->ext.string = buf;
2557 state = (get_funky_string (&buf, &p, true, &ext->ext.len)
2558 ? PS_4 : PS_FAIL);
2559 break;
2561 case '\0':
2562 state = PS_DONE; /* Done! */
2563 goto done;
2565 default: /* Assume it is file type label */
2566 label[0] = *(p++);
2567 state = PS_2;
2568 break;
2570 break;
2572 case PS_2: /* Second label character */
2573 if (*p)
2575 label[1] = *(p++);
2576 state = PS_3;
2578 else
2579 state = PS_FAIL; /* Error */
2580 break;
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);
2594 break;
2597 if (state == PS_FAIL)
2598 error (0, 0, _("unrecognized prefix: %s"), quote (label));
2600 break;
2602 case PS_4: /* Equal sign after *.ext */
2603 if (*(p++) == '=')
2605 ext->seq.string = buf;
2606 state = (get_funky_string (&buf, &p, false, &ext->seq.len)
2607 ? PS_START : PS_FAIL);
2609 else
2610 state = PS_FAIL;
2611 break;
2613 case PS_FAIL:
2614 goto done;
2616 default:
2617 abort ();
2620 done:
2622 if (state == PS_FAIL)
2624 struct color_ext_type *e;
2625 struct color_ext_type *e2;
2627 error (0, 0,
2628 _("unparsable value for LS_COLORS environment variable"));
2629 free (color_buf);
2630 for (e = color_ext_list; e != NULL; /* empty */)
2632 e2 = e;
2633 e = e->next;
2634 free (e2);
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. */
2647 static void
2648 getenv_quoting_style (void)
2650 char const *q_style = getenv ("QUOTING_STYLE");
2651 if (q_style)
2653 int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals);
2654 if (0 <= i)
2655 set_quoting_style (NULL, quoting_style_vals[i]);
2656 else
2657 error (0, 0,
2658 _("ignoring invalid value of environment variable QUOTING_STYLE: %s"),
2659 quote (q_style));
2663 /* Set the exit status to report a failure. If SERIOUS, it is a
2664 serious failure; otherwise, it is merely a minor problem. */
2666 static void
2667 set_exit_status (bool serious)
2669 if (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. */
2679 static void
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. */
2696 static void
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;
2704 pending_dirs = new;
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. */
2712 static void
2713 print_dir (char const *name, char const *realname, bool command_line_arg)
2715 DIR *dirp;
2716 struct dirent *next;
2717 uintmax_t total_blocks = 0;
2718 static bool first = true;
2720 errno = 0;
2721 dirp = opendir (name);
2722 if (!dirp)
2724 file_failure (command_line_arg, _("cannot open directory %s"), name);
2725 return;
2728 if (LOOP_DETECT)
2730 struct stat dir_stat;
2731 int fd = dirfd (dirp);
2733 /* If dirfd failed, endure the overhead of using stat. */
2734 if ((0 <= fd
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);
2740 closedir (dirp);
2741 return;
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"),
2749 quotef (name));
2750 closedir (dirp);
2751 set_exit_status (true);
2752 return;
2755 dev_ino_push (dir_stat.st_dev, dir_stat.st_ino);
2758 clear_files ();
2760 if (recursive || print_dir_name)
2762 if (!first)
2763 DIRED_PUTCHAR ('\n');
2764 first = false;
2765 DIRED_INDENT ();
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'
2784 table. */
2786 while (1)
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. */
2790 errno = 0;
2791 next = readdir (dirp);
2792 if (next)
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;
2808 # ifdef DT_WHT
2809 case DT_WHT: type = whiteout; break;
2810 # endif
2812 #endif
2813 total_blocks += gobble_file (next->d_name, type,
2814 RELIABLE_D_INO (next),
2815 false, name);
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. */
2827 sort_files ();
2828 print_current_files ();
2829 clear_files ();
2833 else if (errno != 0)
2835 file_failure (command_line_arg, _("reading directory %s"), name);
2836 if (errno != EOVERFLOW)
2837 break;
2839 else
2840 break;
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. */
2845 process_signals ();
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. */
2855 sort_files ();
2857 /* If any member files are subdirectories, perhaps they should have their
2858 contents listed rather than being mentioned here as files. */
2860 if (recursive)
2861 extract_dirs_from_files (name, false);
2863 if (format == long_format || print_block_size)
2865 const char *p;
2866 char buf[LONGEST_HUMAN_READABLE + 1];
2868 DIRED_INDENT ();
2869 p = _("total");
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');
2878 if (cwd_n_used)
2879 print_current_files ();
2882 /* Add 'pattern' to the list of patterns for which files that match are
2883 not listed. */
2885 static void
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. */
2899 static bool
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)
2905 return true;
2906 return false;
2909 /* Return true if FILE should be ignored. */
2911 static bool
2912 file_ignored (char const *name)
2914 return ((ignore_mode != IGNORE_MINIMAL
2915 && name[0] == '.'
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. */
2926 static uintmax_t
2927 unsigned_file_size (off_t size)
2929 return size + (size < 0) * ((uintmax_t) OFF_T_MAX - OFF_T_MIN + 1);
2932 #ifdef HAVE_CAP
2933 /* Return true if NAME has a capability (see linux/capability.h) */
2934 static bool
2935 has_capability (char const *name)
2937 char *result;
2938 bool has_cap;
2940 cap_t cap_d = cap_get_file (name);
2941 if (cap_d == NULL)
2942 return false;
2944 result = cap_to_text (cap_d, NULL);
2945 cap_free (cap_d);
2946 if (!result)
2947 return false;
2949 /* check if human-readable capability string is empty */
2950 has_cap = !!*result;
2952 cap_free (result);
2953 return has_cap;
2955 #else
2956 static bool
2957 has_capability (char const *name _GL_UNUSED)
2959 errno = ENOTSUP;
2960 return false;
2962 #endif
2964 /* Enter and remove entries in the table 'cwd_file'. */
2966 static void
2967 free_ent (struct fileinfo *f)
2969 free (f->name);
2970 free (f->linkname);
2971 free (f->absolute_name);
2972 if (f->scontext != UNKNOWN_SECURITY_CONTEXT)
2974 if (is_smack_enabled ())
2975 free (f->scontext);
2976 else
2977 freecon (f->scontext);
2981 /* Empty the table of files. */
2982 static void
2983 clear_files (void)
2985 for (size_t i = 0; i < cwd_n_used; i++)
2987 struct fileinfo *f = sorted_file[i];
2988 free_ent (f);
2991 cwd_n_used = 0;
2992 cwd_some_quoted = false;
2993 any_has_acl = false;
2994 inode_number_width = 0;
2995 block_size_width = 0;
2996 nlink_width = 0;
2997 owner_width = 0;
2998 group_width = 0;
2999 author_width = 0;
3000 scontext_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. */
3008 static bool
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. */
3017 static int
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)
3026 errno = ENOTSUP;
3027 return -1;
3029 int r = 0;
3030 #ifdef HAVE_SMACK
3031 if (is_smack_enabled ())
3032 r = smack_new_label_from_path (file, "security.SMACK64", deref,
3033 &f->scontext);
3034 else
3035 #endif
3036 r = (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;
3041 return r;
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. */
3047 static int
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)
3056 errno = ENOTSUP;
3057 return 0;
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". */
3062 errno = 0;
3063 int n = file_has_acl (file, &f->stat);
3064 if (n <= 0 && errno_unsupported (errno))
3065 unsupported_device = f->stat.st_dev;
3066 return n;
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. */
3072 static bool
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)
3081 errno = ENOTSUP;
3082 return 0;
3085 bool b = has_capability (file);
3086 if ( !b && errno_unsupported (errno))
3087 unsupported_device = f->stat.st_dev;
3088 return b;
3091 static bool
3092 needs_quoting (char const* name)
3094 char test[2];
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. */
3103 static uintmax_t
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;
3108 struct fileinfo *f;
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);
3117 cwd_n_alloc *= 2;
3120 f = &cwd_file[cwd_n_used];
3121 memset (f, '\0', sizeof *f);
3122 f->stat.st_ino = inode;
3123 f->filetype = type;
3125 f->quoted = -1;
3126 if ((! cwd_some_quoted) && align_variable_outer_quotes)
3128 /* Determine if any quoted for padding purposes. */
3129 f->quoted = needs_quoting (name);
3130 if (f->quoted)
3131 cwd_some_quoted = 1;
3134 if (command_line_arg
3135 || print_hyperlink
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)))
3170 )))))
3173 /* Absolute name of this file. */
3174 char *full_name;
3175 bool do_deref;
3176 int err;
3178 if (name[0] == '/' || dirname[0] == 0)
3179 full_name = (char *) name;
3180 else
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,
3189 CAN_MISSING);
3190 if (! f->absolute_name)
3191 file_failure (command_line_arg,
3192 _("error canonicalizing %s"), full_name);
3195 switch (dereference)
3197 case DEREF_ALWAYS:
3198 err = stat (full_name, &f->stat);
3199 do_deref = true;
3200 break;
3202 case DEREF_COMMAND_LINE_ARGUMENTS:
3203 case DEREF_COMMAND_LINE_SYMLINK_TO_DIR:
3204 if (command_line_arg)
3206 bool need_lstat;
3207 err = stat (full_name, &f->stat);
3208 do_deref = true;
3210 if (dereference == DEREF_COMMAND_LINE_ARGUMENTS)
3211 break;
3213 need_lstat = (err < 0
3214 ? errno == ENOENT
3215 : ! S_ISDIR (f->stat.st_mode));
3216 if (!need_lstat)
3217 break;
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. */
3224 FALLTHROUGH;
3226 default: /* DEREF_NEVER */
3227 err = lstat (full_name, &f->stat);
3228 do_deref = false;
3229 break;
3232 if (err != 0)
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)
3240 return 0;
3242 f->name = xstrdup (name);
3243 cwd_n_used++;
3245 return 0;
3248 f->stat_ok = true;
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);
3262 if (err == 0)
3264 if (is_smack_enabled ())
3265 have_scontext = ! STREQ ("_", f->scontext);
3266 else
3267 have_scontext = ! STREQ ("unlabeled", f->scontext);
3269 else
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)
3278 err = 0;
3281 if (err == 0 && format == long_format)
3283 int n = file_has_acl_cache (full_name, f);
3284 err = (n < 0);
3285 have_acl = (0 < n);
3288 f->acl_type = (!have_scontext && !have_acl
3289 ? ACL_T_NONE
3290 : (have_scontext && !have_acl
3291 ? ACL_T_LSM_CONTEXT_ONLY
3292 : ACL_T_YES));
3293 any_has_acl |= f->acl_type != ACL_T_NONE;
3295 if (err)
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))
3310 f->quoted = -1;
3312 /* Avoid following symbolic links when possible, ie, when
3313 they won't be traced and when no indicator is needed. */
3314 if (linkname
3315 && (file_type <= indicator_style || check_symlink_color)
3316 && stat (linkname, &linkstats) == 0)
3318 f->linkok = true;
3320 /* Symbolic links to directories that are mentioned on the
3321 command line are automatically traced if not being
3322 listed as files. */
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;
3331 free (linkname);
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;
3340 else
3341 f->filetype = directory;
3343 else
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)
3359 if (print_owner)
3361 int len = format_user_width (f->stat.st_uid);
3362 if (owner_width < len)
3363 owner_width = len;
3366 if (print_group)
3368 int len = format_group_width (f->stat.st_gid);
3369 if (group_width < len)
3370 group_width = len;
3373 if (print_author)
3375 int len = format_user_width (f->stat.st_author);
3376 if (author_width < len)
3377 author_width = len;
3381 if (print_scontext)
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;
3408 else
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;
3422 if (print_inode)
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);
3431 cwd_n_used++;
3433 return blocks;
3436 /* Return true if F refers to a directory. */
3437 static bool
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. */
3447 static void
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"),
3453 filename);
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. */
3461 static char *
3462 make_link_name (char const *name, char const *linkname)
3464 if (!linkname)
3465 return NULL;
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]))
3482 ++prefix_len;
3484 stpcpy (stpncpy (p, name, prefix_len), linkname);
3485 return p;
3488 /* Return true if the last component of NAME is '.' or '..'
3489 This is so we don't try to recurse on '././././. ...' */
3491 static bool
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. */
3506 static void
3507 extract_dirs_from_files (char const *dirname, bool command_line_arg)
3509 size_t i;
3510 size_t j;
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
3522 order. */
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);
3533 else
3535 char *name = file_name_concat (dirname, f->name, NULL);
3536 queue_directory (name, f->linkname, command_line_arg);
3537 free (name);
3539 if (f->filetype == arg_directory)
3540 free_ent (f);
3544 /* Now delete the directories from the table, compacting all the remaining
3545 entries. */
3547 for (i = 0, j = 0; i < cwd_n_used; i++)
3549 struct fileinfo *f = sorted_file[i];
3550 sorted_file[j] = f;
3551 j += (f->filetype != arg_directory);
3553 cwd_n_used = j;
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;
3561 static int
3562 xstrcoll (char const *a, char const *b)
3564 int diff;
3565 errno = 0;
3566 diff = strcoll (a, b);
3567 if (errno)
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);
3574 return diff;
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) \
3586 do \
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 */ \
3595 while (0)
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); }
3627 static inline int
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);
3636 static inline int
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);
3645 static inline int
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);
3654 static inline int
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);
3662 static inline int
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. */
3672 static inline int
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. */
3698 static inline int
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
3722 sort_type enums! */
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 }, \
3729 }, \
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. */
3753 { NULL, NULL },
3754 { NULL, NULL },
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. */
3777 static void
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. */
3786 static void
3787 sort_files (void)
3789 bool use_strcmp;
3791 if (sorted_file_alloc < cwd_n_used + cwd_n_used / 2)
3793 free (sorted_file);
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)
3801 return;
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 */
3810 else
3812 use_strcmp = true;
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. */
3826 static void
3827 print_current_files (void)
3829 size_t i;
3831 switch (format)
3833 case one_per_line:
3834 for (i = 0; i < cwd_n_used; i++)
3836 print_file_name_and_frills (sorted_file[i], 0);
3837 putchar ('\n');
3839 break;
3841 case many_per_line:
3842 if (! line_length)
3843 print_with_separator (' ');
3844 else
3845 print_many_per_line ();
3846 break;
3848 case horizontal:
3849 if (! line_length)
3850 print_with_separator (' ');
3851 else
3852 print_horizontal ();
3853 break;
3855 case with_commas:
3856 print_with_separator (',');
3857 break;
3859 case long_format:
3860 for (i = 0; i < cwd_n_used; i++)
3862 set_normal_color ();
3863 print_long_format (sorted_file[i]);
3864 DIRED_PUTCHAR ('\n');
3866 break;
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. */
3874 static size_t
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. */
3887 static int
3888 long_time_expected_width (void)
3890 static int width = -1;
3892 if (width < 0)
3894 time_t epoch = 0;
3895 struct tm tm;
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,
3908 &tm, localtz, 0);
3909 if (len != 0)
3910 width = mbsnwidth (buf, len, 0);
3913 if (width < 0)
3914 width = 0;
3917 return width;
3920 /* Print the user or group name NAME, with numeric id ID, using a
3921 print width of WIDTH columns. */
3923 static void
3924 format_user_or_group (char const *name, unsigned long int id, int width)
3926 size_t len;
3928 if (name)
3930 int width_gap = width - mbswidth (name, 0);
3931 int pad = MAX (0, width_gap);
3932 fputs (name, stdout);
3933 len = strlen (name) + pad;
3936 putchar (' ');
3937 while (pad--);
3939 else
3941 printf ("%*lu ", width, id);
3942 len = width;
3945 dired_pos += len + 1;
3948 /* Print the name or id of the user with id U, using a print width of
3949 WIDTH. */
3951 static void
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. */
3960 static void
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. */
3969 static int
3970 format_user_or_group_width (char const *name, unsigned long int id)
3972 if (name)
3974 int len = mbswidth (name, 0);
3975 return MAX (0, len);
3977 else
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. */
3987 static int
3988 format_user_width (uid_t u)
3990 return format_user_or_group_width (numeric_ids ? NULL : getuser (u), u);
3993 /* Likewise, for groups. */
3995 static int
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. */
4004 static char *
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)
4010 : (char *) "?");
4013 /* Print information about F in long format. */
4014 static void
4015 print_long_format (const struct fileinfo *f)
4017 char modebuf[12];
4018 char buf
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 */
4027 size_t s;
4028 char *p;
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. */
4034 if (f->stat_ok)
4035 filemodestring (&f->stat, modebuf);
4036 else
4038 modebuf[0] = filetype_letter[f->filetype];
4039 memset (modebuf + 1, '?', 10);
4040 modebuf[11] = '\0';
4042 if (! any_has_acl)
4043 modebuf[10] = '\0';
4044 else if (f->acl_type == ACL_T_LSM_CONTEXT_ONLY)
4045 modebuf[10] = '.';
4046 else if (f->acl_type == ACL_T_YES)
4047 modebuf[10] = '+';
4049 switch (time_type)
4051 case time_ctime:
4052 when_timespec = get_stat_ctime (&f->stat);
4053 break;
4054 case time_mtime:
4055 when_timespec = get_stat_mtime (&f->stat);
4056 break;
4057 case time_atime:
4058 when_timespec = get_stat_atime (&f->stat);
4059 break;
4060 default:
4061 abort ();
4064 p = buf;
4066 if (print_inode)
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. */
4073 p += strlen (p);
4076 if (print_block_size)
4078 char hbuf[LONGEST_HUMAN_READABLE + 1];
4079 char const *blocks =
4080 (! f->stat_ok
4081 ? "?"
4082 : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts,
4083 ST_NBLOCKSIZE, output_block_size));
4084 int pad;
4085 for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--)
4086 *p++ = ' ';
4087 while ((*p++ = *blocks++))
4088 continue;
4089 p[-1] = ' ';
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. */
4102 p += strlen (p);
4104 DIRED_INDENT ();
4106 if (print_owner || print_group || print_author || print_scontext)
4108 DIRED_FPUTS (buf, stdout, p - buf);
4110 if (print_owner)
4111 format_user (f->stat.st_uid, owner_width, f->stat_ok);
4113 if (print_group)
4114 format_group (f->stat.st_gid, group_width, f->stat_ok);
4116 if (print_author)
4117 format_user (f->stat.st_author, author_width, f->stat_ok);
4119 if (print_scontext)
4120 format_user_or_group (f->scontext, 0, scontext_width);
4122 p = buf;
4125 if (f->stat_ok
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;
4140 else
4142 char hbuf[LONGEST_HUMAN_READABLE + 1];
4143 char const *size =
4144 (! f->stat_ok
4145 ? "?"
4146 : human_readable (unsigned_file_size (f->stat.st_size),
4147 hbuf, file_human_output_opts, 1,
4148 file_output_block_size));
4149 int pad;
4150 for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
4151 *p++ = ' ';
4152 while ((*p++ = *size++))
4153 continue;
4154 p[-1] = ' ';
4157 s = 0;
4158 *p = '\1';
4160 if (f->stat_ok && localtime_rz (localtz, &when_timespec.tv_sec, &when_local))
4162 struct timespec six_months_ago;
4163 bool recent;
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 (&current_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);
4187 if (s || !*p)
4189 p += s;
4190 *p++ = ' ';
4192 /* NUL-terminate the string -- fputs (via DIRED_FPUTS) requires it. */
4193 *p = '\0';
4195 else
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 (),
4201 (! f->stat_ok
4202 ? "?"
4203 : timetostr (when_timespec.tv_sec, hbuf)));
4204 /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */
4205 p += strlen (p);
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)
4213 if (f->linkname)
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. */
4234 static size_t
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)
4239 char *buf = *inbuf;
4240 size_t displayed_width IF_LINT ( = 0);
4241 size_t len = 0;
4242 bool quoted;
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);
4253 if (bufsize <= len)
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);
4264 if (bufsize <= len)
4265 buf = xmalloc (len + 1);
4266 memcpy (buf, name, len + 1);
4268 quoted = false;
4270 else
4272 len = strlen (name);
4273 buf = name;
4274 quoted = false;
4277 if (needs_further_quoting)
4279 if (MB_CUR_MAX > 1)
4281 char const *p = buf;
4282 char const *plimit = buf + len;
4283 char *q = buf;
4284 displayed_width = 0;
4286 while (p < plimit)
4287 switch (*p)
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 '>':
4295 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':
4301 case 'Z':
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. */
4310 *q++ = *p++;
4311 displayed_width += 1;
4312 break;
4313 default:
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, };
4321 wchar_t wc;
4322 size_t bytes;
4323 int w;
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. */
4332 p++;
4333 *q++ = '?';
4334 displayed_width += 1;
4335 break;
4338 if (bytes == (size_t) -2)
4340 /* An incomplete multibyte character
4341 at the end. Replace it entirely with
4342 a question mark. */
4343 p = plimit;
4344 *q++ = '?';
4345 displayed_width += 1;
4346 break;
4349 if (bytes == 0)
4350 /* A null wide character was encountered. */
4351 bytes = 1;
4353 w = wcwidth (wc);
4354 if (w >= 0)
4356 /* A printable multibyte character.
4357 Keep it. */
4358 for (; bytes > 0; --bytes)
4359 *q++ = *p++;
4360 displayed_width += w;
4362 else
4364 /* An unprintable multibyte character.
4365 Replace it entirely with a question
4366 mark. */
4367 p += bytes;
4368 *q++ = '?';
4369 displayed_width += 1;
4372 while (! mbsinit (&mbstate));
4374 break;
4377 /* The buffer may have shrunk. */
4378 len = q - buf;
4380 else
4382 char *p = buf;
4383 char const *plimit = buf + len;
4385 while (p < plimit)
4387 if (! isprint (to_uchar (*p)))
4388 *p = '?';
4389 p++;
4391 displayed_width = len;
4394 else if (width != NULL)
4396 if (MB_CUR_MAX > 1)
4397 displayed_width = mbsnwidth (buf, len, 0);
4398 else
4400 char const *p = buf;
4401 char const *plimit = buf + len;
4403 displayed_width = 0;
4404 while (p < plimit)
4406 if (isprint (to_uchar (*p)))
4407 displayed_width++;
4408 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);
4418 if (width != NULL)
4419 *width = displayed_width;
4421 *inbuf = buf;
4423 return len;
4426 static size_t
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;
4432 size_t width;
4433 bool pad;
4435 quote_name_buf (&buf, sizeof smallbuf, (char *) name, options,
4436 needs_general_quoting, &width, &pad);
4438 if (buf != smallbuf && buf != name)
4439 free (buf);
4441 width += pad;
4443 return width;
4446 /* %XX escape any input out of range as defined in RFC3986,
4447 and also if PATH, convert all path separators to '/'. */
4448 static char *
4449 file_escape (const char *str, bool path)
4451 char *esc = xnmalloc (3, strlen (str) + 1);
4452 char *p = esc;
4453 while (*str)
4455 if (path && ISSLASH (*str))
4457 *p++ = '/';
4458 str++;
4460 else if (RFC3986[to_uchar (*str)])
4461 *p++ = *str++;
4462 else
4463 p += sprintf (p, "%%%02x", to_uchar (*str++));
4465 *p = '\0';
4466 return esc;
4469 static size_t
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;
4476 size_t len;
4477 bool pad;
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 (' ');
4485 if (color)
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;
4492 if (absolute_name)
4494 if (align_variable_outer_quotes && cwd_some_quoted && ! pad)
4496 skip_quotes = true;
4497 putchar (*buf);
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);
4507 free (h);
4508 free (n);
4511 if (stack)
4512 PUSH_CURRENT_DIRED_POS (stack);
4514 fwrite (buf + skip_quotes, 1, len - (skip_quotes * 2), stdout);
4516 dired_pos += len;
4518 if (stack)
4519 PUSH_CURRENT_DIRED_POS (stack);
4521 if (absolute_name)
4523 fputs ("\033]8;;\a", stdout);
4524 if (skip_quotes)
4525 putchar (*(buf + len - 1));
4528 if (buf != smallbuf && buf != name)
4529 free (buf);
4531 return len + pad;
4534 static size_t
4535 print_name_with_quoting (const struct fileinfo *f,
4536 bool symlink_target,
4537 struct obstack *stack,
4538 size_t start_col)
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);
4551 process_signals ();
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. */
4562 if (line_length
4563 && (start_col / line_length != (start_col + len - 1) / line_length))
4564 put_indicator (&color_indicator[C_CLR_TO_EOL]);
4567 return len;
4570 static void
4571 prep_non_filename_text (void)
4573 if (color_indicator[C_END].string != NULL)
4574 put_indicator (&color_indicator[C_END]);
4575 else
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. */
4587 static size_t
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 ();
4594 if (print_inode)
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,
4600 ! f->stat_ok ? "?"
4601 : human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts,
4602 ST_NBLOCKSIZE, output_block_size));
4604 if (print_scontext)
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);
4612 return width;
4615 /* Given these arguments describing a file, return the single-byte
4616 type indicator, or 0. */
4617 static char
4618 get_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4620 char c;
4622 if (stat_ok ? S_ISREG (mode) : type == normal)
4624 if (stat_ok && indicator_style == classify && (mode & S_IXUGO))
4625 c = '*';
4626 else
4627 c = 0;
4629 else
4631 if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory)
4632 c = '/';
4633 else if (indicator_style == slash)
4634 c = 0;
4635 else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link)
4636 c = '@';
4637 else if (stat_ok ? S_ISFIFO (mode) : type == fifo)
4638 c = '|';
4639 else if (stat_ok ? S_ISSOCK (mode) : type == sock)
4640 c = '=';
4641 else if (stat_ok && S_ISDOOR (mode))
4642 c = '>';
4643 else
4644 c = 0;
4646 return c;
4649 static bool
4650 print_type_indicator (bool stat_ok, mode_t mode, enum filetype type)
4652 char c = get_type_indicator (stat_ok, mode, type);
4653 if (c)
4654 DIRED_PUTCHAR (c);
4655 return !!c;
4658 /* Returns if color sequence was printed. */
4659 static bool
4660 print_color_indicator (const struct bin_str *ind)
4662 if (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]);
4672 return ind != NULL;
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 */
4683 const char* name;
4684 mode_t mode;
4685 int linkok;
4686 if (symlink_target)
4688 name = f->linkname;
4689 mode = f->linkmode;
4690 linkok = f->linkok ? 0 : -1;
4692 else
4694 name = f->name;
4695 mode = FILE_OR_LINK_MODE (f);
4696 linkok = f->linkok;
4699 /* Is this a nonexistent file? If so, linkok == -1. */
4701 if (linkok == -1 && is_colored (C_MISSING))
4702 type = C_MISSING;
4703 else if (!f->stat_ok)
4705 static enum indicator_no filetype_indicator[] = FILETYPE_INDICATORS;
4706 type = filetype_indicator[f->filetype];
4708 else
4710 if (S_ISREG (mode))
4712 type = C_FILE;
4714 if ((mode & S_ISUID) != 0 && is_colored (C_SETUID))
4715 type = C_SETUID;
4716 else if ((mode & S_ISGID) != 0 && is_colored (C_SETGID))
4717 type = C_SETGID;
4718 else if (is_colored (C_CAP) && f->has_capability)
4719 type = C_CAP;
4720 else if ((mode & S_IXUGO) != 0 && is_colored (C_EXEC))
4721 type = C_EXEC;
4722 else if ((1 < f->stat.st_nlink) && is_colored (C_MULTIHARDLINK))
4723 type = C_MULTIHARDLINK;
4725 else if (S_ISDIR (mode))
4727 type = C_DIR;
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))
4735 type = C_STICKY;
4737 else if (S_ISLNK (mode))
4738 type = C_LINK;
4739 else if (S_ISFIFO (mode))
4740 type = C_FIFO;
4741 else if (S_ISSOCK (mode))
4742 type = C_SOCK;
4743 else if (S_ISBLK (mode))
4744 type = C_BLK;
4745 else if (S_ISCHR (mode))
4746 type = C_CHR;
4747 else if (S_ISDOOR (mode))
4748 type = C_DOOR;
4749 else
4751 /* Classify a file of some other type as C_ORPHAN. */
4752 type = C_ORPHAN;
4756 /* Check the file's suffix only if still classified as C_FILE. */
4757 ext = NULL;
4758 if (type == 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,
4768 ext->ext.len))
4769 break;
4773 /* Adjust the color for orphaned symlinks. */
4774 if (type == C_LINK && !linkok)
4776 if (color_symlink_as_referent || is_colored (C_ORPHAN))
4777 type = 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). */
4787 static void
4788 put_indicator (const struct bin_str *ind)
4790 if (! used_color)
4792 used_color = true;
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))
4799 signal_init ();
4801 prep_non_filename_text ();
4804 fwrite (ind->string, ind->len, 1, stdout);
4807 static size_t
4808 length_of_file_name_and_frills (const struct fileinfo *f)
4810 size_t len = 0;
4811 char buf[MAX (LONGEST_HUMAN_READABLE + 1, INT_BUFSIZE_BOUND (uintmax_t))];
4813 if (print_inode)
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,
4823 output_block_size))
4824 : block_size_width);
4826 if (print_scontext)
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);
4834 len += (c != 0);
4837 return len;
4840 static void
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++)
4853 size_t col = 0;
4854 size_t filesno = row;
4855 size_t pos = 0;
4857 /* Print the next row. */
4858 while (1)
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);
4865 filesno += rows;
4866 if (filesno >= cwd_n_used)
4867 break;
4869 indent (pos + name_length, pos + max_name_length);
4870 pos += max_name_length;
4872 putchar ('\n');
4876 static void
4877 print_horizontal (void)
4879 size_t filesno;
4880 size_t pos = 0;
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);
4890 /* Now the rest. */
4891 for (filesno = 1; filesno < cwd_n_used; ++filesno)
4893 size_t col = filesno % cols;
4895 if (col == 0)
4897 putchar ('\n');
4898 pos = 0;
4900 else
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];
4912 putchar ('\n');
4915 /* Output name + SEP + ' '. */
4917 static void
4918 print_with_separator (char sep)
4920 size_t filesno;
4921 size_t pos = 0;
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;
4928 if (filesno != 0)
4930 char separator;
4932 if (! line_length
4933 || ((pos + len + 2 < line_length)
4934 && (pos <= SIZE_MAX - len - 2)))
4936 pos += 2;
4937 separator = ' ';
4939 else
4941 pos = 0;
4942 separator = '\n';
4945 putchar (sep);
4946 putchar (separator);
4949 print_file_name_and_frills (f, pos);
4950 pos += len;
4952 putchar ('\n');
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. */
4958 static void
4959 indent (size_t from, size_t to)
4961 while (from < to)
4963 if (tabsize != 0 && to / tabsize > (from + 1) / tabsize)
4965 putchar ('\t');
4966 from += tabsize - from % tabsize;
4968 else
4970 putchar (' ');
4971 from++;
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. */
4980 static void
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)
4988 while (*dirnamep)
4989 *dest++ = *dirnamep++;
4990 /* Add '/' if 'dirname' doesn't already end with it. */
4991 if (dirnamep > dirname && dirnamep[-1] != '/')
4992 *dest++ = '/';
4994 while (*name)
4995 *dest++ = *name++;
4996 *dest = 0;
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. */
5003 static void
5004 init_column_info (void)
5006 size_t i;
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;
5015 size_t *p;
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;
5028 else
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)
5043 xalloc_die ();
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;
5051 p += i + 1;
5054 column_info_alloc = new_column_info_alloc;
5057 for (i = 0; i < max_cols; ++i)
5059 size_t j;
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. */
5071 static size_t
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
5079 as well. */
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
5105 < line_length);
5111 /* Find maximum allowed columns. */
5112 for (cols = max_cols; 1 < cols; --cols)
5114 if (column_info[cols - 1].valid_len)
5115 break;
5118 return cols;
5121 void
5122 usage (int status)
5124 if (status != EXIT_SUCCESS)
5125 emit_try_help ();
5126 else
5128 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
5129 fputs (_("\
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\
5132 "), stdout);
5134 emit_mandatory_arg_note ();
5136 fputs (_("\
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\
5141 "), stdout);
5142 fputs (_("\
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\
5151 "), stdout);
5152 fputs (_("\
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\
5160 "), stdout);
5161 fputs (_("\
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\
5168 "), stdout);
5169 fputs (_("\
5170 -g like -l, but do not list owner\n\
5171 "), stdout);
5172 fputs (_("\
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\
5177 "), stdout);
5178 fputs (_("\
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\
5183 "), stdout);
5184 fputs (_("\
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\
5193 "), stdout);
5194 fputs (_("\
5195 --hyperlink[=WHEN] hyperlink file names; WHEN can be 'always'\n\
5196 (default if omitted), 'auto', or 'never'\n\
5197 "), stdout);
5198 fputs (_("\
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\
5207 "), stdout);
5208 fputs (_("\
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\
5215 "), stdout);
5216 fputs (_("\
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\
5222 "), stdout);
5223 fputs (_("\
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\
5232 "), stdout);
5233 fputs (_("\
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\
5237 "), stdout);
5238 fputs (_("\
5239 -S sort by file size, largest first\n\
5240 --sort=WORD sort by WORD instead of name: none (-U), size (-S)\
5241 ,\n\
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\
5248 "), stdout);
5249 fputs (_("\
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\
5260 "), stdout);
5261 fputs (_("\
5262 -t sort by modification time, newest first\n\
5263 -T, --tabsize=COLS assume tab stops at each COLS instead of 8\n\
5264 "), stdout);
5265 fputs (_("\
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\
5271 "), stdout);
5272 fputs (_("\
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\
5279 "), stdout);
5280 fputs (HELP_OPTION_DESCRIPTION, stdout);
5281 fputs (VERSION_OPTION_DESCRIPTION, stdout);
5282 emit_size_note ();
5283 fputs (_("\
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\
5289 "), stdout);
5290 fputs (_("\
5292 Exit status:\n\
5293 0 if OK,\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\
5296 "), stdout);
5297 emit_ancillary_info (PROGRAM_NAME);
5299 exit (status);