gdb/bcache.c - gdb

Data types defined

Functions defined

Macros defined

Source code

  1. /* Implement a cached obstack.
  2.    Written by Fred Fish <fnf@cygnus.com>
  3.    Rewritten by Jim Blandy <jimb@cygnus.com>

  4.    Copyright (C) 1999-2015 Free Software Foundation, Inc.

  5.    This file is part of GDB.

  6.    This program is free software; you can redistribute it and/or modify
  7.    it under the terms of the GNU General Public License as published by
  8.    the Free Software Foundation; either version 3 of the License, or
  9.    (at your option) any later version.

  10.    This program is distributed in the hope that it will be useful,
  11.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13.    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, see <http://www.gnu.org/licenses/>.  */

  16. #include "defs.h"
  17. #include "gdb_obstack.h"
  18. #include "bcache.h"

  19. /* The type used to hold a single bcache string.  The user data is
  20.    stored in d.data.  Since it can be any type, it needs to have the
  21.    same alignment as the most strict alignment of any type on the host
  22.    machine.  I don't know of any really correct way to do this in
  23.    stock ANSI C, so just do it the same way obstack.h does.  */

  24. struct bstring
  25. {
  26.   /* Hash chain.  */
  27.   struct bstring *next;
  28.   /* Assume the data length is no more than 64k.  */
  29.   unsigned short length;
  30.   /* The half hash hack.  This contains the upper 16 bits of the hash
  31.      value and is used as a pre-check when comparing two strings and
  32.      avoids the need to do length or memcmp calls.  It proves to be
  33.      roughly 100% effective.  */
  34.   unsigned short half_hash;

  35.   union
  36.   {
  37.     char data[1];
  38.     double dummy;
  39.   }
  40.   d;
  41. };


  42. /* The structure for a bcache itself.  The bcache is initialized, in
  43.    bcache_xmalloc(), by filling it with zeros and then setting the
  44.    corresponding obstack's malloc() and free() methods.  */

  45. struct bcache
  46. {
  47.   /* All the bstrings are allocated here.  */
  48.   struct obstack cache;

  49.   /* How many hash buckets we're using.  */
  50.   unsigned int num_buckets;

  51.   /* Hash buckets.  This table is allocated using malloc, so when we
  52.      grow the table we can return the old table to the system.  */
  53.   struct bstring **bucket;

  54.   /* Statistics.  */
  55.   unsigned long unique_count;        /* number of unique strings */
  56.   long total_count;        /* total number of strings cached, including dups */
  57.   long unique_size;        /* size of unique strings, in bytes */
  58.   long total_size;      /* total number of bytes cached, including dups */
  59.   long structure_size;        /* total size of bcache, including infrastructure */
  60.   /* Number of times that the hash table is expanded and hence
  61.      re-built, and the corresponding number of times that a string is
  62.      [re]hashed as part of entering it into the expanded table.  The
  63.      total number of hashes can be computed by adding TOTAL_COUNT to
  64.      expand_hash_count.  */
  65.   unsigned long expand_count;
  66.   unsigned long expand_hash_count;
  67.   /* Number of times that the half-hash compare hit (compare the upper
  68.      16 bits of hash values) hit, but the corresponding combined
  69.      length/data compare missed.  */
  70.   unsigned long half_hash_miss_count;

  71.   /* Hash function to be used for this bcache object.  */
  72.   unsigned long (*hash_function)(const void *addr, int length);

  73.   /* Compare function to be used for this bcache object.  */
  74.   int (*compare_function)(const void *, const void *, int length);
  75. };

  76. /* The old hash function was stolen from SDBM. This is what DB 3.0
  77.    uses now, and is better than the old one.  */

  78. unsigned long
  79. hash(const void *addr, int length)
  80. {
  81.   return hash_continue (addr, length, 0);
  82. }

  83. /* Continue the calculation of the hash H at the given address.  */

  84. unsigned long
  85. hash_continue (const void *addr, int length, unsigned long h)
  86. {
  87.   const unsigned char *k, *e;

  88.   k = (const unsigned char *)addr;
  89.   e = k+length;
  90.   for (; k< e;++k)
  91.     {
  92.       h *=16777619;
  93.       h ^= *k;
  94.     }
  95.   return (h);
  96. }

  97. /* Growing the bcache's hash table.  */

  98. /* If the average chain length grows beyond this, then we want to
  99.    resize our hash table.  */
  100. #define CHAIN_LENGTH_THRESHOLD (5)

  101. static void
  102. expand_hash_table (struct bcache *bcache)
  103. {
  104.   /* A table of good hash table sizes.  Whenever we grow, we pick the
  105.      next larger size from this table.  sizes[i] is close to 1 << (i+10),
  106.      so we roughly double the table size each time.  After we fall off
  107.      the end of this table, we just double.  Don't laugh --- there have
  108.      been executables sighted with a gigabyte of debug info.  */
  109.   static unsigned long sizes[] = {
  110.     1021, 2053, 4099, 8191, 16381, 32771,
  111.     65537, 131071, 262144, 524287, 1048573, 2097143,
  112.     4194301, 8388617, 16777213, 33554467, 67108859, 134217757,
  113.     268435459, 536870923, 1073741827, 2147483659UL
  114.   };
  115.   unsigned int new_num_buckets;
  116.   struct bstring **new_buckets;
  117.   unsigned int i;

  118.   /* Count the stats.  Every unique item needs to be re-hashed and
  119.      re-entered.  */
  120.   bcache->expand_count++;
  121.   bcache->expand_hash_count += bcache->unique_count;

  122.   /* Find the next size.  */
  123.   new_num_buckets = bcache->num_buckets * 2;
  124.   for (i = 0; i < (sizeof (sizes) / sizeof (sizes[0])); i++)
  125.     if (sizes[i] > bcache->num_buckets)
  126.       {
  127.         new_num_buckets = sizes[i];
  128.         break;
  129.       }

  130.   /* Allocate the new table.  */
  131.   {
  132.     size_t new_size = new_num_buckets * sizeof (new_buckets[0]);

  133.     new_buckets = (struct bstring **) xmalloc (new_size);
  134.     memset (new_buckets, 0, new_size);

  135.     bcache->structure_size -= (bcache->num_buckets
  136.                                * sizeof (bcache->bucket[0]));
  137.     bcache->structure_size += new_size;
  138.   }

  139.   /* Rehash all existing strings.  */
  140.   for (i = 0; i < bcache->num_buckets; i++)
  141.     {
  142.       struct bstring *s, *next;

  143.       for (s = bcache->bucket[i]; s; s = next)
  144.         {
  145.           struct bstring **new_bucket;
  146.           next = s->next;

  147.           new_bucket = &new_buckets[(bcache->hash_function (&s->d.data,
  148.                                                             s->length)
  149.                                      % new_num_buckets)];
  150.           s->next = *new_bucket;
  151.           *new_bucket = s;
  152.         }
  153.     }

  154.   /* Plug in the new table.  */
  155.   if (bcache->bucket)
  156.     xfree (bcache->bucket);
  157.   bcache->bucket = new_buckets;
  158.   bcache->num_buckets = new_num_buckets;
  159. }


  160. /* Looking up things in the bcache.  */

  161. /* The number of bytes needed to allocate a struct bstring whose data
  162.    is N bytes long.  */
  163. #define BSTRING_SIZE(n) (offsetof (struct bstring, d.data) + (n))

  164. /* Find a copy of the LENGTH bytes at ADDR in BCACHE.  If BCACHE has
  165.    never seen those bytes before, add a copy of them to BCACHE.  In
  166.    either case, return a pointer to BCACHE's copy of that string.  */
  167. const void *
  168. bcache (const void *addr, int length, struct bcache *cache)
  169. {
  170.   return bcache_full (addr, length, cache, NULL);
  171. }

  172. /* Find a copy of the LENGTH bytes at ADDR in BCACHE.  If BCACHE has
  173.    never seen those bytes before, add a copy of them to BCACHE.  In
  174.    either case, return a pointer to BCACHE's copy of that string.  If
  175.    optional ADDED is not NULL, return 1 in case of new entry or 0 if
  176.    returning an old entry.  */

  177. const void *
  178. bcache_full (const void *addr, int length, struct bcache *bcache, int *added)
  179. {
  180.   unsigned long full_hash;
  181.   unsigned short half_hash;
  182.   int hash_index;
  183.   struct bstring *s;

  184.   if (added)
  185.     *added = 0;

  186.   /* Lazily initialize the obstack.  This can save quite a bit of
  187.      memory in some cases.  */
  188.   if (bcache->total_count == 0)
  189.     {
  190.       /* We could use obstack_specify_allocation here instead, but
  191.          gdb_obstack.h specifies the allocation/deallocation
  192.          functions.  */
  193.       obstack_init (&bcache->cache);
  194.     }

  195.   /* If our average chain length is too high, expand the hash table.  */
  196.   if (bcache->unique_count >= bcache->num_buckets * CHAIN_LENGTH_THRESHOLD)
  197.     expand_hash_table (bcache);

  198.   bcache->total_count++;
  199.   bcache->total_size += length;

  200.   full_hash = bcache->hash_function (addr, length);

  201.   half_hash = (full_hash >> 16);
  202.   hash_index = full_hash % bcache->num_buckets;

  203.   /* Search the hash bucket for a string identical to the caller's.
  204.      As a short-circuit first compare the upper part of each hash
  205.      values.  */
  206.   for (s = bcache->bucket[hash_index]; s; s = s->next)
  207.     {
  208.       if (s->half_hash == half_hash)
  209.         {
  210.           if (s->length == length
  211.               && bcache->compare_function (&s->d.data, addr, length))
  212.             return &s->d.data;
  213.           else
  214.             bcache->half_hash_miss_count++;
  215.         }
  216.     }

  217.   /* The user's string isn't in the list.  Insert it after *ps.  */
  218.   {
  219.     struct bstring *new
  220.       = obstack_alloc (&bcache->cache, BSTRING_SIZE (length));

  221.     memcpy (&new->d.data, addr, length);
  222.     new->length = length;
  223.     new->next = bcache->bucket[hash_index];
  224.     new->half_hash = half_hash;
  225.     bcache->bucket[hash_index] = new;

  226.     bcache->unique_count++;
  227.     bcache->unique_size += length;
  228.     bcache->structure_size += BSTRING_SIZE (length);

  229.     if (added)
  230.       *added = 1;

  231.     return &new->d.data;
  232.   }
  233. }


  234. /* Compare the byte string at ADDR1 of lenght LENGHT to the
  235.    string at ADDR2.  Return 1 if they are equal.  */

  236. static int
  237. bcache_compare (const void *addr1, const void *addr2, int length)
  238. {
  239.   return memcmp (addr1, addr2, length) == 0;
  240. }

  241. /* Allocating and freeing bcaches.  */

  242. /* Allocated a bcache.  HASH_FUNCTION and COMPARE_FUNCTION can be used
  243.    to pass in custom hash, and compare functions to be used by this
  244.    bcache.  If HASH_FUNCTION is NULL hash() is used and if
  245.    COMPARE_FUNCTION is NULL memcmp() is used.  */

  246. struct bcache *
  247. bcache_xmalloc (unsigned long (*hash_function)(const void *, int length),
  248.                 int (*compare_function)(const void *,
  249.                                         const void *,
  250.                                         int length))
  251. {
  252.   /* Allocate the bcache pre-zeroed.  */
  253.   struct bcache *b = XCNEW (struct bcache);

  254.   if (hash_function)
  255.     b->hash_function = hash_function;
  256.   else
  257.     b->hash_function = hash;

  258.   if (compare_function)
  259.     b->compare_function = compare_function;
  260.   else
  261.     b->compare_function = bcache_compare;
  262.   return b;
  263. }

  264. /* Free all the storage associated with BCACHE.  */
  265. void
  266. bcache_xfree (struct bcache *bcache)
  267. {
  268.   if (bcache == NULL)
  269.     return;
  270.   /* Only free the obstack if we actually initialized it.  */
  271.   if (bcache->total_count > 0)
  272.     obstack_free (&bcache->cache, 0);
  273.   xfree (bcache->bucket);
  274.   xfree (bcache);
  275. }



  276. /* Printing statistics.  */

  277. static void
  278. print_percentage (int portion, int total)
  279. {
  280.   if (total == 0)
  281.     /* i18n: Like "Percentage of duplicates, by count: (not applicable)".  */
  282.     printf_filtered (_("(not applicable)\n"));
  283.   else
  284.     printf_filtered ("%3d%%\n", (int) (portion * 100.0 / total));
  285. }


  286. /* Print statistics on BCACHE's memory usage and efficacity at
  287.    eliminating duplication.  NAME should describe the kind of data
  288.    BCACHE holds.  Statistics are printed using `printf_filtered' and
  289.    its ilk.  */
  290. void
  291. print_bcache_statistics (struct bcache *c, char *type)
  292. {
  293.   int occupied_buckets;
  294.   int max_chain_length;
  295.   int median_chain_length;
  296.   int max_entry_size;
  297.   int median_entry_size;

  298.   /* Count the number of occupied buckets, tally the various string
  299.      lengths, and measure chain lengths.  */
  300.   {
  301.     unsigned int b;
  302.     int *chain_length = XCNEWVEC (int, c->num_buckets + 1);
  303.     int *entry_size = XCNEWVEC (int, c->unique_count + 1);
  304.     int stringi = 0;

  305.     occupied_buckets = 0;

  306.     for (b = 0; b < c->num_buckets; b++)
  307.       {
  308.         struct bstring *s = c->bucket[b];

  309.         chain_length[b] = 0;

  310.         if (s)
  311.           {
  312.             occupied_buckets++;

  313.             while (s)
  314.               {
  315.                 gdb_assert (b < c->num_buckets);
  316.                 chain_length[b]++;
  317.                 gdb_assert (stringi < c->unique_count);
  318.                 entry_size[stringi++] = s->length;
  319.                 s = s->next;
  320.               }
  321.           }
  322.       }

  323.     /* To compute the median, we need the set of chain lengths
  324.        sorted.  */
  325.     qsort (chain_length, c->num_buckets, sizeof (chain_length[0]),
  326.            compare_positive_ints);
  327.     qsort (entry_size, c->unique_count, sizeof (entry_size[0]),
  328.            compare_positive_ints);

  329.     if (c->num_buckets > 0)
  330.       {
  331.         max_chain_length = chain_length[c->num_buckets - 1];
  332.         median_chain_length = chain_length[c->num_buckets / 2];
  333.       }
  334.     else
  335.       {
  336.         max_chain_length = 0;
  337.         median_chain_length = 0;
  338.       }
  339.     if (c->unique_count > 0)
  340.       {
  341.         max_entry_size = entry_size[c->unique_count - 1];
  342.         median_entry_size = entry_size[c->unique_count / 2];
  343.       }
  344.     else
  345.       {
  346.         max_entry_size = 0;
  347.         median_entry_size = 0;
  348.       }

  349.     xfree (chain_length);
  350.     xfree (entry_size);
  351.   }

  352.   printf_filtered (_("  Cached '%s' statistics:\n"), type);
  353.   printf_filtered (_("    Total object count%ld\n"), c->total_count);
  354.   printf_filtered (_("    Unique object count: %lu\n"), c->unique_count);
  355.   printf_filtered (_("    Percentage of duplicates, by count: "));
  356.   print_percentage (c->total_count - c->unique_count, c->total_count);
  357.   printf_filtered ("\n");

  358.   printf_filtered (_("    Total object size:   %ld\n"), c->total_size);
  359.   printf_filtered (_("    Unique object size:  %ld\n"), c->unique_size);
  360.   printf_filtered (_("    Percentage of duplicates, by size:  "));
  361.   print_percentage (c->total_size - c->unique_size, c->total_size);
  362.   printf_filtered ("\n");

  363.   printf_filtered (_("    Max entry size:     %d\n"), max_entry_size);
  364.   printf_filtered (_("    Average entry size: "));
  365.   if (c->unique_count > 0)
  366.     printf_filtered ("%ld\n", c->unique_size / c->unique_count);
  367.   else
  368.     /* i18n: "Average entry size: (not applicable)".  */
  369.     printf_filtered (_("(not applicable)\n"));
  370.   printf_filtered (_("    Median entry size:  %d\n"), median_entry_size);
  371.   printf_filtered ("\n");

  372.   printf_filtered (_("    \
  373. Total memory used by bcache, including overhead: %ld\n"),
  374.                    c->structure_size);
  375.   printf_filtered (_("    Percentage memory overhead: "));
  376.   print_percentage (c->structure_size - c->unique_size, c->unique_size);
  377.   printf_filtered (_("    Net memory savings:         "));
  378.   print_percentage (c->total_size - c->structure_size, c->total_size);
  379.   printf_filtered ("\n");

  380.   printf_filtered (_("    Hash table size:           %3d\n"),
  381.                    c->num_buckets);
  382.   printf_filtered (_("    Hash table expands:        %lu\n"),
  383.                    c->expand_count);
  384.   printf_filtered (_("    Hash table hashes:         %lu\n"),
  385.                    c->total_count + c->expand_hash_count);
  386.   printf_filtered (_("    Half hash misses:          %lu\n"),
  387.                    c->half_hash_miss_count);
  388.   printf_filtered (_("    Hash table population:     "));
  389.   print_percentage (occupied_buckets, c->num_buckets);
  390.   printf_filtered (_("    Median hash chain length:  %3d\n"),
  391.                    median_chain_length);
  392.   printf_filtered (_("    Average hash chain length: "));
  393.   if (c->num_buckets > 0)
  394.     printf_filtered ("%3lu\n", c->unique_count / c->num_buckets);
  395.   else
  396.     /* i18n: "Average hash chain length: (not applicable)".  */
  397.     printf_filtered (_("(not applicable)\n"));
  398.   printf_filtered (_("    Maximum hash chain length: %3d\n"),
  399.                    max_chain_length);
  400.   printf_filtered ("\n");
  401. }

  402. int
  403. bcache_memory_used (struct bcache *bcache)
  404. {
  405.   if (bcache->total_count == 0)
  406.     return 0;
  407.   return obstack_memory_used (&bcache->cache);
  408. }