When using C-string lookup keys in a dynahash.c hash table, use strncpy()
authorTom Lane <tgl@sss.pgh.pa.us>
Sat, 18 Jun 2005 20:51:59 +0000 (20:51 +0000)
committerTom Lane <tgl@sss.pgh.pa.us>
Sat, 18 Jun 2005 20:51:59 +0000 (20:51 +0000)
not memcpy() to copy the offered key into the hash table during HASH_ENTER.
This avoids possible core dump if the passed key is located very near the
end of memory.  Per report from Stefan Kaltenbrunner.

src/backend/utils/hash/dynahash.c
src/include/utils/hsearch.h

index 6480993fde23659c7d512152b4ca0100a34ceb35..9f4512eacd3e749d9042e4c1fdaa2ae99a1c87c6 100644 (file)
@@ -144,6 +144,14 @@ hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
        else
                hashp->match = memcmp;
 
+       /*
+        * Similarly, the key-copying function defaults to strncpy() or memcpy().
+        */
+       if (hashp->hash == string_hash)
+               hashp->keycopy = (HashCopyFunc) strncpy;
+       else
+               hashp->keycopy = memcpy;
+
        if (flags & HASH_SHARED_MEM)
        {
                /*
@@ -644,7 +652,7 @@ hash_search(HTAB *hashp,
 
                        /* copy key into record */
                        currBucket->hashvalue = hashvalue;
-                       memcpy(ELEMENTKEY(currBucket), keyPtr, hctl->keysize);
+                       hashp->keycopy(ELEMENTKEY(currBucket), keyPtr, hctl->keysize);
 
                        /* caller is expected to fill the data field on return */
 
index e6b508b0d662ad2ca9ad18d0c76f696f52cdc9cd..1d42183c8c80aae73b4497b664143aa69d54c92c 100644 (file)
@@ -24,6 +24,7 @@
 typedef uint32 (*HashValueFunc) (const void *key, Size keysize);
 typedef int (*HashCompareFunc) (const void *key1, const void *key2,
                                                                Size keysize);
+typedef void *(*HashCopyFunc) (void *dest, const void *src, Size keysize);
 
 /*
  * Space allocation function for a hashtable --- designed to match malloc().
@@ -108,6 +109,7 @@ typedef struct HTAB
                                                                 * used */
        char       *tabname;            /* table name (for error messages) */
        bool            isshared;               /* true if table is in shared memory */
+       HashCopyFunc keycopy;           /* key copying function */
 } HTAB;
 
 /* Parameter data structure for hash_create */