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