home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / fileutils-3.6 / src / du.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-05-14  |  16.6 KB  |  694 lines

  1. /* du -- summarize disk usage
  2.    Copyright (C) 1988, 1989, 1990, 1991 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
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, 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.    * 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.
  35.  
  36.    By tege@sics.se, Torbjorn Granlund,
  37.    and djm@ai.mit.edu, David MacKenzie.  */
  38.  
  39. #ifdef _AIX
  40.  #pragma alloca
  41. #endif
  42. #include <stdio.h>
  43. #include <getopt.h>
  44. #include <sys/types.h>
  45. #include "system.h"
  46. #include "version.h"
  47.  
  48. int lstat ();
  49. int stat ();
  50.  
  51. /* Initial number of entries in each hash table entry's table of inodes.  */
  52. #define INITIAL_HASH_MODULE 100
  53.  
  54. /* Initial number of entries in the inode hash table.  */
  55. #define INITIAL_ENTRY_TAB_SIZE 70
  56.  
  57. /* Initial size to allocate for `path'.  */
  58. #define INITIAL_PATH_SIZE 100
  59.  
  60. /* Hash structure for inode and device numbers.  The separate entry
  61.    structure makes it easier to rehash "in place".  */
  62.  
  63. struct entry
  64. {
  65.   ino_t ino;
  66.   dev_t dev;
  67.   struct entry *coll_link;
  68. };
  69.  
  70. /* Structure for a hash table for inode numbers. */
  71.  
  72. struct htab
  73. {
  74.   unsigned modulus;        /* Size of the `hash' pointer vector.  */
  75.   struct entry *entry_tab;    /* Pointer to dynamically growing vector.  */
  76.   unsigned entry_tab_size;    /* Size of current `entry_tab' allocation.  */
  77.   unsigned first_free_entry;    /* Index in `entry_tab'.  */
  78.   struct entry *hash[1];    /* Vector of pointers in `entry_tab'.  */
  79. };
  80.  
  81.  
  82. /* Structure for dynamically resizable strings. */
  83.  
  84. typedef struct
  85. {
  86.   unsigned alloc;        /* Size of allocation for the text.  */
  87.   unsigned length;        /* Length of the text currently.  */
  88.   char *text;            /* Pointer to the text.  */
  89. } *string, stringstruct;
  90.  
  91. char *savedir ();
  92. char *xgetcwd ();
  93. char *xmalloc ();
  94. char *xrealloc ();
  95. void error ();
  96.  
  97. static int hash_insert ();
  98. static int hash_insert2 ();
  99. static long count_entry ();
  100. static void du_files ();
  101. static void hash_init ();
  102. static void hash_reset ();
  103. static void str_concatc ();
  104. static void str_copyc ();
  105. static void str_init ();
  106. static void str_trunc ();
  107.  
  108. /* Name under which this program was invoked.  */
  109. char *program_name;
  110.  
  111. /* If nonzero, display only a total for each argument. */
  112. static int opt_summarize_only = 0;
  113.  
  114. /* If nonzero, display counts for all files, not just directories. */
  115. static int opt_all = 0;
  116.  
  117. /* If nonzero, count each hard link of files with multiple links. */
  118. static int opt_count_all = 0;
  119.  
  120. /* If nonzero, do not cross file-system boundaries. */
  121. static int opt_one_file_system = 0;
  122.  
  123. /* If nonzero, print a grand total at the end. */
  124. static int opt_combined_arguments = 0;
  125.  
  126. /* If nonzero, do not add sizes of subdirectories. */
  127. static int opt_separate_dirs = 0;
  128.  
  129. /* If nonzero, dereference symlinks that are command line arguments. */
  130. static int opt_dereference_arguments = 0;
  131.  
  132. enum output_size
  133. {
  134.   size_blocks,            /* 512-byte blocks. */
  135.   size_kilobytes,        /* 1K blocks. */
  136.   size_bytes            /* 1-byte blocks. */
  137. };
  138.  
  139. /* The units to count in. */
  140. static enum output_size output_size;
  141.  
  142. /* Accumulated path for file or directory being processed.  */
  143. static string path;
  144.  
  145. /* Pointer to hash structure, used by the hash routines.  */
  146. static struct htab *htab;
  147.  
  148. /* Globally used stat buffer.  */
  149. static struct stat stat_buf;
  150.  
  151. /* A pointer to either lstat or stat, depending on whether
  152.    dereferencing of all symbolic links is to be done. */
  153. static int (*xstat) ();
  154.  
  155. /* The exit status to use if we don't get any fatal errors. */
  156. static int exit_status;
  157.  
  158. /* If non-zero, display usage information and exit.  */
  159. static int flag_help;
  160.  
  161. /* If non-zero, print the version on standard error.  */
  162. static int flag_version;
  163.  
  164. static struct option const long_options[] =
  165. {
  166.   {"all", no_argument, &opt_all, 1},
  167.   {"bytes", no_argument, NULL, 'b'},
  168.   {"count-links", no_argument, &opt_count_all, 1},
  169.   {"dereference", no_argument, NULL, 'L'},
  170.   {"dereference-args", no_argument, &opt_dereference_arguments, 1},
  171.   {"kilobytes", no_argument, NULL, 'k'},
  172.   {"one-file-system", no_argument, &opt_one_file_system, 1},
  173.   {"separate-dirs", no_argument, &opt_separate_dirs, 1},
  174.   {"summarize", no_argument, &opt_summarize_only, 1},
  175.   {"total", no_argument, &opt_combined_arguments, 1},
  176.   {"help", no_argument, &flag_help, 1},
  177.   {"version", no_argument, &flag_version, 1},
  178.   {NULL, 0, NULL, 0}
  179. };
  180.  
  181. static void
  182. usage (reason)
  183.      char *reason;
  184. {
  185.   if (reason != NULL)
  186.     fprintf (stderr, "%s: %s\n", program_name, reason);
  187.  
  188.   fprintf (stderr, "\
  189. Usage: %s [-abcklsxDLS] [--all] [--total] [--count-links] [--summarize]\n\
  190.        [--bytes] [--kilobytes] [--one-file-system] [--separate-dirs]\n\
  191.        [--dereference] [--dereference-args] [--help] [--version] [path...]\n",
  192.        program_name);
  193.  
  194.   exit (2);
  195. }
  196.  
  197. void
  198. main (argc, argv)
  199.      int argc;
  200.      char *argv[];
  201. {
  202.   int c;
  203.  
  204.   program_name = argv[0];
  205.   xstat = lstat;
  206.   output_size = getenv ("POSIXLY_CORRECT") ? size_blocks : size_kilobytes;
  207.  
  208.   while ((c = getopt_long (argc, argv, "abcklsxDLS", long_options, (int *) 0))
  209.      != EOF)
  210.     {
  211.       switch (c)
  212.     {
  213.     case 0:            /* Long option. */
  214.       break;
  215.  
  216.     case 'a':
  217.       opt_all = 1;
  218.       break;
  219.  
  220.     case 'b':
  221.       output_size = size_bytes;
  222.       break;
  223.  
  224.     case 'c':
  225.       opt_combined_arguments = 1;
  226.       break;
  227.  
  228.     case 'k':
  229.       output_size = size_kilobytes;
  230.       break;
  231.  
  232.     case 'l':
  233.       opt_count_all = 1;
  234.       break;
  235.  
  236.     case 's':
  237.       opt_summarize_only = 1;
  238.       break;
  239.  
  240.     case 'x':
  241.       opt_one_file_system = 1;
  242.       break;
  243.  
  244.     case 'D':
  245.       opt_dereference_arguments = 1;
  246.       break;
  247.  
  248.     case 'L':
  249.       xstat = stat;
  250.       break;
  251.  
  252.     case 'S':
  253.       opt_separate_dirs = 1;
  254.       break;
  255.  
  256.     default:
  257.       usage ((char *) 0);
  258.     }
  259.     }
  260.  
  261.   if (flag_version)
  262.     {
  263.       fprintf (stderr, "%s\n", version_string);
  264.       exit (0);
  265.     }
  266.  
  267.   if (flag_help)
  268.     usage (NULL);
  269.  
  270.   if (opt_all && opt_summarize_only)
  271.     usage ("cannot both summarize and show all entries");
  272.  
  273.   /* Initialize the hash structure for inode numbers.  */
  274.   hash_init (INITIAL_HASH_MODULE, INITIAL_ENTRY_TAB_SIZE);
  275.  
  276.   str_init (&path, INITIAL_PATH_SIZE);
  277.  
  278.   if (optind == argc)
  279.     {
  280.       str_copyc (path, ".");
  281.  
  282.       /* Initialize the hash structure for inode numbers.  */
  283.       hash_reset ();
  284.  
  285.       /* Get the size of the current directory only.  */
  286.       count_entry (".", 1, 0);
  287.     }
  288.   else
  289.     {
  290.       du_files (argv + optind);
  291.     }
  292.  
  293.   exit (exit_status);
  294. }
  295.  
  296. /* Recursively print the sizes of the directories (and, if selected, files)
  297.    named in FILES, the last entry of which is NULL.  */
  298.  
  299. static void
  300. du_files (files)
  301.      char **files;
  302. {
  303.   char *wd;
  304.   ino_t initial_ino;        /* Initial directory's inode. */
  305.   dev_t initial_dev;        /* Initial directory's device. */
  306.   long tot_size = 0L;        /* Grand total size of all args. */
  307.   int i;            /* Index in FILES. */
  308.  
  309.   wd = xgetcwd ();
  310.   if (wd == NULL)
  311.     error (1, errno, "cannot get current directory");
  312.  
  313.   /* Remember the inode and device number of the current directory.  */
  314.   if (stat (".", &stat_buf))
  315.     error (1, errno, "current directory");
  316.   initial_ino = stat_buf.st_ino;
  317.   initial_dev = stat_buf.st_dev;
  318.  
  319.   for (i = 0; files[i]; i++)
  320.     {
  321.       char *arg;
  322.       int s;
  323.  
  324.       arg = files[i];
  325.  
  326.       /* Delete final slash in the argument, unless the slash is alone.  */
  327.       s = strlen (arg) - 1;
  328.       if (s != 0)
  329.     {
  330.       if (arg[s] == '/')
  331.         arg[s] = 0;
  332.  
  333.       str_copyc (path, arg);
  334.     }
  335.       else if (arg[0] == '/')
  336.     str_trunc (path, 0);    /* Null path for root directory.  */
  337.       else
  338.     str_copyc (path, arg);
  339.  
  340.       if (!opt_combined_arguments)
  341.     hash_reset ();
  342.  
  343.       tot_size += count_entry (arg, 1, 0);
  344.  
  345.       /* chdir if `count_entry' has changed the working directory.  */
  346.       if (stat (".", &stat_buf))
  347.     error (1, errno, ".");
  348.       if ((stat_buf.st_ino != initial_ino || stat_buf.st_dev != initial_dev)
  349.       && chdir (wd) < 0)
  350.     error (1, errno, "cannot change to directory %s", wd);
  351.     }
  352.  
  353.   if (opt_combined_arguments)
  354.     {
  355.       printf ("%ld\ttotal\n", output_size == size_bytes ? tot_size
  356.           : convert_blocks (tot_size, output_size == size_kilobytes));
  357.       fflush (stdout);
  358.     }
  359.  
  360.   free (wd);
  361. }
  362.  
  363. /* Print (if appropriate) and return the size
  364.    (in units determined by `output_size') of file or directory ENT.
  365.    TOP is one for external calls, zero for recursive calls.
  366.    LAST_DEV is the device that the parent directory of ENT is on.  */
  367.  
  368. static long
  369. count_entry (ent, top, last_dev)
  370.      char *ent;
  371.      int top;
  372.      dev_t last_dev;
  373. {
  374.   long size;
  375.  
  376.   if ((top && opt_dereference_arguments ?
  377.       stat (ent, &stat_buf) :
  378.       (*xstat) (ent, &stat_buf)) < 0)
  379.     {
  380.       error (0, errno, "%s", path->text);
  381.       exit_status = 1;
  382.       return 0;
  383.     }
  384.  
  385.   if (!opt_count_all
  386.       && stat_buf.st_nlink > 1
  387.       && hash_insert (stat_buf.st_ino, stat_buf.st_dev))
  388.     return 0;            /* Have counted this already.  */
  389.  
  390.   if (output_size == size_bytes)
  391.     size = stat_buf.st_size;
  392.   else
  393.     size = ST_NBLOCKS (stat_buf);
  394.  
  395.   if (S_ISDIR (stat_buf.st_mode))
  396.     {
  397.       unsigned pathlen;
  398.       dev_t dir_dev;
  399.       char *name_space;
  400.       char *namep;
  401.  
  402.       dir_dev = stat_buf.st_dev;
  403.  
  404.       if (opt_one_file_system && !top && last_dev != dir_dev)
  405.     return 0;        /* Don't enter a new file system.  */
  406.  
  407.       if (chdir (ent) < 0)
  408.     {
  409.       error (0, errno, "cannot change to directory %s", path->text);
  410.       exit_status = 1;
  411.       return 0;
  412.     }
  413.  
  414.       errno = 0;
  415.       name_space = savedir (".", stat_buf.st_size);
  416.       if (name_space == NULL)
  417.     {
  418.       if (errno)
  419.         {
  420.           error (0, errno, "%s", path->text);
  421.           if (chdir ("..") < 0)    /* Try to return to previous dir.  */
  422.         error (1, errno, "cannot change to `..' from directory %s",
  423.                path->text);
  424.           exit_status = 1;
  425.           return 0;
  426.         }
  427.       else
  428.         error (1, 0, "virtual memory exhausted");
  429.     }
  430.  
  431.       /* Remember the current path.  */
  432.  
  433.       str_concatc (path, "/");
  434.       pathlen = path->length;
  435.  
  436.       namep = name_space;
  437.       while (*namep != 0)
  438.     {
  439.       str_concatc (path, namep);
  440.  
  441.       size += count_entry (namep, 0, dir_dev);
  442.  
  443.       str_trunc (path, pathlen);
  444.       namep += strlen (namep) + 1;
  445.     }
  446.       free (name_space);
  447.       if (chdir ("..") < 0)
  448.         error (1, errno, "cannot change to `..' from directory %s", path->text);
  449.  
  450.       str_trunc (path, pathlen - 1); /* Remove the "/" we added.  */
  451.       if (!opt_summarize_only || top)
  452.     {
  453.       printf ("%ld\t%s\n", output_size == size_bytes ? size
  454.           : convert_blocks (size, output_size == size_kilobytes),
  455.           path->text);
  456.       fflush (stdout);
  457.     }
  458.       return opt_separate_dirs ? 0 : size;
  459.     }
  460.   else if (opt_all || top)
  461.     {
  462.       printf ("%ld\t%s\n", output_size == size_bytes ? size
  463.           : convert_blocks (size, output_size == size_kilobytes),
  464.           path->text);
  465.       fflush (stdout);
  466.     }
  467.  
  468.   return size;
  469. }
  470.  
  471. /* Allocate space for the hash structures, and set the global
  472.    variable `htab' to point to it.  The initial hash module is specified in
  473.    MODULUS, and the number of entries are specified in ENTRY_TAB_SIZE.  (The
  474.    hash structure will be rebuilt when ENTRY_TAB_SIZE entries have been
  475.    inserted, and MODULUS and ENTRY_TAB_SIZE in the global `htab' will be
  476.    doubled.)  */
  477.  
  478. static void
  479. hash_init (modulus, entry_tab_size)
  480.      unsigned modulus;
  481.      unsigned entry_tab_size;
  482. {
  483.   struct htab *htab_r;
  484.  
  485.   htab_r = (struct htab *)
  486.     xmalloc (sizeof (struct htab) + sizeof (struct entry *) * modulus);
  487.  
  488.   htab_r->entry_tab = (struct entry *)
  489.     xmalloc (sizeof (struct entry) * entry_tab_size);
  490.  
  491.   htab_r->modulus = modulus;
  492.   htab_r->entry_tab_size = entry_tab_size;
  493.   htab = htab_r;
  494.  
  495.   hash_reset ();
  496. }
  497.  
  498. /* Reset the hash structure in the global variable `htab' to
  499.    contain no entries.  */
  500.  
  501. static void
  502. hash_reset ()
  503. {
  504.   int i;
  505.   struct entry **p;
  506.  
  507.   htab->first_free_entry = 0;
  508.  
  509.   p = htab->hash;
  510.   for (i = htab->modulus; i > 0; i--)
  511.     *p++ = NULL;
  512. }
  513.  
  514. /* Insert an item (inode INO and device DEV) in the hash
  515.    structure in the global variable `htab', if an entry with the same data
  516.    was not found already.  Return zero if the item was inserted and non-zero
  517.    if it wasn't.  */
  518.  
  519. static int
  520. hash_insert (ino, dev)
  521.      ino_t ino;
  522.      dev_t dev;
  523. {
  524.   struct htab *htab_r = htab;    /* Initially a copy of the global `htab'.  */
  525.  
  526.   if (htab_r->first_free_entry >= htab_r->entry_tab_size)
  527.     {
  528.       int i;
  529.       struct entry *ep;
  530.       unsigned modulus;
  531.       unsigned entry_tab_size;
  532.  
  533.       /* Increase the number of hash entries, and re-hash the data.
  534.      The method of shrimping and increasing is made to compactify
  535.      the heap.  If twice as much data would be allocated
  536.      straightforwardly, we would never re-use a byte of memory.  */
  537.  
  538.       /* Let `htab' shrimp.  Keep only the header, not the pointer vector.  */
  539.  
  540.       htab_r = (struct htab *)
  541.     xrealloc ((char *) htab_r, sizeof (struct htab));
  542.  
  543.       modulus = 2 * htab_r->modulus;
  544.       entry_tab_size = 2 * htab_r->entry_tab_size;
  545.  
  546.       /* Increase the number of possible entries.  */
  547.  
  548.       htab_r->entry_tab = (struct entry *)
  549.     xrealloc ((char *) htab_r->entry_tab,
  550.          sizeof (struct entry) * entry_tab_size);
  551.  
  552.       /* Increase the size of htab again.  */
  553.  
  554.       htab_r = (struct htab *)
  555.     xrealloc ((char *) htab_r,
  556.          sizeof (struct htab) + sizeof (struct entry *) * modulus);
  557.  
  558.       htab_r->modulus = modulus;
  559.       htab_r->entry_tab_size = entry_tab_size;
  560.       htab = htab_r;
  561.  
  562.       i = htab_r->first_free_entry;
  563.  
  564.       /* Make the increased hash table empty.  The entries are still
  565.      available in htab->entry_tab.  */
  566.  
  567.       hash_reset ();
  568.  
  569.       /* Go through the entries and install them in the pointer vector
  570.      htab->hash.  The items are actually inserted in htab->entry_tab at
  571.      the position where they already are.  The htab->coll_link need
  572.      however be updated.  Could be made a little more efficient.  */
  573.  
  574.       for (ep = htab_r->entry_tab; i > 0; i--)
  575.     {
  576.       hash_insert2 (htab_r, ep->ino, ep->dev);
  577.       ep++;
  578.     }
  579.     }
  580.  
  581.   return hash_insert2 (htab_r, ino, dev);
  582. }
  583.  
  584. /* Insert INO and DEV in the hash structure HTAB, if not
  585.    already present.  Return zero if inserted and non-zero if it
  586.    already existed.  */
  587.  
  588. static int
  589. hash_insert2 (htab, ino, dev)
  590.      struct htab *htab;
  591.      ino_t ino;
  592.      dev_t dev;
  593. {
  594.   struct entry **hp, *ep2, *ep;
  595.   hp = &htab->hash[ino % htab->modulus];
  596.   ep2 = *hp;
  597.  
  598.   /* Collision?  */
  599.  
  600.   if (ep2 != NULL)
  601.     {
  602.       ep = ep2;
  603.  
  604.       /* Search for an entry with the same data.  */
  605.  
  606.       do
  607.     {
  608.       if (ep->ino == ino && ep->dev == dev)
  609.         return 1;        /* Found an entry with the same data.  */
  610.       ep = ep->coll_link;
  611.     }
  612.       while (ep != NULL);
  613.  
  614.       /* Did not find it.  */
  615.  
  616.     }
  617.  
  618.   ep = *hp = &htab->entry_tab[htab->first_free_entry++];
  619.   ep->ino = ino;
  620.   ep->dev = dev;
  621.   ep->coll_link = ep2;        /* `ep2' is NULL if no collision.  */
  622.  
  623.   return 0;
  624. }
  625.  
  626. /* Initialize the struct string S1 for holding SIZE characters.  */
  627.  
  628. static void
  629. str_init (s1, size)
  630.      string *s1;
  631.      unsigned size;
  632. {
  633.   string s;
  634.  
  635.   s = (string) xmalloc (sizeof (stringstruct));
  636.   s->text = xmalloc (size + 1);
  637.  
  638.   s->alloc = size;
  639.   *s1 = s;
  640. }
  641.  
  642. static void
  643. ensure_space (s, size)
  644.      string s;
  645.      unsigned size;
  646. {
  647.   if (s->alloc < size)
  648.     {
  649.       s->text = xrealloc (s->text, size + 1);
  650.       s->alloc = size;
  651.     }
  652. }
  653.  
  654. /* Assign the null-terminated C-string CSTR to S1.  */
  655.  
  656. static void
  657. str_copyc (s1, cstr)
  658.      string s1;
  659.      char *cstr;
  660. {
  661.   unsigned l = strlen (cstr);
  662.   ensure_space (s1, l);
  663.   strcpy (s1->text, cstr);
  664.   s1->length = l;
  665. }
  666.  
  667. static void
  668. str_concatc (s1, cstr)
  669.      string s1;
  670.      char *cstr;
  671. {
  672.   unsigned l1 = s1->length;
  673.   unsigned l2 = strlen (cstr);
  674.   unsigned l = l1 + l2;
  675.  
  676.   ensure_space (s1, l);
  677.   strcpy (s1->text + l1, cstr);
  678.   s1->length = l;
  679. }
  680.  
  681. /* Truncate the string S1 to have length LENGTH.  */
  682.  
  683. static void
  684. str_trunc (s1, length)
  685.      string s1;
  686.      unsigned length;
  687. {
  688.   if (s1->length > length)
  689.     {
  690.       s1->text[length] = 0;
  691.       s1->length = length;
  692.     }
  693. }
  694.