*** empty log message ***
[platform/upstream/coreutils.git] / src / du.c
1 /* du -- summarize disk usage
2    Copyright (C) 1988-1991, 1995-2006 Free Software Foundation, Inc.
3
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 2, or (at your option)
7    any later version.
8
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.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software Foundation,
16    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
17
18 /* Differences from the Unix du:
19    * Doesn't simply ignore the names of regular files given as arguments
20      when -a is given.
21
22    By tege@sics.se, Torbjorn Granlund,
23    and djm@ai.mit.edu, David MacKenzie.
24    Variable blocks added by lm@sgi.com and eggert@twinsun.com.
25    Rewritten to use nftw, then to use fts by Jim Meyering.  */
26
27 #include <config.h>
28 #include <stdio.h>
29 #include <getopt.h>
30 #include <sys/types.h>
31 #include <assert.h>
32 #include "system.h"
33 #include "argmatch.h"
34 #include "dirname.h" /* for strip_trailing_slashes */
35 #include "error.h"
36 #include "exclude.h"
37 #include "fprintftime.h"
38 #include "hash.h"
39 #include "human.h"
40 #include "inttostr.h"
41 #include "quote.h"
42 #include "quotearg.h"
43 #include "readtokens0.h"
44 #include "same.h"
45 #include "stat-time.h"
46 #include "xfts.h"
47 #include "xstrtol.h"
48
49 extern bool fts_debug;
50
51 /* The official name of this program (e.g., no `g' prefix).  */
52 #define PROGRAM_NAME "du"
53
54 #define AUTHORS \
55   "Torbjorn Granlund", "David MacKenzie, Paul Eggert", "Jim Meyering"
56
57 #if DU_DEBUG
58 # define FTS_CROSS_CHECK(Fts) fts_cross_check (Fts)
59 # define DEBUG_OPT "d"
60 #else
61 # define FTS_CROSS_CHECK(Fts)
62 # define DEBUG_OPT
63 #endif
64
65 /* Initial size of the hash table.  */
66 #define INITIAL_TABLE_SIZE 103
67
68 /* Hash structure for inode and device numbers.  The separate entry
69    structure makes it easier to rehash "in place".  */
70
71 struct entry
72 {
73   ino_t st_ino;
74   dev_t st_dev;
75 };
76
77 /* A set of dev/ino pairs.  */
78 static Hash_table *htab;
79
80 /* Define a class for collecting directory information. */
81
82 struct duinfo
83 {
84   /* Size of files in directory.  */
85   uintmax_t size;
86
87   /* Latest time stamp found.  If tmax.tv_sec == TYPE_MINIMUM (time_t)
88      && tmax.tv_nsec < 0, no time stamp has been found.  */
89   struct timespec tmax;
90 };
91
92 /* Initialize directory data.  */
93 static inline void
94 duinfo_init (struct duinfo *a)
95 {
96   a->size = 0;
97   a->tmax.tv_sec = TYPE_MINIMUM (time_t);
98   a->tmax.tv_nsec = -1;
99 }
100
101 /* Set directory data.  */
102 static inline void
103 duinfo_set (struct duinfo *a, uintmax_t size, struct timespec tmax)
104 {
105   a->size = size;
106   a->tmax = tmax;
107 }
108
109 /* Accumulate directory data.  */
110 static inline void
111 duinfo_add (struct duinfo *a, struct duinfo const *b)
112 {
113   a->size += b->size;
114   if (timespec_cmp (a->tmax, b->tmax) < 0)
115     a->tmax = b->tmax;
116 }
117
118 /* A structure for per-directory level information.  */
119 struct dulevel
120 {
121   /* Entries in this directory.  */
122   struct duinfo ent;
123
124   /* Total for subdirectories.  */
125   struct duinfo subdir;
126 };
127
128 /* Name under which this program was invoked.  */
129 char *program_name;
130
131 /* If true, display counts for all files, not just directories.  */
132 static bool opt_all = false;
133
134 /* If true, rather than using the disk usage of each file,
135    use the apparent size (a la stat.st_size).  */
136 static bool apparent_size = false;
137
138 /* If true, count each hard link of files with multiple links.  */
139 static bool opt_count_all = false;
140
141 /* If true, output the NUL byte instead of a newline at the end of each line. */
142 static bool opt_nul_terminate_output = false;
143
144 /* If true, print a grand total at the end.  */
145 static bool print_grand_total = false;
146
147 /* If nonzero, do not add sizes of subdirectories.  */
148 static bool opt_separate_dirs = false;
149
150 /* Show the total for each directory (and file if --all) that is at
151    most MAX_DEPTH levels down from the root of the hierarchy.  The root
152    is at level 0, so `du --max-depth=0' is equivalent to `du -s'.  */
153 static size_t max_depth = SIZE_MAX;
154
155 /* Human-readable options for output.  */
156 static int human_output_opts;
157
158 /* If true, print most recently modified date, using the specified format.  */
159 static bool opt_time = false;
160
161 /* Type of time to display. controlled by --time.  */
162
163 enum time_type
164   {
165     time_mtime,                 /* default */
166     time_ctime,
167     time_atime
168   };
169
170 static enum time_type time_type = time_mtime;
171
172 /* User specified date / time style */
173 static char const *time_style = NULL;
174
175 /* Format used to display date / time. Controlled by --time-style */
176 static char const *time_format = NULL;
177
178 /* The units to use when printing sizes.  */
179 static uintmax_t output_block_size;
180
181 /* File name patterns to exclude.  */
182 static struct exclude *exclude;
183
184 /* Grand total size of all args, in bytes. Also latest modified date. */
185 static struct duinfo tot_dui;
186
187 #define IS_DIR_TYPE(Type)       \
188   ((Type) == FTS_DP             \
189    || (Type) == FTS_DNR)
190
191 /* For long options that have no equivalent short option, use a
192    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
193 enum
194 {
195   APPARENT_SIZE_OPTION = CHAR_MAX + 1,
196   EXCLUDE_OPTION,
197   FILES0_FROM_OPTION,
198   HUMAN_SI_OPTION,
199
200   /* FIXME: --kilobytes is deprecated (but not -k); remove in late 2006 */
201   KILOBYTES_LONG_OPTION,
202
203   MAX_DEPTH_OPTION,
204
205   /* FIXME: --megabytes is deprecated (but not -m); remove in late 2006 */
206   MEGABYTES_LONG_OPTION,
207
208   TIME_OPTION,
209   TIME_STYLE_OPTION
210 };
211
212 static struct option const long_options[] =
213 {
214   {"all", no_argument, NULL, 'a'},
215   {"apparent-size", no_argument, NULL, APPARENT_SIZE_OPTION},
216   {"block-size", required_argument, NULL, 'B'},
217   {"bytes", no_argument, NULL, 'b'},
218   {"count-links", no_argument, NULL, 'l'},
219   {"dereference", no_argument, NULL, 'L'},
220   {"dereference-args", no_argument, NULL, 'D'},
221   {"exclude", required_argument, NULL, EXCLUDE_OPTION},
222   {"exclude-from", required_argument, NULL, 'X'},
223   {"files0-from", required_argument, NULL, FILES0_FROM_OPTION},
224   {"human-readable", no_argument, NULL, 'h'},
225   {"si", no_argument, NULL, HUMAN_SI_OPTION},
226   {"kilobytes", no_argument, NULL, KILOBYTES_LONG_OPTION},
227   {"max-depth", required_argument, NULL, MAX_DEPTH_OPTION},
228   {"null", no_argument, NULL, '0'},
229   {"megabytes", no_argument, NULL, MEGABYTES_LONG_OPTION},
230   {"no-dereference", no_argument, NULL, 'P'},
231   {"one-file-system", no_argument, NULL, 'x'},
232   {"separate-dirs", no_argument, NULL, 'S'},
233   {"summarize", no_argument, NULL, 's'},
234   {"total", no_argument, NULL, 'c'},
235   {"time", optional_argument, NULL, TIME_OPTION},
236   {"time-style", required_argument, NULL, TIME_STYLE_OPTION},
237   {GETOPT_HELP_OPTION_DECL},
238   {GETOPT_VERSION_OPTION_DECL},
239   {NULL, 0, NULL, 0}
240 };
241
242 static char const *const time_args[] =
243 {
244   "atime", "access", "use", "ctime", "status", NULL
245 };
246 static enum time_type const time_types[] =
247 {
248   time_atime, time_atime, time_atime, time_ctime, time_ctime
249 };
250 ARGMATCH_VERIFY (time_args, time_types);
251
252 /* `full-iso' uses full ISO-style dates and times.  `long-iso' uses longer
253    ISO-style time stamps, though shorter than `full-iso'.  `iso' uses shorter
254    ISO-style time stamps.  */
255 enum time_style
256   {
257     full_iso_time_style,       /* --time-style=full-iso */
258     long_iso_time_style,       /* --time-style=long-iso */
259     iso_time_style             /* --time-style=iso */
260   };
261
262 static char const *const time_style_args[] =
263 {
264   "full-iso", "long-iso", "iso", NULL
265 };
266 static enum time_style const time_style_types[] =
267 {
268   full_iso_time_style, long_iso_time_style, iso_time_style
269 };
270 ARGMATCH_VERIFY (time_style_args, time_style_types);
271
272 void
273 usage (int status)
274 {
275   if (status != EXIT_SUCCESS)
276     fprintf (stderr, _("Try `%s --help' for more information.\n"),
277              program_name);
278   else
279     {
280       printf (_("\
281 Usage: %s [OPTION]... [FILE]...\n\
282   or:  %s [OPTION]... --files0-from=F\n\
283 "), program_name, program_name);
284       fputs (_("\
285 Summarize disk usage of each FILE, recursively for directories.\n\
286 \n\
287 "), stdout);
288       fputs (_("\
289 Mandatory arguments to long options are mandatory for short options too.\n\
290 "), stdout);
291       fputs (_("\
292   -a, --all             write counts for all files, not just directories\n\
293       --apparent-size   print apparent sizes, rather than disk usage; although\n\
294                           the apparent size is usually smaller, it may be\n\
295                           larger due to holes in (`sparse') files, internal\n\
296                           fragmentation, indirect blocks, and the like\n\
297   -B, --block-size=SIZE use SIZE-byte blocks\n\
298   -b, --bytes           equivalent to `--apparent-size --block-size=1'\n\
299   -c, --total           produce a grand total\n\
300   -D, --dereference-args  dereference FILEs that are symbolic links\n\
301 "), stdout);
302       fputs (_("\
303       --files0-from=F   summarize disk usage of the NUL-terminated file\n\
304                           names specified in file F\n\
305   -H                    like --si, but also evokes a warning; will soon\n\
306                           change to be equivalent to --dereference-args (-D)\n\
307   -h, --human-readable  print sizes in human readable format (e.g., 1K 234M 2G)\n\
308       --si              like -h, but use powers of 1000 not 1024\n\
309   -k                    like --block-size=1K\n\
310   -l, --count-links     count sizes many times if hard linked\n\
311   -m                    like --block-size=1M\n\
312 "), stdout);
313       fputs (_("\
314   -L, --dereference     dereference all symbolic links\n\
315   -P, --no-dereference  don't follow any symbolic links (this is the default)\n\
316   -0, --null            end each output line with 0 byte rather than newline\n\
317   -S, --separate-dirs   do not include size of subdirectories\n\
318   -s, --summarize       display only a total for each argument\n\
319 "), stdout);
320       fputs (_("\
321   -x, --one-file-system  skip directories on different file systems\n\
322   -X FILE, --exclude-from=FILE  Exclude files that match any pattern in FILE.\n\
323       --exclude=PATTERN Exclude files that match PATTERN.\n\
324       --max-depth=N     print the total for a directory (or file, with --all)\n\
325                           only if it is N or fewer levels below the command\n\
326                           line argument;  --max-depth=0 is the same as\n\
327                           --summarize\n\
328 "), stdout);
329       fputs (_("\
330       --time            show time of the last modification of any file in the\n\
331                           directory, or any of its subdirectories\n\
332       --time=WORD       show time as WORD instead of modification time:\n\
333                           atime, access, use, ctime or status\n\
334       --time-style=STYLE show times using style STYLE:\n\
335                           full-iso, long-iso, iso, +FORMAT\n\
336                           FORMAT is interpreted like `date'\n\
337 "), stdout);
338       fputs (HELP_OPTION_DESCRIPTION, stdout);
339       fputs (VERSION_OPTION_DESCRIPTION, stdout);
340       fputs (_("\n\
341 SIZE may be (or may be an integer optionally followed by) one of following:\n\
342 kB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
343 "), stdout);
344       printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
345     }
346   exit (status);
347 }
348
349 static size_t
350 entry_hash (void const *x, size_t table_size)
351 {
352   struct entry const *p = x;
353
354   /* Ignoring the device number here should be fine.  */
355   /* The cast to uintmax_t prevents negative remainders
356      if st_ino is negative.  */
357   return (uintmax_t) p->st_ino % table_size;
358 }
359
360 /* Compare two dev/ino pairs.  Return true if they are the same.  */
361 static bool
362 entry_compare (void const *x, void const *y)
363 {
364   struct entry const *a = x;
365   struct entry const *b = y;
366   return SAME_INODE (*a, *b) ? true : false;
367 }
368
369 /* Try to insert the INO/DEV pair into the global table, HTAB.
370    Return true if the pair is successfully inserted,
371    false if the pair is already in the table.  */
372 static bool
373 hash_ins (ino_t ino, dev_t dev)
374 {
375   struct entry *ent;
376   struct entry *ent_from_table;
377
378   ent = xmalloc (sizeof *ent);
379   ent->st_ino = ino;
380   ent->st_dev = dev;
381
382   ent_from_table = hash_insert (htab, ent);
383   if (ent_from_table == NULL)
384     {
385       /* Insertion failed due to lack of memory.  */
386       xalloc_die ();
387     }
388
389   if (ent_from_table == ent)
390     {
391       /* Insertion succeeded.  */
392       return true;
393     }
394
395   /* That pair is already in the table, so ENT was not inserted.  Free it.  */
396   free (ent);
397
398   return false;
399 }
400
401 /* Initialize the hash table.  */
402 static void
403 hash_init (void)
404 {
405   htab = hash_initialize (INITIAL_TABLE_SIZE, NULL,
406                           entry_hash, entry_compare, free);
407   if (htab == NULL)
408     xalloc_die ();
409 }
410
411 /* FIXME: this code is nearly identical to code in date.c  */
412 /* Display the date and time in WHEN according to the format specified
413    in FORMAT.  */
414
415 static void
416 show_date (const char *format, struct timespec when)
417 {
418   struct tm *tm = localtime (&when.tv_sec);
419   if (! tm)
420     {
421       char buf[INT_BUFSIZE_BOUND (intmax_t)];
422       error (0, 0, _("time %s is out of range"),
423              (TYPE_SIGNED (time_t)
424               ? imaxtostr (when.tv_sec, buf)
425               : umaxtostr (when.tv_sec, buf)));
426       fputs (buf, stdout);
427       return;
428     }
429
430   fprintftime (stdout, format, tm, 0, when.tv_nsec);
431 }
432
433 /* Print N_BYTES.  Convert it to a readable value before printing.  */
434
435 static void
436 print_only_size (uintmax_t n_bytes)
437 {
438   char buf[LONGEST_HUMAN_READABLE + 1];
439   fputs (human_readable (n_bytes, buf, human_output_opts,
440                          1, output_block_size), stdout);
441 }
442
443 /* Print size (and optionally time) indicated by *PDUI, followed by STRING.  */
444
445 static void
446 print_size (const struct duinfo *pdui, const char *string)
447 {
448   print_only_size (pdui->size);
449   if (opt_time)
450     {
451       putchar ('\t');
452       show_date (time_format, pdui->tmax);
453     }
454   printf ("\t%s%c", string, opt_nul_terminate_output ? '\0' : '\n');
455   fflush (stdout);
456 }
457
458 /* This function is called once for every file system object that fts
459    encounters.  fts does a depth-first traversal.  This function knows
460    that and accumulates per-directory totals based on changes in
461    the depth of the current entry.  It returns true on success.  */
462
463 static bool
464 process_file (FTS *fts, FTSENT *ent)
465 {
466   bool ok;
467   struct duinfo dui;
468   struct duinfo dui_to_print;
469   size_t level;
470   static size_t prev_level;
471   static size_t n_alloc;
472   /* First element of the structure contains:
473      The sum of the st_size values of all entries in the single directory
474      at the corresponding level.  Although this does include the st_size
475      corresponding to each subdirectory, it does not include the size of
476      any file in a subdirectory. Also corresponding last modified date.
477      Second element of the structure contains:
478      The sum of the sizes of all entries in the hierarchy at or below the
479      directory at the specified level.  */
480   static struct dulevel *dulvl;
481   bool print = true;
482
483   const char *file = ent->fts_path;
484   const struct stat *sb = ent->fts_statp;
485   bool skip;
486
487   /* If necessary, set FTS_SKIP before returning.  */
488   skip = excluded_file_name (exclude, ent->fts_path);
489   if (skip)
490     fts_set (fts, ent, FTS_SKIP);
491
492   switch (ent->fts_info)
493     {
494     case FTS_NS:
495       error (0, ent->fts_errno, _("cannot access %s"), quote (file));
496       return false;
497
498     case FTS_ERR:
499       /* if (S_ISDIR (ent->fts_statp->st_mode) && FIXME */
500       error (0, ent->fts_errno, _("%s"), quote (file));
501       return false;
502
503     case FTS_DNR:
504       /* Don't return just yet, since although the directory is not readable,
505          we were able to stat it, so we do have a size.  */
506       error (0, ent->fts_errno, _("cannot read directory %s"), quote (file));
507       ok = false;
508       break;
509
510     default:
511       ok = true;
512       break;
513     }
514
515   /* If this is the first (pre-order) encounter with a directory,
516      or if it's the second encounter for a skipped directory, then
517      return right away.  */
518   if (ent->fts_info == FTS_D || skip)
519     return ok;
520
521   /* If the file is being excluded or if it has already been counted
522      via a hard link, then don't let it contribute to the sums.  */
523   if (skip
524       || (!opt_count_all
525           && ! S_ISDIR (sb->st_mode)
526           && 1 < sb->st_nlink
527           && ! hash_ins (sb->st_ino, sb->st_dev)))
528     {
529       /* Note that we must not simply return here.
530          We still have to update prev_level and maybe propagate
531          some sums up the hierarchy.  */
532       duinfo_init (&dui);
533       print = false;
534     }
535   else
536     {
537       duinfo_set (&dui,
538                   (apparent_size
539                    ? sb->st_size
540                    : (uintmax_t) ST_NBLOCKS (*sb) * ST_NBLOCKSIZE),
541                   (time_type == time_mtime ? get_stat_mtime (sb)
542                    : time_type == time_atime ? get_stat_atime (sb)
543                    : get_stat_ctime (sb)));
544     }
545
546   level = ent->fts_level;
547   dui_to_print = dui;
548
549   if (n_alloc == 0)
550     {
551       n_alloc = level + 10;
552       dulvl = xcalloc (n_alloc, sizeof *dulvl);
553     }
554   else
555     {
556       if (level == prev_level)
557         {
558           /* This is usually the most common case.  Do nothing.  */
559         }
560       else if (level > prev_level)
561         {
562           /* Descending the hierarchy.
563              Clear the accumulators for *all* levels between prev_level
564              and the current one.  The depth may change dramatically,
565              e.g., from 1 to 10.  */
566           size_t i;
567
568           if (n_alloc <= level)
569             {
570               dulvl = xnrealloc (dulvl, level, 2 * sizeof *dulvl);
571               n_alloc = level * 2;
572             }
573
574           for (i = prev_level + 1; i <= level; i++)
575             {
576               duinfo_init (&dulvl[i].ent);
577               duinfo_init (&dulvl[i].subdir);
578             }
579         }
580       else /* level < prev_level */
581         {
582           /* Ascending the hierarchy.
583              Process a directory only after all entries in that
584              directory have been processed.  When the depth decreases,
585              propagate sums from the children (prev_level) to the parent.
586              Here, the current level is always one smaller than the
587              previous one.  */
588           assert (level == prev_level - 1);
589           duinfo_add (&dui_to_print, &dulvl[prev_level].ent);
590           if (!opt_separate_dirs)
591             duinfo_add (&dui_to_print, &dulvl[prev_level].subdir);
592           duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].ent);
593           duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].subdir);
594         }
595     }
596
597   prev_level = level;
598
599   /* Let the size of a directory entry contribute to the total for the
600      containing directory, unless --separate-dirs (-S) is specified.  */
601   if ( ! (opt_separate_dirs && IS_DIR_TYPE (ent->fts_info)))
602     duinfo_add (&dulvl[level].ent, &dui);
603
604   /* Even if this directory is unreadable or we can't chdir into it,
605      do let its size contribute to the total, ... */
606   duinfo_add (&tot_dui, &dui);
607
608   /* ... but don't print out a total for it, since without the size(s)
609      of any potential entries, it could be very misleading.  */
610   if (ent->fts_info == FTS_DNR)
611     return ok;
612
613   /* If we're not counting an entry, e.g., because it's a hard link
614      to a file we've already counted (and --count-links), then don't
615      print a line for it.  */
616   if (!print)
617     return ok;
618
619   if ((IS_DIR_TYPE (ent->fts_info) && level <= max_depth)
620       || ((opt_all && level <= max_depth) || level == 0))
621     print_size (&dui_to_print, file);
622
623   return ok;
624 }
625
626 /* Recursively print the sizes of the directories (and, if selected, files)
627    named in FILES, the last entry of which is NULL.
628    BIT_FLAGS controls how fts works.
629    Return true if successful.  */
630
631 static bool
632 du_files (char **files, int bit_flags)
633 {
634   bool ok = true;
635
636   if (*files)
637     {
638       FTS *fts = xfts_open (files, bit_flags, NULL);
639
640       while (1)
641         {
642           FTSENT *ent;
643
644           ent = fts_read (fts);
645           if (ent == NULL)
646             {
647               if (errno != 0)
648                 {
649                   /* FIXME: try to give a better message  */
650                   error (0, errno, _("fts_read failed"));
651                   ok = false;
652                 }
653               break;
654             }
655           FTS_CROSS_CHECK (fts);
656
657           ok &= process_file (fts, ent);
658         }
659
660       /* Ignore failure, since the only way it can do so is in failing to
661          return to the original directory, and since we're about to exit,
662          that doesn't matter.  */
663       fts_close (fts);
664     }
665
666   if (print_grand_total)
667     print_size (&tot_dui, _("total"));
668
669   return ok;
670 }
671
672 int
673 main (int argc, char **argv)
674 {
675   int c;
676   char *cwd_only[2];
677   bool max_depth_specified = false;
678   char **files;
679   bool ok = true;
680   char *files_from = NULL;
681   struct Tokens tok;
682
683   /* Bit flags that control how fts works.  */
684   int bit_flags = FTS_TIGHT_CYCLE_CHECK;
685
686   /* Select one of the three FTS_ options that control if/when
687      to follow a symlink.  */
688   int symlink_deref_bits = FTS_PHYSICAL;
689
690   /* If true, display only a total for each argument. */
691   bool opt_summarize_only = false;
692
693   cwd_only[0] = ".";
694   cwd_only[1] = NULL;
695
696   initialize_main (&argc, &argv);
697   program_name = argv[0];
698   setlocale (LC_ALL, "");
699   bindtextdomain (PACKAGE, LOCALEDIR);
700   textdomain (PACKAGE);
701
702   atexit (close_stdout);
703
704   exclude = new_exclude ();
705
706   human_output_opts = human_options (getenv ("DU_BLOCK_SIZE"), false,
707                                      &output_block_size);
708
709   while ((c = getopt_long (argc, argv, DEBUG_OPT "0abchHklmsxB:DLPSX:",
710                            long_options, NULL)) != -1)
711     {
712       switch (c)
713         {
714 #if DU_DEBUG
715         case 'd':
716           fts_debug = true;
717           break;
718 #endif
719
720         case '0':
721           opt_nul_terminate_output = true;
722           break;
723
724         case 'a':
725           opt_all = true;
726           break;
727
728         case APPARENT_SIZE_OPTION:
729           apparent_size = true;
730           break;
731
732         case 'b':
733           apparent_size = true;
734           human_output_opts = 0;
735           output_block_size = 1;
736           break;
737
738         case 'c':
739           print_grand_total = true;
740           break;
741
742         case 'h':
743           human_output_opts = human_autoscale | human_SI | human_base_1024;
744           output_block_size = 1;
745           break;
746
747         case 'H':  /* FIXME: remove warning and move this "case 'H'" to
748                       precede --dereference-args in late 2006.  */
749           error (0, 0, _("WARNING: use --si, not -H; the meaning of the -H\
750  option will soon\nchange to be the same as that of --dereference-args (-D)"));
751           /* fall through */
752         case HUMAN_SI_OPTION:
753           human_output_opts = human_autoscale | human_SI;
754           output_block_size = 1;
755           break;
756
757         case KILOBYTES_LONG_OPTION:
758           error (0, 0,
759                  _("the --kilobytes option is deprecated; use -k instead"));
760           /* fall through */
761         case 'k':
762           human_output_opts = 0;
763           output_block_size = 1024;
764           break;
765
766         case MAX_DEPTH_OPTION:          /* --max-depth=N */
767           {
768             unsigned long int tmp_ulong;
769             if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK
770                 && tmp_ulong <= SIZE_MAX)
771               {
772                 max_depth_specified = true;
773                 max_depth = tmp_ulong;
774               }
775             else
776               {
777                 error (0, 0, _("invalid maximum depth %s"),
778                        quote (optarg));
779                 ok = false;
780               }
781           }
782           break;
783
784         case MEGABYTES_LONG_OPTION:
785           error (0, 0,
786                  _("the --megabytes option is deprecated; use -m instead"));
787           /* fall through */
788         case 'm':
789           human_output_opts = 0;
790           output_block_size = 1024 * 1024;
791           break;
792
793         case 'l':
794           opt_count_all = true;
795           break;
796
797         case 's':
798           opt_summarize_only = true;
799           break;
800
801         case 'x':
802           bit_flags |= FTS_XDEV;
803           break;
804
805         case 'B':
806           human_output_opts = human_options (optarg, true, &output_block_size);
807           break;
808
809         case 'D': /* This will eventually be 'H' (-H), too.  */
810           symlink_deref_bits = FTS_COMFOLLOW | FTS_PHYSICAL;
811           break;
812
813         case 'L': /* --dereference */
814           symlink_deref_bits = FTS_LOGICAL;
815           break;
816
817         case 'P': /* --no-dereference */
818           symlink_deref_bits = FTS_PHYSICAL;
819           break;
820
821         case 'S':
822           opt_separate_dirs = true;
823           break;
824
825         case 'X':
826           if (add_exclude_file (add_exclude, exclude, optarg,
827                                 EXCLUDE_WILDCARDS, '\n'))
828             {
829               error (0, errno, "%s", quotearg_colon (optarg));
830               ok = false;
831             }
832           break;
833
834         case FILES0_FROM_OPTION:
835           files_from = optarg;
836           break;
837
838         case EXCLUDE_OPTION:
839           add_exclude (exclude, optarg, EXCLUDE_WILDCARDS);
840           break;
841
842         case TIME_OPTION:
843           opt_time = true;
844           time_type =
845             (optarg
846              ? XARGMATCH ("--time", optarg, time_args, time_types)
847              : time_mtime);
848           break;
849
850         case TIME_STYLE_OPTION:
851           time_style = optarg;
852           break;
853
854         case_GETOPT_HELP_CHAR;
855
856         case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
857
858         default:
859           ok = false;
860         }
861     }
862
863   if (!ok)
864     usage (EXIT_FAILURE);
865
866   if (opt_all & opt_summarize_only)
867     {
868       error (0, 0, _("cannot both summarize and show all entries"));
869       usage (EXIT_FAILURE);
870     }
871
872   if (opt_summarize_only && max_depth_specified && max_depth == 0)
873     {
874       error (0, 0,
875              _("warning: summarizing is the same as using --max-depth=0"));
876     }
877
878   if (opt_summarize_only && max_depth_specified && max_depth != 0)
879     {
880       unsigned long int d = max_depth;
881       error (0, 0, _("warning: summarizing conflicts with --max-depth=%lu"), d);
882       usage (EXIT_FAILURE);
883     }
884
885   if (opt_summarize_only)
886     max_depth = 0;
887
888   /* Process time style if printing last times.  */
889   if (opt_time)
890     {
891       if (! time_style)
892         {
893           time_style = getenv ("TIME_STYLE");
894
895           /* Ignore TIMESTYLE="locale", for compatibility with ls.  */
896           if (! time_style || STREQ (time_style, "locale"))
897             time_style = "long-iso";
898           else if (*time_style == '+')
899             {
900               /* Ignore anything after a newline, for compatibility
901                  with ls.  */
902               char *p = strchr (time_style, '\n');
903               if (p)
904                 *p = '\0';
905             }
906           else
907             {
908               /* Ignore "posix-" prefix, for compatibility with ls.  */
909               static char const posix_prefix[] = "posix-";
910               while (strncmp (time_style, posix_prefix, sizeof posix_prefix - 1)
911                      == 0)
912                 time_style += sizeof posix_prefix - 1;
913             }
914         }
915
916       if (*time_style == '+')
917         time_format = time_style + 1;
918       else
919         {
920           switch (XARGMATCH ("time style", time_style,
921                              time_style_args, time_style_types))
922             {
923             case full_iso_time_style:
924               time_format = "%Y-%m-%d %H:%M:%S.%N %z";
925               break;
926
927             case long_iso_time_style:
928               time_format = "%Y-%m-%d %H:%M";
929               break;
930
931             case iso_time_style:
932               time_format = "%Y-%m-%d";
933               break;
934             }
935         }
936     }
937
938   if (files_from)
939     {
940       /* When using --files0-from=F, you may not specify any files
941          on the command-line.  */
942       if (optind < argc)
943         {
944           error (0, 0, _("extra operand %s"), quote (argv[optind]));
945           fprintf (stderr, "%s\n",
946                    _("File operands cannot be combined with --files0-from."));
947           usage (EXIT_FAILURE);
948         }
949
950       if (! (STREQ (files_from, "-") || freopen (files_from, "r", stdin)))
951         error (EXIT_FAILURE, errno, _("cannot open %s for reading"),
952                quote (files_from));
953
954       readtokens0_init (&tok);
955
956       if (! readtokens0 (stdin, &tok) || fclose (stdin) != 0)
957         error (EXIT_FAILURE, 0, _("cannot read file names from %s"),
958                quote (files_from));
959
960       files = tok.tok;
961     }
962   else
963     {
964       files = (optind < argc ? argv + optind : cwd_only);
965     }
966
967   /* Initialize the hash structure for inode numbers.  */
968   hash_init ();
969
970   /* Report and filter out any empty file names before invoking fts.
971      This works around a glitch in fts, which fails immediately
972      (without looking at the other file names) when given an empty
973      file name.  */
974   {
975     size_t i = 0;
976     size_t j;
977
978     for (j = 0; ; j++)
979       {
980         if (i != j)
981           files[i] = files[j];
982
983         if ( ! files[i])
984           break;
985
986         if (files[i][0])
987           i++;
988         else
989           {
990             if (files_from)
991               {
992                 /* Using the standard `filename:line-number:' prefix here is
993                    not totally appropriate, since NUL is the separator, not NL,
994                    but it might be better than nothing.  */
995                 unsigned long int file_number = j + 1;
996                 error (0, 0, "%s:%lu: %s", quotearg_colon (files_from),
997                        file_number, _("invalid zero-length file name"));
998               }
999             else
1000               error (0, 0, "%s", _("invalid zero-length file name"));
1001           }
1002       }
1003
1004     ok = (i == j);
1005   }
1006
1007   bit_flags |= symlink_deref_bits;
1008   ok &= du_files (files, bit_flags);
1009
1010   /* This isn't really necessary, but it does ensure we
1011      exercise this function.  */
1012   if (files_from)
1013     readtokens0_free (&tok);
1014
1015   hash_free (htab);
1016
1017   exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
1018 }