.
[coreutils.git] / src / du.c
blobb7c522912ea5b16afb93955743165a0176fe0a89
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)
7 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, 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
20 when -a is given.
21 * Additional options:
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. */
39 #ifdef _AIX
40 #pragma alloca
41 #endif
43 #include <config.h>
44 #include <stdio.h>
45 #include <getopt.h>
46 #include <sys/types.h>
48 #include "system.h"
49 #include "version.h"
50 #include "save-cwd.h"
51 #include "error.h"
53 /* Initial number of entries in each hash table entry's table of inodes. */
54 #define INITIAL_HASH_MODULE 100
56 /* Initial number of entries in the inode hash table. */
57 #define INITIAL_ENTRY_TAB_SIZE 70
59 /* Initial size to allocate for `path'. */
60 #define INITIAL_PATH_SIZE 100
62 /* Hash structure for inode and device numbers. The separate entry
63 structure makes it easier to rehash "in place". */
65 struct entry
67 ino_t ino;
68 dev_t dev;
69 struct entry *coll_link;
72 /* Structure for a hash table for inode numbers. */
74 struct htab
76 unsigned modulus; /* Size of the `hash' pointer vector. */
77 struct entry *entry_tab; /* Pointer to dynamically growing vector. */
78 unsigned entry_tab_size; /* Size of current `entry_tab' allocation. */
79 unsigned first_free_entry; /* Index in `entry_tab'. */
80 struct entry *hash[1]; /* Vector of pointers in `entry_tab'. */
84 /* Structure for dynamically resizable strings. */
86 typedef struct
88 unsigned alloc; /* Size of allocation for the text. */
89 unsigned length; /* Length of the text currently. */
90 char *text; /* Pointer to the text. */
91 } *string, stringstruct;
93 int stat ();
94 int lstat ();
96 char *savedir ();
97 char *xmalloc ();
98 char *xrealloc ();
100 static int hash_insert __P ((ino_t ino, dev_t dev));
101 static int hash_insert2 __P ((struct htab *htab, ino_t ino, dev_t dev));
102 static long count_entry __P ((char *ent, int top, dev_t last_dev));
103 static void du_files __P ((char **files));
104 static void hash_init __P ((unsigned int modulus,
105 unsigned int entry_tab_size));
106 static void hash_reset __P ((void));
107 static void str_concatc __P ((string s1, char *cstr));
108 static void str_copyc __P ((string s1, char *cstr));
109 static void str_init __P ((string *s1, unsigned int size));
110 static void str_trunc __P ((string s1, unsigned int length));
112 /* Name under which this program was invoked. */
113 char *program_name;
115 /* If nonzero, display only a total for each argument. */
116 static int opt_summarize_only = 0;
118 /* If nonzero, display counts for all files, not just directories. */
119 static int opt_all = 0;
121 /* If nonzero, count each hard link of files with multiple links. */
122 static int opt_count_all = 0;
124 /* If nonzero, do not cross file-system boundaries. */
125 static int opt_one_file_system = 0;
127 /* If nonzero, print a grand total at the end. */
128 static int opt_combined_arguments = 0;
130 /* If nonzero, do not add sizes of subdirectories. */
131 static int opt_separate_dirs = 0;
133 /* If nonzero, dereference symlinks that are command line arguments. */
134 static int opt_dereference_arguments = 0;
136 enum output_size
138 size_blocks, /* 512-byte blocks. */
139 size_kilobytes, /* 1K blocks. */
140 size_bytes /* 1-byte blocks. */
143 /* The units to count in. */
144 static enum output_size output_size;
146 /* Accumulated path for file or directory being processed. */
147 static string path;
149 /* Pointer to hash structure, used by the hash routines. */
150 static struct htab *htab;
152 /* Globally used stat buffer. */
153 static struct stat stat_buf;
155 /* A pointer to either lstat or stat, depending on whether
156 dereferencing of all symbolic links is to be done. */
157 static int (*xstat) ();
159 /* The exit status to use if we don't get any fatal errors. */
160 static int exit_status;
162 /* If nonzero, display usage information and exit. */
163 static int show_help;
165 /* If nonzero, print the version on standard output and exit. */
166 static int show_version;
168 /* Grand total size of all args. */
169 static long tot_size = 0L;
171 static struct option const long_options[] =
173 {"all", no_argument, &opt_all, 1},
174 {"bytes", no_argument, NULL, 'b'},
175 {"count-links", no_argument, &opt_count_all, 1},
176 {"dereference", no_argument, NULL, 'L'},
177 {"dereference-args", no_argument, &opt_dereference_arguments, 1},
178 {"kilobytes", no_argument, NULL, 'k'},
179 {"one-file-system", no_argument, &opt_one_file_system, 1},
180 {"separate-dirs", no_argument, &opt_separate_dirs, 1},
181 {"summarize", no_argument, &opt_summarize_only, 1},
182 {"total", no_argument, &opt_combined_arguments, 1},
183 {"help", no_argument, &show_help, 1},
184 {"version", no_argument, &show_version, 1},
185 {NULL, 0, NULL, 0}
188 static void
189 usage (int status, char *reason)
191 if (reason != NULL)
192 fprintf (status == 0 ? stdout : stderr, "%s: %s\n",
193 program_name, reason);
195 if (status != 0)
196 fprintf (stderr, _("Try `%s --help' for more information.\n"),
197 program_name);
198 else
200 printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name);
201 printf (_("\
202 Summarize disk usage of each FILE, recursively for directories.\n\
204 -a, --all write counts for all files, not just directories\n\
205 -b, --bytes print size in bytes\n\
206 -c, --total produce a grand total\n\
207 -k, --kilobytes use 1024 blocks, not 512 despite POSIXLY_CORRECT\n\
208 -l, --count-links count sizes many times if hard linked\n\
209 -s, --summarize display only a total for each argument\n\
210 -x, --one-file-system skip directories on different filesystems\n\
211 -D, --dereference-args dereference PATHs when symbolic link\n\
212 -L, --dereference dereference all symbolic links\n\
213 -S, --separate-dirs do not include size of subdirectories\n\
214 --help display this help and exit\n\
215 --version output version information and exit\n"));
217 exit (status);
220 void
221 main (int argc, char **argv)
223 int c;
224 char *cwd_only[2];
226 cwd_only[0] = ".";
227 cwd_only[1] = NULL;
229 program_name = argv[0];
230 xstat = lstat;
231 output_size = getenv ("POSIXLY_CORRECT") ? size_blocks : size_kilobytes;
233 while ((c = getopt_long (argc, argv, "abcklsxDLS", long_options, (int *) 0))
234 != EOF)
236 switch (c)
238 case 0: /* Long option. */
239 break;
241 case 'a':
242 opt_all = 1;
243 break;
245 case 'b':
246 output_size = size_bytes;
247 break;
249 case 'c':
250 opt_combined_arguments = 1;
251 break;
253 case 'k':
254 output_size = size_kilobytes;
255 break;
257 case 'l':
258 opt_count_all = 1;
259 break;
261 case 's':
262 opt_summarize_only = 1;
263 break;
265 case 'x':
266 opt_one_file_system = 1;
267 break;
269 case 'D':
270 opt_dereference_arguments = 1;
271 break;
273 case 'L':
274 xstat = stat;
275 break;
277 case 'S':
278 opt_separate_dirs = 1;
279 break;
281 default:
282 usage (2, (char *) 0);
286 if (show_version)
288 printf ("du - %s\n", version_string);
289 exit (0);
292 if (show_help)
293 usage (0, NULL);
295 if (opt_all && opt_summarize_only)
296 usage (2, _("cannot both summarize and show all entries"));
298 /* Initialize the hash structure for inode numbers. */
299 hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
301 str_init (&path, INITIAL_PATH_SIZE);
303 du_files (optind == argc ? cwd_only : argv + optind);
305 exit (exit_status);
308 /* Recursively print the sizes of the directories (and, if selected, files)
309 named in FILES, the last entry of which is NULL. */
311 static void
312 du_files (char **files)
314 struct saved_cwd cwd;
315 ino_t initial_ino; /* Initial directory's inode. */
316 dev_t initial_dev; /* Initial directory's device. */
317 int i; /* Index in FILES. */
319 if (save_cwd (&cwd))
320 exit (1);
322 /* Remember the inode and device number of the current directory. */
323 if (stat (".", &stat_buf))
324 error (1, errno, _("current directory"));
325 initial_ino = stat_buf.st_ino;
326 initial_dev = stat_buf.st_dev;
328 for (i = 0; files[i]; i++)
330 char *arg;
331 int s;
333 arg = files[i];
335 /* Delete final slash in the argument, unless the slash is alone. */
336 s = strlen (arg) - 1;
337 if (s != 0)
339 if (arg[s] == '/')
340 arg[s] = 0;
342 str_copyc (path, arg);
344 else if (arg[0] == '/')
345 str_trunc (path, 0); /* Null path for root directory. */
346 else
347 str_copyc (path, arg);
349 if (!opt_combined_arguments)
350 hash_reset ();
352 count_entry (arg, 1, 0);
354 /* chdir if `count_entry' has changed the working directory. */
355 if (stat (".", &stat_buf))
356 error (1, errno, ".");
357 if (stat_buf.st_ino != initial_ino || stat_buf.st_dev != initial_dev)
359 if (restore_cwd (&cwd, _("starting directory"), NULL))
360 exit (1);
364 if (opt_combined_arguments)
366 printf (_("%ld\ttotal\n"), output_size == size_bytes ? tot_size
367 : convert_blocks (tot_size, output_size == size_kilobytes));
368 fflush (stdout);
371 free_cwd (&cwd);
374 /* Print (if appropriate) and return the size
375 (in units determined by `output_size') of file or directory ENT.
376 TOP is one for external calls, zero for recursive calls.
377 LAST_DEV is the device that the parent directory of ENT is on. */
379 static long
380 count_entry (char *ent, int top, dev_t last_dev)
382 long size;
384 if (((top && opt_dereference_arguments)
385 ? stat (ent, &stat_buf)
386 : (*xstat) (ent, &stat_buf)) < 0)
388 error (0, errno, "%s", path->text);
389 exit_status = 1;
390 return 0;
393 if (!opt_count_all
394 && stat_buf.st_nlink > 1
395 && hash_insert (stat_buf.st_ino, stat_buf.st_dev))
396 return 0; /* Have counted this already. */
398 if (output_size == size_bytes)
399 size = stat_buf.st_size;
400 else
401 size = ST_NBLOCKS (stat_buf);
403 tot_size += size;
405 if (S_ISDIR (stat_buf.st_mode))
407 unsigned pathlen;
408 dev_t dir_dev;
409 char *name_space;
410 char *namep;
411 struct saved_cwd cwd;
412 int through_symlink;
413 struct stat e_buf;
415 dir_dev = stat_buf.st_dev;
417 if (opt_one_file_system && !top && last_dev != dir_dev)
418 return 0; /* Don't enter a new file system. */
420 #ifndef S_ISDIR
421 # define S_ISDIR(s) 0
422 #endif
423 /* If we're dereferencing symlinks and we're about to chdir through
424 a symlink, remember the current directory so we can return to it
425 later. In other cases, chdir ("..") works fine. */
426 through_symlink = (xstat == stat
427 && lstat (ent, &e_buf) == 0
428 && S_ISLNK (e_buf.st_mode));
429 if (through_symlink)
430 if (save_cwd (&cwd))
431 exit (1);
433 if (chdir (ent) < 0)
435 error (0, errno, _("cannot change to directory %s"), path->text);
436 exit_status = 1;
437 return 0;
440 errno = 0;
441 name_space = savedir (".", stat_buf.st_size);
442 if (name_space == NULL)
444 if (errno)
446 error (0, errno, "%s", path->text);
447 if (through_symlink)
449 if (restore_cwd (&cwd, "..", path->text))
450 exit (1);
451 free_cwd (&cwd);
453 else if (chdir ("..") < 0)
454 error (1, errno, _("cannot change to `..' from directory %s"),
455 path->text);
456 exit_status = 1;
457 return 0;
459 else
460 error (1, 0, _("virtual memory exhausted"));
463 /* Remember the current path. */
465 str_concatc (path, "/");
466 pathlen = path->length;
468 namep = name_space;
469 while (*namep != 0)
471 str_concatc (path, namep);
473 size += count_entry (namep, 0, dir_dev);
475 str_trunc (path, pathlen);
476 namep += strlen (namep) + 1;
478 free (name_space);
479 if (through_symlink)
481 restore_cwd (&cwd, "..", path->text);
482 free_cwd (&cwd);
484 else if (chdir ("..") < 0)
485 error (1, errno,
486 _("cannot change to `..' from directory %s"), path->text);
488 str_trunc (path, pathlen - 1); /* Remove the "/" we added. */
489 if (!opt_summarize_only || top)
491 printf ("%ld\t%s\n", output_size == size_bytes ? size
492 : convert_blocks (size, output_size == size_kilobytes),
493 path->length > 0 ? path->text : "/");
494 fflush (stdout);
496 return opt_separate_dirs ? 0 : size;
498 else if (opt_all || top)
500 /* FIXME: make this an option. */
501 int print_only_dir_size = 0;
502 if (!print_only_dir_size)
504 printf ("%ld\t%s\n", output_size == size_bytes ? size
505 : convert_blocks (size, output_size == size_kilobytes),
506 path->text);
507 fflush (stdout);
511 return size;
514 /* Allocate space for the hash structures, and set the global
515 variable `htab' to point to it. The initial hash module is specified in
516 MODULUS, and the number of entries are specified in ENTRY_TAB_SIZE. (The
517 hash structure will be rebuilt when ENTRY_TAB_SIZE entries have been
518 inserted, and MODULUS and ENTRY_TAB_SIZE in the global `htab' will be
519 doubled.) */
521 static void
522 hash_init (unsigned int modulus, unsigned int entry_tab_size)
524 struct htab *htab_r;
526 htab_r = (struct htab *)
527 xmalloc (sizeof (struct htab) + sizeof (struct entry *) * modulus);
529 htab_r->entry_tab = (struct entry *)
530 xmalloc (sizeof (struct entry) * entry_tab_size);
532 htab_r->modulus = modulus;
533 htab_r->entry_tab_size = entry_tab_size;
534 htab = htab_r;
536 hash_reset ();
539 /* Reset the hash structure in the global variable `htab' to
540 contain no entries. */
542 static void
543 hash_reset (void)
545 int i;
546 struct entry **p;
548 htab->first_free_entry = 0;
550 p = htab->hash;
551 for (i = htab->modulus; i > 0; i--)
552 *p++ = NULL;
555 /* Insert an item (inode INO and device DEV) in the hash
556 structure in the global variable `htab', if an entry with the same data
557 was not found already. Return zero if the item was inserted and nonzero
558 if it wasn't. */
560 static int
561 hash_insert (ino_t ino, dev_t dev)
563 struct htab *htab_r = htab; /* Initially a copy of the global `htab'. */
565 if (htab_r->first_free_entry >= htab_r->entry_tab_size)
567 int i;
568 struct entry *ep;
569 unsigned modulus;
570 unsigned entry_tab_size;
572 /* Increase the number of hash entries, and re-hash the data.
573 The method of shrimping and increasing is made to compactify
574 the heap. If twice as much data would be allocated
575 straightforwardly, we would never re-use a byte of memory. */
577 /* Let `htab' shrimp. Keep only the header, not the pointer vector. */
579 htab_r = (struct htab *)
580 xrealloc ((char *) htab_r, sizeof (struct htab));
582 modulus = 2 * htab_r->modulus;
583 entry_tab_size = 2 * htab_r->entry_tab_size;
585 /* Increase the number of possible entries. */
587 htab_r->entry_tab = (struct entry *)
588 xrealloc ((char *) htab_r->entry_tab,
589 sizeof (struct entry) * entry_tab_size);
591 /* Increase the size of htab again. */
593 htab_r = (struct htab *)
594 xrealloc ((char *) htab_r,
595 sizeof (struct htab) + sizeof (struct entry *) * modulus);
597 htab_r->modulus = modulus;
598 htab_r->entry_tab_size = entry_tab_size;
599 htab = htab_r;
601 i = htab_r->first_free_entry;
603 /* Make the increased hash table empty. The entries are still
604 available in htab->entry_tab. */
606 hash_reset ();
608 /* Go through the entries and install them in the pointer vector
609 htab->hash. The items are actually inserted in htab->entry_tab at
610 the position where they already are. The htab->coll_link need
611 however be updated. Could be made a little more efficient. */
613 for (ep = htab_r->entry_tab; i > 0; i--)
615 hash_insert2 (htab_r, ep->ino, ep->dev);
616 ep++;
620 return hash_insert2 (htab_r, ino, dev);
623 /* Insert INO and DEV in the hash structure HTAB, if not
624 already present. Return zero if inserted and nonzero if it
625 already existed. */
627 static int
628 hash_insert2 (struct htab *htab, ino_t ino, dev_t dev)
630 struct entry **hp, *ep2, *ep;
631 hp = &htab->hash[ino % htab->modulus];
632 ep2 = *hp;
634 /* Collision? */
636 if (ep2 != NULL)
638 ep = ep2;
640 /* Search for an entry with the same data. */
644 if (ep->ino == ino && ep->dev == dev)
645 return 1; /* Found an entry with the same data. */
646 ep = ep->coll_link;
648 while (ep != NULL);
650 /* Did not find it. */
654 ep = *hp = &htab->entry_tab[htab->first_free_entry++];
655 ep->ino = ino;
656 ep->dev = dev;
657 ep->coll_link = ep2; /* `ep2' is NULL if no collision. */
659 return 0;
662 /* Initialize the struct string S1 for holding SIZE characters. */
664 static void
665 str_init (string *s1, unsigned int size)
667 string s;
669 s = (string) xmalloc (sizeof (stringstruct));
670 s->text = xmalloc (size + 1);
672 s->alloc = size;
673 *s1 = s;
676 static void
677 ensure_space (string s, unsigned int size)
679 if (s->alloc < size)
681 s->text = xrealloc (s->text, size + 1);
682 s->alloc = size;
686 /* Assign the null-terminated C-string CSTR to S1. */
688 static void
689 str_copyc (string s1, char *cstr)
691 unsigned l = strlen (cstr);
692 ensure_space (s1, l);
693 strcpy (s1->text, cstr);
694 s1->length = l;
697 static void
698 str_concatc (string s1, char *cstr)
700 unsigned l1 = s1->length;
701 unsigned l2 = strlen (cstr);
702 unsigned l = l1 + l2;
704 ensure_space (s1, l);
705 strcpy (s1->text + l1, cstr);
706 s1->length = l;
709 /* Truncate the string S1 to have length LENGTH. */
711 static void
712 str_trunc (string s1, unsigned int length)
714 if (s1->length > length)
716 s1->text[length] = 0;
717 s1->length = length;