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