doc: clarify the operation of wc -L
[coreutils.git] / src / du.c
blob86827f808ebe6abebea3c14fcf2530f22764f740
1 /* du -- summarize disk usage
2 Copyright (C) 1988-2015 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 /* Differences from the Unix du:
18 * Doesn't simply ignore the names of regular files given as arguments
19 when -a is given.
21 By tege@sics.se, Torbjorn Granlund,
22 and djm@ai.mit.edu, David MacKenzie.
23 Variable blocks added by lm@sgi.com and eggert@twinsun.com.
24 Rewritten to use nftw, then to use fts by Jim Meyering. */
26 #include <config.h>
27 #include <getopt.h>
28 #include <sys/types.h>
29 #include <assert.h>
30 #include "system.h"
31 #include "argmatch.h"
32 #include "argv-iter.h"
33 #include "di-set.h"
34 #include "error.h"
35 #include "exclude.h"
36 #include "fprintftime.h"
37 #include "human.h"
38 #include "mountlist.h"
39 #include "quote.h"
40 #include "quotearg.h"
41 #include "stat-size.h"
42 #include "stat-time.h"
43 #include "stdio--.h"
44 #include "xfts.h"
45 #include "xstrtol.h"
47 extern bool fts_debug;
49 /* The official name of this program (e.g., no 'g' prefix). */
50 #define PROGRAM_NAME "du"
52 #define AUTHORS \
53 proper_name_utf8 ("Torbjorn Granlund", "Torbj\303\266rn Granlund"), \
54 proper_name ("David MacKenzie"), \
55 proper_name ("Paul Eggert"), \
56 proper_name ("Jim Meyering")
58 #if DU_DEBUG
59 # define FTS_CROSS_CHECK(Fts) fts_cross_check (Fts)
60 #else
61 # define FTS_CROSS_CHECK(Fts)
62 #endif
64 /* A set of dev/ino pairs to help identify files and directories
65 whose sizes have already been counted. */
66 static struct di_set *di_files;
68 /* A set containing a dev/ino pair for each local mount point directory. */
69 static struct di_set *di_mnt;
71 /* Keep track of the preceding "level" (depth in hierarchy)
72 from one call of process_file to the next. */
73 static size_t prev_level;
75 /* Define a class for collecting directory information. */
76 struct duinfo
78 /* Size of files in directory. */
79 uintmax_t size;
81 /* Number of inodes in directory. */
82 uintmax_t inodes;
84 /* Latest time stamp found. If tmax.tv_sec == TYPE_MINIMUM (time_t)
85 && tmax.tv_nsec < 0, no time stamp has been found. */
86 struct timespec tmax;
89 /* Initialize directory data. */
90 static inline void
91 duinfo_init (struct duinfo *a)
93 a->size = 0;
94 a->inodes = 0;
95 a->tmax.tv_sec = TYPE_MINIMUM (time_t);
96 a->tmax.tv_nsec = -1;
99 /* Set directory data. */
100 static inline void
101 duinfo_set (struct duinfo *a, uintmax_t size, struct timespec tmax)
103 a->size = size;
104 a->inodes = 1;
105 a->tmax = tmax;
108 /* Accumulate directory data. */
109 static inline void
110 duinfo_add (struct duinfo *a, struct duinfo const *b)
112 uintmax_t sum = a->size + b->size;
113 a->size = a->size <= sum ? sum : UINTMAX_MAX;
114 a->inodes = a->inodes + b->inodes;
115 if (timespec_cmp (a->tmax, b->tmax) < 0)
116 a->tmax = b->tmax;
119 /* A structure for per-directory level information. */
120 struct dulevel
122 /* Entries in this directory. */
123 struct duinfo ent;
125 /* Total for subdirectories. */
126 struct duinfo subdir;
129 /* If true, display counts for all files, not just directories. */
130 static bool opt_all = false;
132 /* If true, rather than using the disk usage of each file,
133 use the apparent size (a la stat.st_size). */
134 static bool apparent_size = false;
136 /* If true, count each hard link of files with multiple links. */
137 static bool opt_count_all = false;
139 /* If true, hash all files to look for hard links. */
140 static bool hash_all;
142 /* If true, output the NUL byte instead of a newline at the end of each line. */
143 static bool opt_nul_terminate_output = false;
145 /* If true, print a grand total at the end. */
146 static bool print_grand_total = false;
148 /* If nonzero, do not add sizes of subdirectories. */
149 static bool opt_separate_dirs = false;
151 /* Show the total for each directory (and file if --all) that is at
152 most MAX_DEPTH levels down from the root of the hierarchy. The root
153 is at level 0, so 'du --max-depth=0' is equivalent to 'du -s'. */
154 static size_t max_depth = SIZE_MAX;
156 /* Only output entries with at least this SIZE if positive,
157 or at most if negative. See --threshold option. */
158 static intmax_t opt_threshold = 0;
160 /* Human-readable options for output. */
161 static int human_output_opts;
163 /* Output inodes count instead of blocks used. */
164 static bool opt_inodes = false;
166 /* If true, print most recently modified date, using the specified format. */
167 static bool opt_time = false;
169 /* Type of time to display. controlled by --time. */
171 enum time_type
173 time_mtime, /* default */
174 time_ctime,
175 time_atime
178 static enum time_type time_type = time_mtime;
180 /* User specified date / time style */
181 static char const *time_style = NULL;
183 /* Format used to display date / time. Controlled by --time-style */
184 static char const *time_format = NULL;
186 /* The units to use when printing sizes. */
187 static uintmax_t output_block_size;
189 /* File name patterns to exclude. */
190 static struct exclude *exclude;
192 /* Grand total size of all args, in bytes. Also latest modified date. */
193 static struct duinfo tot_dui;
195 #define IS_DIR_TYPE(Type) \
196 ((Type) == FTS_DP \
197 || (Type) == FTS_DNR)
199 /* For long options that have no equivalent short option, use a
200 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
201 enum
203 APPARENT_SIZE_OPTION = CHAR_MAX + 1,
204 EXCLUDE_OPTION,
205 FILES0_FROM_OPTION,
206 HUMAN_SI_OPTION,
207 FTS_DEBUG,
208 TIME_OPTION,
209 TIME_STYLE_OPTION,
210 INODES_OPTION
213 static struct option const long_options[] =
215 {"all", no_argument, NULL, 'a'},
216 {"apparent-size", no_argument, NULL, APPARENT_SIZE_OPTION},
217 {"block-size", required_argument, NULL, 'B'},
218 {"bytes", no_argument, NULL, 'b'},
219 {"count-links", no_argument, NULL, 'l'},
220 /* {"-debug", no_argument, NULL, FTS_DEBUG}, */
221 {"dereference", no_argument, NULL, 'L'},
222 {"dereference-args", no_argument, NULL, 'D'},
223 {"exclude", required_argument, NULL, EXCLUDE_OPTION},
224 {"exclude-from", required_argument, NULL, 'X'},
225 {"files0-from", required_argument, NULL, FILES0_FROM_OPTION},
226 {"human-readable", no_argument, NULL, 'h'},
227 {"inodes", no_argument, NULL, INODES_OPTION},
228 {"si", no_argument, NULL, HUMAN_SI_OPTION},
229 {"max-depth", required_argument, NULL, 'd'},
230 {"null", no_argument, NULL, '0'},
231 {"no-dereference", no_argument, NULL, 'P'},
232 {"one-file-system", no_argument, NULL, 'x'},
233 {"separate-dirs", no_argument, NULL, 'S'},
234 {"summarize", no_argument, NULL, 's'},
235 {"total", no_argument, NULL, 'c'},
236 {"threshold", required_argument, NULL, 't'},
237 {"time", optional_argument, NULL, TIME_OPTION},
238 {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
239 {GETOPT_HELP_OPTION_DECL},
240 {GETOPT_VERSION_OPTION_DECL},
241 {NULL, 0, NULL, 0}
244 static char const *const time_args[] =
246 "atime", "access", "use", "ctime", "status", NULL
248 static enum time_type const time_types[] =
250 time_atime, time_atime, time_atime, time_ctime, time_ctime
252 ARGMATCH_VERIFY (time_args, time_types);
254 /* 'full-iso' uses full ISO-style dates and times. 'long-iso' uses longer
255 ISO-style time stamps, though shorter than 'full-iso'. 'iso' uses shorter
256 ISO-style time stamps. */
257 enum time_style
259 full_iso_time_style, /* --time-style=full-iso */
260 long_iso_time_style, /* --time-style=long-iso */
261 iso_time_style /* --time-style=iso */
264 static char const *const time_style_args[] =
266 "full-iso", "long-iso", "iso", NULL
268 static enum time_style const time_style_types[] =
270 full_iso_time_style, long_iso_time_style, iso_time_style
272 ARGMATCH_VERIFY (time_style_args, time_style_types);
274 void
275 usage (int status)
277 if (status != EXIT_SUCCESS)
278 emit_try_help ();
279 else
281 printf (_("\
282 Usage: %s [OPTION]... [FILE]...\n\
283 or: %s [OPTION]... --files0-from=F\n\
284 "), program_name, program_name);
285 fputs (_("\
286 Summarize disk usage of the set of FILEs, recursively for directories.\n\
287 "), stdout);
289 emit_mandatory_arg_note ();
291 fputs (_("\
292 -0, --null end each output line with NUL, not newline\n\
293 -a, --all write counts for all files, not just directories\n\
294 --apparent-size print apparent sizes, rather than disk usage; although\
296 the apparent size is usually smaller, it may be\n\
297 larger due to holes in ('sparse') files, internal\n\
298 fragmentation, indirect blocks, and the like\n\
299 "), stdout);
300 fputs (_("\
301 -B, --block-size=SIZE scale sizes by SIZE before printing them; e.g.,\n\
302 '-BM' prints sizes in units of 1,048,576 bytes;\n\
303 see SIZE format below\n\
304 -b, --bytes equivalent to '--apparent-size --block-size=1'\n\
305 -c, --total produce a grand total\n\
306 -D, --dereference-args dereference only symlinks that are listed on the\n\
307 command line\n\
308 -d, --max-depth=N print the total for a directory (or file, with --all)\n\
309 only if it is N or fewer levels below the command\n\
310 line argument; --max-depth=0 is the same as\n\
311 --summarize\n\
312 "), stdout);
313 fputs (_("\
314 --files0-from=F summarize disk usage of the\n\
315 NUL-terminated file names specified in file F;\n\
316 if F is -, then read names from standard input\n\
317 -H equivalent to --dereference-args (-D)\n\
318 -h, --human-readable print sizes in human readable format (e.g., 1K 234M 2G)\
320 --inodes list inode usage information instead of block usage\n\
321 "), stdout);
322 fputs (_("\
323 -k like --block-size=1K\n\
324 -L, --dereference dereference all symbolic links\n\
325 -l, --count-links count sizes many times if hard linked\n\
326 -m like --block-size=1M\n\
327 "), stdout);
328 fputs (_("\
329 -P, --no-dereference don't follow any symbolic links (this is the default)\n\
330 -S, --separate-dirs for directories do not include size of subdirectories\n\
331 --si like -h, but use powers of 1000 not 1024\n\
332 -s, --summarize display only a total for each argument\n\
333 "), stdout);
334 fputs (_("\
335 -t, --threshold=SIZE exclude entries smaller than SIZE if positive,\n\
336 or entries greater than SIZE if negative\n\
337 --time show time of the last modification of any file in the\n\
338 directory, or any of its subdirectories\n\
339 --time=WORD show time as WORD instead of modification time:\n\
340 atime, access, use, ctime or status\n\
341 --time-style=STYLE show times using STYLE, which can be:\n\
342 full-iso, long-iso, iso, or +FORMAT;\n\
343 FORMAT is interpreted like in 'date'\n\
344 "), stdout);
345 fputs (_("\
346 -X, --exclude-from=FILE exclude files that match any pattern in FILE\n\
347 --exclude=PATTERN exclude files that match PATTERN\n\
348 -x, --one-file-system skip directories on different file systems\n\
349 "), stdout);
350 fputs (HELP_OPTION_DESCRIPTION, stdout);
351 fputs (VERSION_OPTION_DESCRIPTION, stdout);
352 emit_blocksize_note ("DU");
353 emit_size_note ();
354 emit_ancillary_info (PROGRAM_NAME);
356 exit (status);
359 /* Try to insert the INO/DEV pair into DI_SET.
360 Return true if the pair is successfully inserted,
361 false if the pair was already there. */
362 static bool
363 hash_ins (struct di_set *di_set, ino_t ino, dev_t dev)
365 int inserted = di_set_insert (di_set, dev, ino);
366 if (inserted < 0)
367 xalloc_die ();
368 return inserted;
371 /* FIXME: this code is nearly identical to code in date.c */
372 /* Display the date and time in WHEN according to the format specified
373 in FORMAT. */
375 static void
376 show_date (const char *format, struct timespec when)
378 struct tm *tm = localtime (&when.tv_sec);
379 if (! tm)
381 char buf[INT_BUFSIZE_BOUND (intmax_t)];
382 char *when_str = timetostr (when.tv_sec, buf);
383 error (0, 0, _("time %s is out of range"), when_str);
384 fputs (when_str, stdout);
385 return;
388 fprintftime (stdout, format, tm, 0, when.tv_nsec);
391 /* Print N_BYTES. Convert it to a readable value before printing. */
393 static void
394 print_only_size (uintmax_t n_bytes)
396 char buf[LONGEST_HUMAN_READABLE + 1];
397 fputs ((n_bytes == UINTMAX_MAX
398 ? _("Infinity")
399 : human_readable (n_bytes, buf, human_output_opts,
400 1, output_block_size)),
401 stdout);
404 /* Print size (and optionally time) indicated by *PDUI, followed by STRING. */
406 static void
407 print_size (const struct duinfo *pdui, const char *string)
409 print_only_size (opt_inodes
410 ? pdui->inodes
411 : pdui->size);
413 if (opt_time)
415 putchar ('\t');
416 show_date (time_format, pdui->tmax);
418 printf ("\t%s%c", string, opt_nul_terminate_output ? '\0' : '\n');
419 fflush (stdout);
422 /* This function checks whether any of the directories in the cycle that
423 fts detected is a mount point. */
425 static bool
426 mount_point_in_fts_cycle (FTSENT const *ent)
428 FTSENT const *cycle_ent = ent->fts_cycle;
430 while (ent && ent != cycle_ent)
432 if (di_set_lookup (di_mnt, ent->fts_statp->st_dev,
433 ent->fts_statp->st_ino) > 0)
435 return true;
437 ent = ent->fts_parent;
440 return false;
443 /* This function is called once for every file system object that fts
444 encounters. fts does a depth-first traversal. This function knows
445 that and accumulates per-directory totals based on changes in
446 the depth of the current entry. It returns true on success. */
448 static bool
449 process_file (FTS *fts, FTSENT *ent)
451 bool ok = true;
452 struct duinfo dui;
453 struct duinfo dui_to_print;
454 size_t level;
455 static size_t n_alloc;
456 /* First element of the structure contains:
457 The sum of the st_size values of all entries in the single directory
458 at the corresponding level. Although this does include the st_size
459 corresponding to each subdirectory, it does not include the size of
460 any file in a subdirectory. Also corresponding last modified date.
461 Second element of the structure contains:
462 The sum of the sizes of all entries in the hierarchy at or below the
463 directory at the specified level. */
464 static struct dulevel *dulvl;
466 const char *file = ent->fts_path;
467 const struct stat *sb = ent->fts_statp;
468 int info = ent->fts_info;
470 if (info == FTS_DNR)
472 /* An error occurred, but the size is known, so count it. */
473 error (0, ent->fts_errno, _("cannot read directory %s"), quote (file));
474 ok = false;
476 else if (info != FTS_DP)
478 bool excluded = excluded_file_name (exclude, file);
479 if (! excluded)
481 /* Make the stat buffer *SB valid, or fail noisily. */
483 if (info == FTS_NSOK)
485 fts_set (fts, ent, FTS_AGAIN);
486 FTSENT const *e = fts_read (fts);
487 assert (e == ent);
488 info = ent->fts_info;
491 if (info == FTS_NS || info == FTS_SLNONE)
493 error (0, ent->fts_errno, _("cannot access %s"), quote (file));
494 return false;
497 /* The --one-file-system (-x) option cannot exclude anything
498 specified on the command-line. By definition, it can exclude
499 a file or directory only when its device number is different
500 from that of its just-processed parent directory, and du does
501 not process the parent of a command-line argument. */
502 if (fts->fts_options & FTS_XDEV
503 && FTS_ROOTLEVEL < ent->fts_level
504 && fts->fts_dev != sb->st_dev)
505 excluded = true;
508 if (excluded
509 || (! opt_count_all
510 && (hash_all || (! S_ISDIR (sb->st_mode) && 1 < sb->st_nlink))
511 && ! hash_ins (di_files, sb->st_ino, sb->st_dev)))
513 /* If ignoring a directory in preorder, skip its children.
514 Ignore the next fts_read output too, as it's a postorder
515 visit to the same directory. */
516 if (info == FTS_D)
518 fts_set (fts, ent, FTS_SKIP);
519 FTSENT const *e = fts_read (fts);
520 assert (e == ent);
523 return true;
526 switch (info)
528 case FTS_D:
529 return true;
531 case FTS_ERR:
532 /* An error occurred, but the size is known, so count it. */
533 error (0, ent->fts_errno, "%s", quote (file));
534 ok = false;
535 break;
537 case FTS_DC:
538 /* If not following symlinks and not a (bind) mount point. */
539 if (cycle_warning_required (fts, ent)
540 && ! mount_point_in_fts_cycle (ent))
542 emit_cycle_warning (file);
543 return false;
545 return true;
549 duinfo_set (&dui,
550 (apparent_size
551 ? MAX (0, sb->st_size)
552 : (uintmax_t) ST_NBLOCKS (*sb) * ST_NBLOCKSIZE),
553 (time_type == time_mtime ? get_stat_mtime (sb)
554 : time_type == time_atime ? get_stat_atime (sb)
555 : get_stat_ctime (sb)));
557 level = ent->fts_level;
558 dui_to_print = dui;
560 if (n_alloc == 0)
562 n_alloc = level + 10;
563 dulvl = xcalloc (n_alloc, sizeof *dulvl);
565 else
567 if (level == prev_level)
569 /* This is usually the most common case. Do nothing. */
571 else if (level > prev_level)
573 /* Descending the hierarchy.
574 Clear the accumulators for *all* levels between prev_level
575 and the current one. The depth may change dramatically,
576 e.g., from 1 to 10. */
577 size_t i;
579 if (n_alloc <= level)
581 dulvl = xnrealloc (dulvl, level, 2 * sizeof *dulvl);
582 n_alloc = level * 2;
585 for (i = prev_level + 1; i <= level; i++)
587 duinfo_init (&dulvl[i].ent);
588 duinfo_init (&dulvl[i].subdir);
591 else /* level < prev_level */
593 /* Ascending the hierarchy.
594 Process a directory only after all entries in that
595 directory have been processed. When the depth decreases,
596 propagate sums from the children (prev_level) to the parent.
597 Here, the current level is always one smaller than the
598 previous one. */
599 assert (level == prev_level - 1);
600 duinfo_add (&dui_to_print, &dulvl[prev_level].ent);
601 if (!opt_separate_dirs)
602 duinfo_add (&dui_to_print, &dulvl[prev_level].subdir);
603 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].ent);
604 duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].subdir);
608 prev_level = level;
610 /* Let the size of a directory entry contribute to the total for the
611 containing directory, unless --separate-dirs (-S) is specified. */
612 if (! (opt_separate_dirs && IS_DIR_TYPE (info)))
613 duinfo_add (&dulvl[level].ent, &dui);
615 /* Even if this directory is unreadable or we can't chdir into it,
616 do let its size contribute to the total. */
617 duinfo_add (&tot_dui, &dui);
619 if ((IS_DIR_TYPE (info) && level <= max_depth)
620 || (opt_all && level <= max_depth)
621 || level == 0)
623 /* Print or elide this entry according to the --threshold option. */
624 uintmax_t v = opt_inodes ? dui_to_print.inodes : dui_to_print.size;
625 if (opt_threshold < 0
626 ? v <= -opt_threshold
627 : v >= opt_threshold)
628 print_size (&dui_to_print, file);
631 return ok;
634 /* Recursively print the sizes of the directories (and, if selected, files)
635 named in FILES, the last entry of which is NULL.
636 BIT_FLAGS controls how fts works.
637 Return true if successful. */
639 static bool
640 du_files (char **files, int bit_flags)
642 bool ok = true;
644 if (*files)
646 FTS *fts = xfts_open (files, bit_flags, NULL);
648 while (1)
650 FTSENT *ent;
652 ent = fts_read (fts);
653 if (ent == NULL)
655 if (errno != 0)
657 error (0, errno, _("fts_read failed: %s"),
658 quotearg_colon (fts->fts_path));
659 ok = false;
662 /* When exiting this loop early, be careful to reset the
663 global, prev_level, used in process_file. Otherwise, its
664 (level == prev_level - 1) assertion could fail. */
665 prev_level = 0;
666 break;
668 FTS_CROSS_CHECK (fts);
670 ok &= process_file (fts, ent);
673 if (fts_close (fts) != 0)
675 error (0, errno, _("fts_close failed"));
676 ok = false;
680 return ok;
683 /* Fill the di_mnt set with local mount point dev/ino pairs. */
685 static void
686 fill_mount_table (void)
688 struct mount_entry *mnt_ent = read_file_system_list (false);
689 while (mnt_ent)
691 struct mount_entry *mnt_free;
692 if (!mnt_ent->me_remote && !mnt_ent->me_dummy)
694 struct stat buf;
695 if (!stat (mnt_ent->me_mountdir, &buf))
696 hash_ins (di_mnt, buf.st_ino, buf.st_dev);
697 else
699 /* Ignore stat failure. False positives are too common.
700 E.g., "Permission denied" on /run/user/<name>/gvfs. */
704 mnt_free = mnt_ent;
705 mnt_ent = mnt_ent->me_next;
706 free_mount_entry (mnt_free);
711 main (int argc, char **argv)
713 char *cwd_only[2];
714 bool max_depth_specified = false;
715 bool ok = true;
716 char *files_from = NULL;
718 /* Bit flags that control how fts works. */
719 int bit_flags = FTS_NOSTAT;
721 /* Select one of the three FTS_ options that control if/when
722 to follow a symlink. */
723 int symlink_deref_bits = FTS_PHYSICAL;
725 /* If true, display only a total for each argument. */
726 bool opt_summarize_only = false;
728 cwd_only[0] = bad_cast (".");
729 cwd_only[1] = NULL;
731 initialize_main (&argc, &argv);
732 set_program_name (argv[0]);
733 setlocale (LC_ALL, "");
734 bindtextdomain (PACKAGE, LOCALEDIR);
735 textdomain (PACKAGE);
737 atexit (close_stdout);
739 exclude = new_exclude ();
741 human_options (getenv ("DU_BLOCK_SIZE"),
742 &human_output_opts, &output_block_size);
744 while (true)
746 int oi = -1;
747 int c = getopt_long (argc, argv, "0abd:chHklmst:xB:DLPSX:",
748 long_options, &oi);
749 if (c == -1)
750 break;
752 switch (c)
754 #if DU_DEBUG
755 case FTS_DEBUG:
756 fts_debug = true;
757 break;
758 #endif
760 case '0':
761 opt_nul_terminate_output = true;
762 break;
764 case 'a':
765 opt_all = true;
766 break;
768 case APPARENT_SIZE_OPTION:
769 apparent_size = true;
770 break;
772 case 'b':
773 apparent_size = true;
774 human_output_opts = 0;
775 output_block_size = 1;
776 break;
778 case 'c':
779 print_grand_total = true;
780 break;
782 case 'h':
783 human_output_opts = human_autoscale | human_SI | human_base_1024;
784 output_block_size = 1;
785 break;
787 case HUMAN_SI_OPTION:
788 human_output_opts = human_autoscale | human_SI;
789 output_block_size = 1;
790 break;
792 case 'k':
793 human_output_opts = 0;
794 output_block_size = 1024;
795 break;
797 case 'd': /* --max-depth=N */
799 unsigned long int tmp_ulong;
800 if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
801 && tmp_ulong <= SIZE_MAX)
803 max_depth_specified = true;
804 max_depth = tmp_ulong;
806 else
808 error (0, 0, _("invalid maximum depth %s"),
809 quote (optarg));
810 ok = false;
813 break;
815 case 'm':
816 human_output_opts = 0;
817 output_block_size = 1024 * 1024;
818 break;
820 case 'l':
821 opt_count_all = true;
822 break;
824 case 's':
825 opt_summarize_only = true;
826 break;
828 case 't':
830 enum strtol_error e;
831 e = xstrtoimax (optarg, NULL, 0, &opt_threshold, "kKmMGTPEZY0");
832 if (e != LONGINT_OK)
833 xstrtol_fatal (e, oi, c, long_options, optarg);
834 if (opt_threshold == 0 && *optarg == '-')
836 /* Do not allow -0, as this wouldn't make sense anyway. */
837 error (EXIT_FAILURE, 0, _("invalid --threshold argument '-0'"));
840 break;
842 case 'x':
843 bit_flags |= FTS_XDEV;
844 break;
846 case 'B':
848 enum strtol_error e = human_options (optarg, &human_output_opts,
849 &output_block_size);
850 if (e != LONGINT_OK)
851 xstrtol_fatal (e, oi, c, long_options, optarg);
853 break;
855 case 'H': /* NOTE: before 2008-12, -H was equivalent to --si. */
856 case 'D':
857 symlink_deref_bits = FTS_COMFOLLOW | FTS_PHYSICAL;
858 break;
860 case 'L': /* --dereference */
861 symlink_deref_bits = FTS_LOGICAL;
862 break;
864 case 'P': /* --no-dereference */
865 symlink_deref_bits = FTS_PHYSICAL;
866 break;
868 case 'S':
869 opt_separate_dirs = true;
870 break;
872 case 'X':
873 if (add_exclude_file (add_exclude, exclude, optarg,
874 EXCLUDE_WILDCARDS, '\n'))
876 error (0, errno, "%s", quotearg_colon (optarg));
877 ok = false;
879 break;
881 case FILES0_FROM_OPTION:
882 files_from = optarg;
883 break;
885 case EXCLUDE_OPTION:
886 add_exclude (exclude, optarg, EXCLUDE_WILDCARDS);
887 break;
889 case INODES_OPTION:
890 opt_inodes = true;
891 break;
893 case TIME_OPTION:
894 opt_time = true;
895 time_type =
896 (optarg
897 ? XARGMATCH ("--time", optarg, time_args, time_types)
898 : time_mtime);
899 break;
901 case TIME_STYLE_OPTION:
902 time_style = optarg;
903 break;
905 case_GETOPT_HELP_CHAR;
907 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
909 default:
910 ok = false;
914 if (!ok)
915 usage (EXIT_FAILURE);
917 if (opt_all && opt_summarize_only)
919 error (0, 0, _("cannot both summarize and show all entries"));
920 usage (EXIT_FAILURE);
923 if (opt_summarize_only && max_depth_specified && max_depth == 0)
925 error (0, 0,
926 _("warning: summarizing is the same as using --max-depth=0"));
929 if (opt_summarize_only && max_depth_specified && max_depth != 0)
931 unsigned long int d = max_depth;
932 error (0, 0, _("warning: summarizing conflicts with --max-depth=%lu"), d);
933 usage (EXIT_FAILURE);
936 if (opt_summarize_only)
937 max_depth = 0;
939 if (opt_inodes)
941 if (apparent_size)
943 error (0, 0, _("warning: options --apparent-size and -b are "
944 "ineffective with --inodes"));
946 output_block_size = 1;
949 /* Process time style if printing last times. */
950 if (opt_time)
952 if (! time_style)
954 time_style = getenv ("TIME_STYLE");
956 /* Ignore TIMESTYLE="locale", for compatibility with ls. */
957 if (! time_style || STREQ (time_style, "locale"))
958 time_style = "long-iso";
959 else if (*time_style == '+')
961 /* Ignore anything after a newline, for compatibility
962 with ls. */
963 char *p = strchr (time_style, '\n');
964 if (p)
965 *p = '\0';
967 else
969 /* Ignore "posix-" prefix, for compatibility with ls. */
970 static char const posix_prefix[] = "posix-";
971 static const size_t prefix_len = sizeof posix_prefix - 1;
972 while (STREQ_LEN (time_style, posix_prefix, prefix_len))
973 time_style += prefix_len;
977 if (*time_style == '+')
978 time_format = time_style + 1;
979 else
981 switch (XARGMATCH ("time style", time_style,
982 time_style_args, time_style_types))
984 case full_iso_time_style:
985 time_format = "%Y-%m-%d %H:%M:%S.%N %z";
986 break;
988 case long_iso_time_style:
989 time_format = "%Y-%m-%d %H:%M";
990 break;
992 case iso_time_style:
993 time_format = "%Y-%m-%d";
994 break;
999 struct argv_iterator *ai;
1000 if (files_from)
1002 /* When using --files0-from=F, you may not specify any files
1003 on the command-line. */
1004 if (optind < argc)
1006 error (0, 0, _("extra operand %s"), quote (argv[optind]));
1007 fprintf (stderr, "%s\n",
1008 _("file operands cannot be combined with --files0-from"));
1009 usage (EXIT_FAILURE);
1012 if (! (STREQ (files_from, "-") || freopen (files_from, "r", stdin)))
1013 error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
1014 quote (files_from));
1016 ai = argv_iter_init_stream (stdin);
1018 /* It's not easy here to count the arguments, so assume the
1019 worst. */
1020 hash_all = true;
1022 else
1024 char **files = (optind < argc ? argv + optind : cwd_only);
1025 ai = argv_iter_init_argv (files);
1027 /* Hash all dev,ino pairs if there are multiple arguments, or if
1028 following non-command-line symlinks, because in either case a
1029 file with just one hard link might be seen more than once. */
1030 hash_all = (optind + 1 < argc || symlink_deref_bits == FTS_LOGICAL);
1033 if (!ai)
1034 xalloc_die ();
1036 /* Initialize the set of dev,inode pairs. */
1038 di_mnt = di_set_alloc ();
1039 if (!di_mnt)
1040 xalloc_die ();
1042 fill_mount_table ();
1044 di_files = di_set_alloc ();
1045 if (!di_files)
1046 xalloc_die ();
1048 /* If not hashing everything, process_file won't find cycles on its
1049 own, so ask fts_read to check for them accurately. */
1050 if (opt_count_all || ! hash_all)
1051 bit_flags |= FTS_TIGHT_CYCLE_CHECK;
1053 bit_flags |= symlink_deref_bits;
1054 static char *temp_argv[] = { NULL, NULL };
1056 while (true)
1058 bool skip_file = false;
1059 enum argv_iter_err ai_err;
1060 char *file_name = argv_iter (ai, &ai_err);
1061 if (!file_name)
1063 switch (ai_err)
1065 case AI_ERR_EOF:
1066 goto argv_iter_done;
1067 case AI_ERR_READ:
1068 error (0, errno, _("%s: read error"),
1069 quotearg_colon (files_from));
1070 ok = false;
1071 goto argv_iter_done;
1072 case AI_ERR_MEM:
1073 xalloc_die ();
1074 default:
1075 assert (!"unexpected error code from argv_iter");
1078 if (files_from && STREQ (files_from, "-") && STREQ (file_name, "-"))
1080 /* Give a better diagnostic in an unusual case:
1081 printf - | du --files0-from=- */
1082 error (0, 0, _("when reading file names from stdin, "
1083 "no file name of %s allowed"),
1084 quote (file_name));
1085 skip_file = true;
1088 /* Report and skip any empty file names before invoking fts.
1089 This works around a glitch in fts, which fails immediately
1090 (without looking at the other file names) when given an empty
1091 file name. */
1092 if (!file_name[0])
1094 /* Diagnose a zero-length file name. When it's one
1095 among many, knowing the record number may help.
1096 FIXME: currently print the record number only with
1097 --files0-from=FILE. Maybe do it for argv, too? */
1098 if (files_from == NULL)
1099 error (0, 0, "%s", _("invalid zero-length file name"));
1100 else
1102 /* Using the standard 'filename:line-number:' prefix here is
1103 not totally appropriate, since NUL is the separator, not NL,
1104 but it might be better than nothing. */
1105 unsigned long int file_number = argv_iter_n_args (ai);
1106 error (0, 0, "%s:%lu: %s", quotearg_colon (files_from),
1107 file_number, _("invalid zero-length file name"));
1109 skip_file = true;
1112 if (skip_file)
1113 ok = false;
1114 else
1116 temp_argv[0] = file_name;
1117 ok &= du_files (temp_argv, bit_flags);
1120 argv_iter_done:
1122 argv_iter_free (ai);
1123 di_set_free (di_files);
1124 di_set_free (di_mnt);
1126 if (files_from && (ferror (stdin) || fclose (stdin) != 0) && ok)
1127 error (EXIT_FAILURE, 0, _("error reading %s"), quote (files_from));
1129 if (print_grand_total)
1130 print_size (&tot_dui, _("total"));
1132 return ok ? EXIT_SUCCESS : EXIT_FAILURE;