1 /* du -- summarize disk usage
2 Copyright (C) 1988, 1989, 1990, 1991, 1995 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 2, or (at your option)
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, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
18 /* Differences from the Unix du:
19 * Doesn't simply ignore the names of regular files given as arguments
22 -l Count the size of all files, even if they have appeared
23 already in another hard link.
24 -x Do not cross file-system boundaries during the recursion.
25 -c Write a grand total of all of the arguments after all
26 arguments have been processed. This can be used to find
27 out the disk usage of a directory, with some files excluded.
28 -k Print sizes in kilobytes instead of 512 byte blocks
29 (the default required by POSIX).
30 -b Print sizes in bytes.
31 -S Count the size of each directory separately, not including
32 the sizes of subdirectories.
33 -D Dereference only symbolic links given on the command line.
34 -L Dereference all symbolic links.
36 By tege@sics.se, Torbjorn Granlund,
37 and djm@ai.mit.edu, David MacKenzie. */
46 #include <sys/types.h>
52 /* Initial number of entries in each hash table entry's table of inodes. */
53 #define INITIAL_HASH_MODULE 100
55 /* Initial number of entries in the inode hash table. */
56 #define INITIAL_ENTRY_TAB_SIZE 70
58 /* Initial size to allocate for `path'. */
59 #define INITIAL_PATH_SIZE 100
61 /* Hash structure for inode and device numbers. The separate entry
62 structure makes it easier to rehash "in place". */
68 struct entry *coll_link;
71 /* Structure for a hash table for inode numbers. */
75 unsigned modulus; /* Size of the `hash' pointer vector. */
76 struct entry *entry_tab; /* Pointer to dynamically growing vector. */
77 unsigned entry_tab_size; /* Size of current `entry_tab' allocation. */
78 unsigned first_free_entry; /* Index in `entry_tab'. */
79 struct entry *hash[1]; /* Vector of pointers in `entry_tab'. */
89 /* Structure for dynamically resizable strings. */
93 unsigned alloc; /* Size of allocation for the text. */
94 unsigned length; /* Length of the text currently. */
95 char *text; /* Pointer to the text. */
96 } *string, stringstruct;
103 static int hash_insert ();
104 static int hash_insert2 ();
105 static long count_entry ();
106 static void du_files ();
107 static void hash_init ();
108 static void hash_reset ();
109 static void str_concatc ();
110 static void str_copyc ();
111 static void str_init ();
112 static void str_trunc ();
114 /* Name under which this program was invoked. */
117 /* If nonzero, display only a total for each argument. */
118 static int opt_summarize_only = 0;
120 /* If nonzero, display counts for all files, not just directories. */
121 static int opt_all = 0;
123 /* If nonzero, count each hard link of files with multiple links. */
124 static int opt_count_all = 0;
126 /* If nonzero, do not cross file-system boundaries. */
127 static int opt_one_file_system = 0;
129 /* If nonzero, print a grand total at the end. */
130 static int opt_combined_arguments = 0;
132 /* If nonzero, do not add sizes of subdirectories. */
133 static int opt_separate_dirs = 0;
135 /* If nonzero, dereference symlinks that are command line arguments. */
136 static int opt_dereference_arguments = 0;
140 size_blocks, /* 512-byte blocks. */
141 size_kilobytes, /* 1K blocks. */
142 size_bytes /* 1-byte blocks. */
145 /* The units to count in. */
146 static enum output_size output_size;
148 /* Accumulated path for file or directory being processed. */
151 /* Pointer to hash structure, used by the hash routines. */
152 static struct htab *htab;
154 /* Globally used stat buffer. */
155 static struct stat stat_buf;
157 /* A pointer to either lstat or stat, depending on whether
158 dereferencing of all symbolic links is to be done. */
159 static int (*xstat) ();
161 /* The exit status to use if we don't get any fatal errors. */
162 static int exit_status;
164 /* If non-zero, display usage information and exit. */
165 static int show_help;
167 /* If non-zero, print the version on standard output and exit. */
168 static int show_version;
170 /* Grand total size of all args. */
171 static long tot_size = 0L;
173 static struct option const long_options[] =
175 {"all", no_argument, &opt_all, 1},
176 {"bytes", no_argument, NULL, 'b'},
177 {"count-links", no_argument, &opt_count_all, 1},
178 {"dereference", no_argument, NULL, 'L'},
179 {"dereference-args", no_argument, &opt_dereference_arguments, 1},
180 {"kilobytes", no_argument, NULL, 'k'},
181 {"one-file-system", no_argument, &opt_one_file_system, 1},
182 {"separate-dirs", no_argument, &opt_separate_dirs, 1},
183 {"summarize", no_argument, &opt_summarize_only, 1},
184 {"total", no_argument, &opt_combined_arguments, 1},
185 {"help", no_argument, &show_help, 1},
186 {"version", no_argument, &show_version, 1},
192 struct saved_cwd *cwd;
194 static int have_working_fchdir = 1;
196 if (have_working_fchdir)
199 cwd->desc = open (".", O_RDONLY);
201 error (1, errno, "cannot open current directory");
203 /* On SunOS 4, fchdir returns EINVAL if accounting is enabled,
204 so we have to fall back to chdir. */
205 if (fchdir (cwd->desc))
211 have_working_fchdir = 0;
215 error (1, errno, "current directory");
219 #define fchdir(x) (abort (), 0)
220 have_working_fchdir = 0;
224 if (!have_working_fchdir)
227 cwd->name = xgetcwd ();
228 if (cwd->name == NULL)
229 error (1, errno, "cannot get current directory");
238 restore_cwd (cwd, dest, current)
239 const struct saved_cwd *cwd;
245 if (fchdir (cwd->desc))
246 error (1, errno, "cannot return to %s%s%s", dest,
247 (current ? " from " : ""),
248 (current ? current : ""));
250 else if (chdir (cwd->name) < 0)
252 error (1, errno, "%s", cwd->name);
257 usage (status, reason)
262 fprintf (status == 0 ? stdout : stderr, "%s: %s\n",
263 program_name, reason);
266 fprintf (stderr, "Try `%s --help' for more information.\n",
270 printf ("Usage: %s [OPTION]... [PATH]...\n", program_name);
273 -a, --all write counts for all files, not just directories\n\
274 -b, --bytes print size in bytes\n\
275 -c, --total produce a grand total\n\
276 -k, --kilobytes use 1024 blocks, not 512 despite POSIXLY_CORRECT\n\
277 -l, --count-links count sizes many times if hard linked\n\
278 -s, --summarize display only a total for each argument\n\
279 -x, --one-file-system skip directories on different filesystems\n\
280 -D, --dereference-args dereference PATHs when symbolic link\n\
281 -L, --dereference dereference all symbolic links\n\
282 -S, --separate-dirs do not include size of subdirectories\n\
283 --help display this help and exit\n\
284 --version output version information and exit\n");
300 program_name = argv[0];
302 output_size = getenv ("POSIXLY_CORRECT") ? size_blocks : size_kilobytes;
304 while ((c = getopt_long (argc, argv, "abcklsxDLS", long_options, (int *) 0))
309 case 0: /* Long option. */
317 output_size = size_bytes;
321 opt_combined_arguments = 1;
325 output_size = size_kilobytes;
333 opt_summarize_only = 1;
337 opt_one_file_system = 1;
341 opt_dereference_arguments = 1;
349 opt_separate_dirs = 1;
353 usage (2, (char *) 0);
359 printf ("%s\n", version_string);
366 if (opt_all && opt_summarize_only)
367 usage (2, "cannot both summarize and show all entries");
369 /* Initialize the hash structure for inode numbers. */
370 hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
372 str_init (&path, INITIAL_PATH_SIZE);
374 du_files (optind == argc ? cwd_only : argv + optind);
379 /* Recursively print the sizes of the directories (and, if selected, files)
380 named in FILES, the last entry of which is NULL. */
386 struct saved_cwd cwd;
387 ino_t initial_ino; /* Initial directory's inode. */
388 dev_t initial_dev; /* Initial directory's device. */
389 int i; /* Index in FILES. */
393 /* Remember the inode and device number of the current directory. */
394 if (stat (".", &stat_buf))
395 error (1, errno, "current directory");
396 initial_ino = stat_buf.st_ino;
397 initial_dev = stat_buf.st_dev;
399 for (i = 0; files[i]; i++)
406 /* Delete final slash in the argument, unless the slash is alone. */
407 s = strlen (arg) - 1;
413 str_copyc (path, arg);
415 else if (arg[0] == '/')
416 str_trunc (path, 0); /* Null path for root directory. */
418 str_copyc (path, arg);
420 if (!opt_combined_arguments)
423 count_entry (arg, 1, 0);
425 /* chdir if `count_entry' has changed the working directory. */
426 if (stat (".", &stat_buf))
427 error (1, errno, ".");
428 if (stat_buf.st_ino != initial_ino || stat_buf.st_dev != initial_dev)
430 restore_cwd (&cwd, "starting directory", NULL);
434 if (opt_combined_arguments)
436 printf ("%ld\ttotal\n", output_size == size_bytes ? tot_size
437 : convert_blocks (tot_size, output_size == size_kilobytes));
441 if (cwd.name != NULL)
445 /* Print (if appropriate) and return the size
446 (in units determined by `output_size') of file or directory ENT.
447 TOP is one for external calls, zero for recursive calls.
448 LAST_DEV is the device that the parent directory of ENT is on. */
451 count_entry (ent, top, last_dev)
458 if (((top && opt_dereference_arguments)
459 ? stat (ent, &stat_buf)
460 : (*xstat) (ent, &stat_buf)) < 0)
462 error (0, errno, "%s", path->text);
468 && stat_buf.st_nlink > 1
469 && hash_insert (stat_buf.st_ino, stat_buf.st_dev))
470 return 0; /* Have counted this already. */
472 if (output_size == size_bytes)
473 size = stat_buf.st_size;
475 size = ST_NBLOCKS (stat_buf);
479 if (S_ISDIR (stat_buf.st_mode))
485 struct saved_cwd cwd;
489 dir_dev = stat_buf.st_dev;
491 if (opt_one_file_system && !top && last_dev != dir_dev)
492 return 0; /* Don't enter a new file system. */
495 # define S_ISDIR(s) 0
497 /* If we're dereferencing symlinks and we're about to chdir through
498 a symlink, remember the current directory so we can return to it
499 later. In other cases, chdir ("..") works fine. */
500 through_symlink = (xstat == stat
501 && lstat (ent, &e_buf) == 0
502 && S_ISLNK (e_buf.st_mode));
508 error (0, errno, "cannot change to directory %s", path->text);
514 name_space = savedir (".", stat_buf.st_size);
515 if (name_space == NULL)
519 error (0, errno, "%s", path->text);
522 restore_cwd (&cwd, "..", path->text);
523 if (cwd.name != NULL)
526 else if (chdir ("..") < 0)
527 error (1, errno, "cannot change to `..' from directory %s",
533 error (1, 0, "virtual memory exhausted");
536 /* Remember the current path. */
538 str_concatc (path, "/");
539 pathlen = path->length;
544 str_concatc (path, namep);
546 size += count_entry (namep, 0, dir_dev);
548 str_trunc (path, pathlen);
549 namep += strlen (namep) + 1;
554 restore_cwd (&cwd, "..", path->text);
555 if (cwd.name != NULL)
558 else if (chdir ("..") < 0)
559 error (1, errno, "cannot change to `..' from directory %s", path->text);
561 str_trunc (path, pathlen - 1); /* Remove the "/" we added. */
562 if (!opt_summarize_only || top)
564 printf ("%ld\t%s\n", output_size == size_bytes ? size
565 : convert_blocks (size, output_size == size_kilobytes),
566 path->length > 0 ? path->text : "/");
569 return opt_separate_dirs ? 0 : size;
571 else if (opt_all || top)
573 /* FIXME: make this an option. */
574 int print_only_dir_size = 0;
575 if (!print_only_dir_size)
577 printf ("%ld\t%s\n", output_size == size_bytes ? size
578 : convert_blocks (size, output_size == size_kilobytes),
587 /* Allocate space for the hash structures, and set the global
588 variable `htab' to point to it. The initial hash module is specified in
589 MODULUS, and the number of entries are specified in ENTRY_TAB_SIZE. (The
590 hash structure will be rebuilt when ENTRY_TAB_SIZE entries have been
591 inserted, and MODULUS and ENTRY_TAB_SIZE in the global `htab' will be
595 hash_init (modulus, entry_tab_size)
597 unsigned entry_tab_size;
601 htab_r = (struct htab *)
602 xmalloc (sizeof (struct htab) + sizeof (struct entry *) * modulus);
604 htab_r->entry_tab = (struct entry *)
605 xmalloc (sizeof (struct entry) * entry_tab_size);
607 htab_r->modulus = modulus;
608 htab_r->entry_tab_size = entry_tab_size;
614 /* Reset the hash structure in the global variable `htab' to
615 contain no entries. */
623 htab->first_free_entry = 0;
626 for (i = htab->modulus; i > 0; i--)
630 /* Insert an item (inode INO and device DEV) in the hash
631 structure in the global variable `htab', if an entry with the same data
632 was not found already. Return zero if the item was inserted and non-zero
636 hash_insert (ino, dev)
640 struct htab *htab_r = htab; /* Initially a copy of the global `htab'. */
642 if (htab_r->first_free_entry >= htab_r->entry_tab_size)
647 unsigned entry_tab_size;
649 /* Increase the number of hash entries, and re-hash the data.
650 The method of shrimping and increasing is made to compactify
651 the heap. If twice as much data would be allocated
652 straightforwardly, we would never re-use a byte of memory. */
654 /* Let `htab' shrimp. Keep only the header, not the pointer vector. */
656 htab_r = (struct htab *)
657 xrealloc ((char *) htab_r, sizeof (struct htab));
659 modulus = 2 * htab_r->modulus;
660 entry_tab_size = 2 * htab_r->entry_tab_size;
662 /* Increase the number of possible entries. */
664 htab_r->entry_tab = (struct entry *)
665 xrealloc ((char *) htab_r->entry_tab,
666 sizeof (struct entry) * entry_tab_size);
668 /* Increase the size of htab again. */
670 htab_r = (struct htab *)
671 xrealloc ((char *) htab_r,
672 sizeof (struct htab) + sizeof (struct entry *) * modulus);
674 htab_r->modulus = modulus;
675 htab_r->entry_tab_size = entry_tab_size;
678 i = htab_r->first_free_entry;
680 /* Make the increased hash table empty. The entries are still
681 available in htab->entry_tab. */
685 /* Go through the entries and install them in the pointer vector
686 htab->hash. The items are actually inserted in htab->entry_tab at
687 the position where they already are. The htab->coll_link need
688 however be updated. Could be made a little more efficient. */
690 for (ep = htab_r->entry_tab; i > 0; i--)
692 hash_insert2 (htab_r, ep->ino, ep->dev);
697 return hash_insert2 (htab_r, ino, dev);
700 /* Insert INO and DEV in the hash structure HTAB, if not
701 already present. Return zero if inserted and non-zero if it
705 hash_insert2 (htab, ino, dev)
710 struct entry **hp, *ep2, *ep;
711 hp = &htab->hash[ino % htab->modulus];
720 /* Search for an entry with the same data. */
724 if (ep->ino == ino && ep->dev == dev)
725 return 1; /* Found an entry with the same data. */
730 /* Did not find it. */
734 ep = *hp = &htab->entry_tab[htab->first_free_entry++];
737 ep->coll_link = ep2; /* `ep2' is NULL if no collision. */
742 /* Initialize the struct string S1 for holding SIZE characters. */
751 s = (string) xmalloc (sizeof (stringstruct));
752 s->text = xmalloc (size + 1);
759 ensure_space (s, size)
765 s->text = xrealloc (s->text, size + 1);
770 /* Assign the null-terminated C-string CSTR to S1. */
777 unsigned l = strlen (cstr);
778 ensure_space (s1, l);
779 strcpy (s1->text, cstr);
784 str_concatc (s1, cstr)
788 unsigned l1 = s1->length;
789 unsigned l2 = strlen (cstr);
790 unsigned l = l1 + l2;
792 ensure_space (s1, l);
793 strcpy (s1->text + l1, cstr);
797 /* Truncate the string S1 to have length LENGTH. */
800 str_trunc (s1, length)
804 if (s1->length > length)
806 s1->text[length] = 0;