Commit 757bb44d4a for openssl.org
commit 757bb44d4a2977a04087821ee237bfded7c5d788
Author: Daniel Kubec <kubec@openssl.foundation>
Date: Thu Nov 5 15:16:26 2026 +0100
Add intrusive queues and hash tables, replacing ossl_ht
As a data structure it is a clear 3 to 5x win, but on OpenSSL's steady-state
packet paths the table is a small slice of the work, so the end-to-end gain
there is modest. The big wins are where the old code had pathological or
allocation-heavy behaviour. A DTLS or QUIC packet costs tens of thousands of
instructions in record processing and crypto, so these savings are low
single-digit percent of per-packet cost at best.
Intrusive hashtables eliminate per-operation allocation and pointer chasing.
Embedding the link in the object gives better cache locality and fewer dependent
loads for the prefetcher to stumble on, while static layout leaves the compiler
room to inline and optimize across the table code. Where the table dominates the
hot path, even a single thread benefits clearly. Under concurrency the gain
compounds: with fewer instructions, lower memory access complexity and no
allocator calls, the critical section is typically much shorter and the lock is
held far less.
- DEFINE_HTABLE_OF(name, type, bits) has 1 << bits buckets, fixed at
compile time. The table lives wherever it is declared, allocates
nothing, never rehashes and has nothing to free.
- DEFINE_HTABLE_KEYED_OF is the same table with a 128-bit key drawn from
the private DRBG at init and a generated inline SipHash-2-4 hash, for
keys the peer chooses. It has no library consumer yet;
test/htable_test.c drives it through a copy of scan_ext_flags() over
real certificates, including a hash flood.
- DEFINE_HTABLE_DYN_OF starts with its buckets inline and doubles them,
up to a maximum, once it holds more elements than buckets. The element
stores its hash, so growing does not hash again and a lookup compares
keys only where the hash matches. A grow that cannot allocate keeps
the current buckets, raises no error and is tried again at the next
add, so adding still cannot fail.
- The namemap's name to number table becomes a fixed table of 1024
buckets read without a lock. An entry holds the name once, for both
the table and the number's stack of names.
- The X509_STORE's name to objects table becomes a growable table. The
hash of a name's canonical encoding is kept in the X509_NAME, computed
along with that encoding, so a lookup does not hash the name again.
Assisted-by: Claude:claude-fable-5-2
Reviewed-by: Tomas Mraz <tomas@openssl.foundation>
Reviewed-by: Neil Horman <nhorman@openssl.org>
Merge-date: Mon Nov 23 16:54:47 2026
Merged-from: https://github.com/openssl/openssl/pull/33392
diff --git a/.clang-format b/.clang-format
index 3cdf7345d9..80d8d0c9c8 100644
--- a/.clang-format
+++ b/.clang-format
@@ -25,6 +25,13 @@ ForEachMacros:
- "OSSL_LIST_FOREACH_DELSAFE_FROM"
- "OSSL_LIST_FOREACH_REV_DELSAFE"
- "OSSL_LIST_FOREACH_REV_DELSAFE_FROM"
+ - "OSSL_HTABLE_FOREACH"
+ - "OSSL_HTABLE_FOREACH_DELSAFE"
+ - "OSSL_HTABLE_FOREACH_RCU"
+ - "OSSL_QUEUE_FOREACH"
+ - "OSSL_QUEUE_FOREACH_DELSAFE"
+ - "OSSL_QUEUE_WALK"
+ - "OSSL_QUEUE_WALK_DELSAFE"
- "OSSL_RBT_FOREACH"
- "OSSL_RBT_FOREACH_SAFE"
- "OSSL_RBT_FOREACH_REVERSE"
@@ -656,6 +663,7 @@ TypeNames:
- "OSSL_PROVIDER"
- "OSSL_PROVIDER_INFO"
- "OSSL_provider_init_fn"
+ - "OSSL_QNODE"
- "OSSL_QRL_ENC_LEVEL"
- "OSSL_QRL_ENC_LEVEL_SET"
- "OSSL_QRX"
@@ -667,6 +675,7 @@ TypeNames:
- "OSSL_QTX_ARGS"
- "OSSL_QTX_IOVEC"
- "OSSL_QTX_PKT"
+ - "OSSL_QUEUE"
- "OSSL_QUIC_ACK_RANGE"
- "ossl_quic_demux_cb_fn"
- "OSSL_QUIC_FRAME_ACK"
@@ -1142,6 +1151,7 @@ TypeNames:
# OpenSSL uses macros extensively. Tell clang-format about them.
TypenameMacros:
- "LHASH_OF"
+ - "OSSL_HTABLE"
- "OSSL_LIST"
- "OSSL_RBT_ENTRY"
- "OSSL_RBT_HEAD"
diff --git a/.gitignore b/.gitignore
index cb35e280a5..c35c5c57c2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -351,6 +351,7 @@ providers/implementations/rands/test_rng.inc
/test/evp_pkey_ctx_new_from_name
/test/threadstest_fips
/test/timing_load_creds
+/test/timing_namemap_x509store
# Demo applications
/demos/bio/client-arg
diff --git a/crypto/core_namemap.c b/crypto/core_namemap.c
index 7ba228bdc0..dccfab1ddf 100644
--- a/crypto/core_namemap.c
+++ b/crypto/core_namemap.c
@@ -14,12 +14,127 @@
#include "crypto/context.h"
#include "crypto/evp.h"
-#define NAMEMAP_HT_BUCKETS 512
-
+/* Names are told apart by their first NAMEMAP_NAME_LEN characters. */
#define NAMEMAP_NAME_LEN 64
-HT_START_KEY_DEFN(namenum_key)
-HT_DEF_KEY_FIELD_CHAR_ARRAY(name, NAMEMAP_NAME_LEN)
-HT_END_KEY_DEFN(NAMENUM_KEY)
+
+/* 1 << NAMEMAP_HT_BITS buckets; chains grow beyond that many names. */
+#define NAMEMAP_HT_BITS 10
+
+/*
+ * A name, held once: it is an element of the name->number table and its
+ * |name| is the string stored in the number->names stack, which owns it.
+ * Nothing changes after the entry has been added, and entries are only
+ * freed with the namemap, so the table is read without a lock.
+ */
+typedef struct namemap_entry_st {
+ OSSL_QUEUE_MEMBER(namenum);
+ uint64_t hash; /* of the folded key */
+ size_t keylen; /* strlen(name), at most NAMEMAP_NAME_LEN */
+ int number;
+ char name[1]; /* as registered, NUL terminated */
+} NAMEMAP_ENTRY;
+
+DEFINE_QUEUE_OF(namenum, NAMEMAP_ENTRY);
+DEFINE_HTABLE_OF(namenum, NAMEMAP_ENTRY, NAMEMAP_HT_BITS);
+DEFINE_HTABLE_RCU_OF(namenum, NAMEMAP_ENTRY);
+
+/*
+ * Names compare case insensitively, by clearing the bit that tells an upper
+ * from a lower case letter. Two names are the same when their keys, the
+ * first NAMEMAP_NAME_LEN characters folded this way, are.
+ */
+#if defined(CHARSET_EBCDIC) && !defined(CHARSET_EBCDIC_TEST)
+#define NAMEMAP_FOLD 0xbfU
+#else
+#define NAMEMAP_FOLD 0xdfU
+#endif
+
+/*
+ * Keys are hashed and compared a word at a time. The words are read in the
+ * host's byte order, which is as good as any: neither a word nor a hash
+ * leaves the process.
+ */
+static ossl_inline uint64_t namemap_fold64(const char *p)
+{
+ uint64_t w;
+
+ memcpy(&w, p, sizeof(w));
+ return w & (NAMEMAP_FOLD * 0x0101010101010101ULL);
+}
+
+static ossl_inline uint32_t namemap_fold32(const char *p)
+{
+ uint32_t w;
+
+ memcpy(&w, p, sizeof(w));
+ return w & (NAMEMAP_FOLD * 0x01010101U);
+}
+
+/*
+ * The folded key of a name shorter than a word, as one word. Given |len|,
+ * which the callers hash or compare as well, it determines every character:
+ * the two halves of 4 to 7 characters overlap, and so do the first, middle
+ * and last of 1 to 3.
+ */
+static ossl_inline uint64_t namemap_fold_short(const char *p, size_t len)
+{
+ if (len >= 4)
+ return namemap_fold32(p) | (uint64_t)namemap_fold32(p + len - 4) << 32;
+ if (len == 0)
+ return 0;
+ return ((unsigned char)p[0] & NAMEMAP_FOLD)
+ | ((unsigned char)p[len >> 1] & NAMEMAP_FOLD) << 8
+ | ((unsigned char)p[len - 1] & NAMEMAP_FOLD) << 16;
+}
+
+#define NAMEMAP_HASH_MULT 0x9e3779b97f4a7c15ULL
+
+static ossl_inline uint64_t namemap_hash_word(uint64_t h, uint64_t w)
+{
+ h = (h ^ w) * NAMEMAP_HASH_MULT;
+ /* The next word's multiplication must see the high bits of this one */
+ return h ^ (h >> 32);
+}
+
+/*
+ * Hash of the folded key. A name of a word or more is taken a word at a
+ * time, the last word ending at the name's end and overlapping the one
+ * before it unless the length is a multiple of the word size; the length is
+ * hashed too, so that the overlap is unambiguous. The result is mixed, since
+ * the table uses the low bits.
+ */
+static ossl_inline uint64_t namemap_hash(const char *name, size_t keylen)
+{
+ uint64_t h = keylen * NAMEMAP_HASH_MULT;
+ size_t i;
+
+ if (keylen >= sizeof(uint64_t)) {
+ for (i = 0; i + sizeof(uint64_t) < keylen; i += sizeof(uint64_t))
+ h = namemap_hash_word(h, namemap_fold64(name + i));
+ h = namemap_hash_word(h,
+ namemap_fold64(name + keylen - sizeof(uint64_t)));
+ } else {
+ h = namemap_hash_word(h, namemap_fold_short(name, keylen));
+ }
+ return ossl_hash_mix64(h);
+}
+
+static ossl_inline int namemap_key_eq(const NAMEMAP_ENTRY *e, uint64_t hash,
+ const char *name, size_t keylen)
+{
+ size_t i;
+
+ if (e->hash != hash || e->keylen != keylen)
+ return 0;
+ if (keylen < sizeof(uint64_t))
+ return namemap_fold_short(e->name, keylen)
+ == namemap_fold_short(name, keylen);
+ for (i = 0; i + sizeof(uint64_t) < keylen; i += sizeof(uint64_t))
+ if (namemap_fold64(e->name + i) != namemap_fold64(name + i))
+ return 0;
+ return namemap_fold64(e->name + keylen - sizeof(uint64_t))
+ == namemap_fold64(name + keylen - sizeof(uint64_t));
+}
/*-
* The namemap itself
@@ -34,17 +149,21 @@ struct ossl_namemap_st {
/* Flags */
unsigned int stored : 1; /* If 1, it's stored in a library context */
- HT *namenum_ht; /* Name->number mapping */
-
CRYPTO_RWLOCK *lock;
STACK_OF(NAMES) *numnames;
TSAN_QUALIFIER int max_number; /* Current max number */
+
+ /*
+ * Name->number mapping. Added to under |lock|, held for writing; read
+ * without a lock.
+ */
+ OSSL_HTABLE(namenum) namenum_ht;
};
static void name_string_free(char *name)
{
- OPENSSL_free(name);
+ OPENSSL_free(OSSL_CONTAINER_OF(name, NAMEMAP_ENTRY, name));
}
static void names_free(NAMES *n)
@@ -139,19 +258,15 @@ int ossl_namemap_doall_names(const OSSL_NAMEMAP *namemap, int number,
return i > 0;
}
-int ossl_namemap_name2num(const OSSL_NAMEMAP *namemap, const char *name)
-{
- if (name == NULL)
- return 0;
- return ossl_namemap_name2num_n(namemap, name, strlen(name));
-}
-
-int ossl_namemap_name2num_n(const OSSL_NAMEMAP *namemap,
+/*
+ * The number of the name whose key is the first |name_len| characters of
+ * |name|, or 0. All of them are read, so there must be no NUL among them.
+ */
+static ossl_inline int namemap_find(const OSSL_NAMEMAP *namemap,
const char *name, size_t name_len)
{
- int number = 0;
- HT_VALUE *val;
- NAMENUM_KEY key;
+ const NAMEMAP_ENTRY *e;
+ uint64_t hash;
#ifndef FIPS_MODULE
if (namemap == NULL)
@@ -164,16 +279,41 @@ int ossl_namemap_name2num_n(const OSSL_NAMEMAP *namemap,
if (name_len > NAMEMAP_NAME_LEN)
name_len = NAMEMAP_NAME_LEN;
- HT_INIT_RAW_KEY(&key);
- HT_COPY_RAW_KEY_CASE(TO_HT_KEY(&key), name, name_len);
+ hash = namemap_hash(name, name_len);
+ OSSL_HTABLE_FIND_RCU(e, namenum, &namemap->namenum_ht, hash,
+ namemap_key_eq(e, hash, name, name_len));
- val = ossl_ht_get(namemap->namenum_ht, TO_HT_KEY(&key));
+ return e != NULL ? e->number : 0;
+}
- if (val != NULL)
- /* We store a (small) int directly instead of a pointer to it. */
- number = (int)(intptr_t)val->value;
+int ossl_namemap_name2num(const OSSL_NAMEMAP *namemap, const char *name)
+{
+ if (name == NULL)
+ return 0;
+ return namemap_find(namemap, name, strlen(name));
+}
- return number;
+int ossl_namemap_name2num_n(const OSSL_NAMEMAP *namemap,
+ const char *name, size_t name_len)
+{
+ char key[NAMEMAP_NAME_LEN];
+ const char *end = NULL;
+
+ if (name_len > NAMEMAP_NAME_LEN)
+ name_len = NAMEMAP_NAME_LEN;
+
+ /*
+ * A name that ends before |name_len| is not read beyond its NUL: what
+ * would follow counts as NULs, and the length stays |name_len|.
+ */
+ if (name == NULL
+ || (end = memchr(name, '\0', name_len)) != NULL) {
+ memset(key, 0, sizeof(key));
+ if (end != NULL)
+ memcpy(key, name, end - name);
+ name = key;
+ }
+ return namemap_find(namemap, name, name_len);
}
const char *ossl_namemap_num2name(const OSSL_NAMEMAP *namemap, int number,
@@ -197,12 +337,14 @@ const char *ossl_namemap_num2name(const OSSL_NAMEMAP *namemap, int number,
return ret;
}
-/* This function is not thread safe, the namemap must be locked */
-static int numname_insert(OSSL_NAMEMAP *namemap, int number,
- const char *name)
+/*
+ * Add |name| to the names of |number|, or as the first name of a new number
+ * if that is 0. The stack takes ownership of the entry that |name| is part
+ * of. This function is not thread safe, the namemap must be locked.
+ */
+static int numname_insert(OSSL_NAMEMAP *namemap, int number, char *name)
{
NAMES *names;
- char *tmpname;
if (number > 0) {
names = sk_NAMES_value(namemap->numnames, number - 1);
@@ -217,25 +359,19 @@ static int numname_insert(OSSL_NAMEMAP *namemap, int number,
return 0;
}
- if ((tmpname = OPENSSL_strdup(name)) == NULL)
- goto err;
-
- if (!sk_OPENSSL_STRING_push(names, tmpname))
- goto err;
- tmpname = NULL;
-
if (number <= 0) {
- if (!sk_NAMES_push(namemap->numnames, names))
- goto err;
+ /* Reserve the slot first, so that the pushes below cannot fail */
+ if (!sk_OPENSSL_STRING_reserve(names, 1)
+ || !sk_NAMES_push(namemap->numnames, names)) {
+ sk_OPENSSL_STRING_free(names);
+ return 0;
+ }
number = sk_NAMES_num(namemap->numnames);
}
- return number;
-err:
- if (number <= 0)
- sk_OPENSSL_STRING_pop_free(names, name_string_free);
- OPENSSL_free(tmpname);
- return 0;
+ if (!sk_OPENSSL_STRING_push(names, name))
+ return 0;
+ return number;
}
/* This function is not thread safe, the namemap must be locked */
@@ -243,32 +379,31 @@ static int namemap_add_name(OSSL_NAMEMAP *namemap, int number,
const char *name)
{
int ret;
- HT_VALUE val = { 0 };
- NAMENUM_KEY key;
+ size_t len = strlen(name);
+ NAMEMAP_ENTRY *e;
/* If it already exists, we don't add it */
if ((ret = ossl_namemap_name2num(namemap, name)) != 0)
return ret;
- if ((number = numname_insert(namemap, number, name)) == 0)
+ if ((e = OPENSSL_malloc(sizeof(*e) + len)) == NULL)
return 0;
+ ossl_queue_namenum_init_elem(e);
+ memcpy(e->name, name, len + 1);
+ e->keylen = len > NAMEMAP_NAME_LEN ? NAMEMAP_NAME_LEN : len;
+ e->hash = namemap_hash(name, e->keylen);
+
+ if ((number = numname_insert(namemap, number, e->name)) == 0) {
+ OPENSSL_free(e);
+ return 0;
+ }
+ e->number = number;
/* Using tsan_store alone here is safe since we're under lock */
tsan_store(&namemap->max_number, number);
- HT_INIT_RAW_KEY(&key);
- HT_COPY_RAW_KEY_CASE(TO_HT_KEY(&key), name, strlen(name));
-
- val.value = (void *)(intptr_t)number;
- ret = ossl_ht_insert(namemap->namenum_ht, TO_HT_KEY(&key), &val, NULL);
- if (ret <= 0) {
- /*
- * We either got an allocation failure (INTERNAL_ERROR), or
- * hit too many conflicts in the table (TOO_MANY_NAMES)
- */
- ERR_raise(ERR_LIB_CRYPTO, (ret < 0) ? CRYPTO_R_TOO_MANY_NAMES : ERR_R_INTERNAL_ERROR);
- return 0;
- }
+ /* Publish the finished entry to the lock-free readers; cannot fail */
+ ossl_htable_namenum_add_rcu(&namemap->namenum_ht, e, e->hash);
return number;
}
@@ -528,19 +663,14 @@ OSSL_NAMEMAP *ossl_namemap_stored(OSSL_LIB_CTX *libctx)
OSSL_NAMEMAP *ossl_namemap_new(OSSL_LIB_CTX *libctx)
{
OSSL_NAMEMAP *namemap;
- HT_CONFIG htconf = { NULL, NULL, NULL, NAMEMAP_HT_BUCKETS, 1, 1, 0 };
-
- htconf.ctx = libctx;
if ((namemap = OPENSSL_zalloc(sizeof(*namemap))) == NULL)
goto err;
+ ossl_htable_namenum_init(&namemap->namenum_ht);
if ((namemap->lock = CRYPTO_THREAD_lock_new()) == NULL)
goto err;
- if ((namemap->namenum_ht = ossl_ht_new(&htconf)) == NULL)
- goto err;
-
if ((namemap->numnames = sk_NAMES_new_null()) == NULL)
goto err;
@@ -556,10 +686,9 @@ void ossl_namemap_free(OSSL_NAMEMAP *namemap)
if (namemap == NULL || namemap->stored)
return;
+ /* The names stacks own the entries of the name->number table */
sk_NAMES_pop_free(namemap->numnames, names_free);
- ossl_ht_free(namemap->namenum_ht);
-
CRYPTO_THREAD_lock_free(namemap->lock);
OPENSSL_free(namemap);
}
diff --git a/crypto/hashtable/build.info b/crypto/hashtable/build.info
index b13615d5ab..72581a53f5 100644
--- a/crypto/hashtable/build.info
+++ b/crypto/hashtable/build.info
@@ -1,5 +1,5 @@
LIBS=../../libcrypto
-$COMMON=hashtable.c hashfunc.c
+$COMMON=hashfunc.c
SOURCE[../../libcrypto]=$COMMON
SOURCE[../../providers/libfips.a]=$COMMON
diff --git a/crypto/hashtable/hashtable.c b/crypto/hashtable/hashtable.c
deleted file mode 100644
index 132e3ada47..0000000000
--- a/crypto/hashtable/hashtable.c
+++ /dev/null
@@ -1,896 +0,0 @@
-/*
- * Copyright 2024-2026 The OpenSSL Project Authors. All Rights Reserved.
- *
- * Licensed under the Apache License 2.0 (the "License"). You may not use
- * this file except in compliance with the License. You can obtain a copy
- * in the file LICENSE in the source distribution or at
- * https://www.openssl.org/source/license.html
- *
- *
- *
- * Notes On hash table design and layout
- * This hashtable uses a hopscotch algorithm to do indexing. The data structure
- * looks as follows:
- *
- * hash +--------------+
- * value+------->+ HT_VALUE |
- * + +--------------+
- * +-------+
- * | |
- * +---------------------------------------------------------+
- * | | | | | |
- * | entry | entry | entry | entry | |
- * | | | | | |
- * +---------------------------------------------------------+
- * | | |
- * | | |
- * +---------------------------------------------------------+
- * | + + +
- * | neighborhood[0] neighborhood[1] |
- * | |
- * | |
- * +---------------------------------------------------------+
- * |
- * +
- * neighborhoods
- *
- * On lookup/insert/delete, the items key is hashed to a 64 bit value
- * and the result is masked to provide an index into the neighborhoods
- * table. Once a neighborhood is determined, an in-order search is done
- * of the elements in the neighborhood indexes entries for a matching hash
- * value, if found, the corresponding HT_VALUE is used for the respective
- * operation. The number of entries in a neighborhood is determined at build
- * time based on the cacheline size of the target CPU. The intent is for a
- * neighborhood to have all entries in the neighborhood fit into a single cache
- * line to speed up lookups. If all entries in a neighborhood are in use at the
- * time of an insert, the table is expanded and rehashed.
- *
- * Lockless reads hash table is based on the same design but does not
- * allow growing and deletion. Thus subsequent neighborhoods are always
- * searched for a match until an empty entry is found.
- */
-
-#include <string.h>
-#include <internal/rcu.h>
-#include <internal/hashtable.h>
-#include <internal/hashfunc.h>
-#include <openssl/rand.h>
-
-/*
- * gcc defines __SANITIZE_THREAD__
- * but clang uses the feature attributes api
- * map the latter to the former
- */
-#if defined(__clang__) && defined(__has_feature)
-#if __has_feature(thread_sanitizer)
-#define __SANITIZE_THREADS__
-#endif
-#endif
-
-#ifdef __SANITIZE_THREADS__
-#include <sanitizer/tsan_interface.h>
-#endif
-
-/*
- * When we do a lookup/insert/delete, there is a high likelihood
- * that we will iterate over at least part of the neighborhood list
- * As such, because we design a neighborhood entry to fit into a single
- * cache line it is advantageous, when supported to fetch the entire
- * structure for faster lookups
- */
-#if defined(__GNUC__) || defined(__CLANG__)
-#define PREFETCH_NEIGHBORHOOD(x) __builtin_prefetch(x.entries)
-#define PREFETCH(x) __builtin_prefetch(x)
-#define ALIGN __attribute__((aligned(8)))
-#else
-#define PREFETCH_NEIGHBORHOOD(x)
-#define PREFETCH(x)
-#define ALIGN
-#endif
-
-/*
- * Define our neighborhood list length
- * Note: It should always be a power of 2
- */
-#define DEFAULT_NEIGH_LEN_LOG 4
-#define DEFAULT_NEIGH_LEN (1 << DEFAULT_NEIGH_LEN_LOG)
-
-/*
- * For now assume cache line size is 64 bytes
- */
-#define CACHE_LINE_BYTES 64
-#define CACHE_LINE_ALIGNMENT CACHE_LINE_BYTES
-
-#define NEIGHBORHOOD_LEN (CACHE_LINE_BYTES / sizeof(struct ht_neighborhood_entry_st))
-/*
- * Defines our chains of values
- */
-struct ht_internal_value_st {
- HT_VALUE value;
- HT *ht;
-};
-
-struct ht_neighborhood_entry_st {
- uint64_t hash;
- struct ht_internal_value_st *value;
-} ALIGN;
-
-struct ht_neighborhood_st {
- struct ht_neighborhood_entry_st entries[NEIGHBORHOOD_LEN];
-};
-
-/*
- * Updates to data in this struct
- * require an rcu sync after modification
- * prior to free
- */
-struct ht_mutable_data_st {
- struct ht_neighborhood_st *neighborhoods;
- void *neighborhood_ptr_to_free;
- uint64_t neighborhood_mask;
-};
-
-/*
- * Private data may be updated on the write
- * side only, and so do not require rcu sync
- */
-struct ht_write_private_data_st {
- size_t neighborhood_len;
- size_t value_count;
- int need_sync;
-};
-
-struct ht_internal_st {
- HT_CONFIG config;
- CRYPTO_RCU_LOCK *lock;
- CRYPTO_RWLOCK *atomic_lock;
- struct ht_mutable_data_st *md;
- struct ht_write_private_data_st wpd;
-};
-
-static void free_value(struct ht_internal_value_st *v);
-
-static struct ht_neighborhood_st *alloc_new_neighborhood_list(size_t len,
- void **freeptr)
-{
- struct ht_neighborhood_st *ret;
-
-#if !defined(OPENSSL_SMALL_FOOTPRINT)
- ret = OPENSSL_aligned_alloc_array(len, sizeof(struct ht_neighborhood_st),
- CACHE_LINE_BYTES, freeptr);
-
- /* fall back to regular malloc */
- if (ret == NULL)
-#endif
- {
- ret = *freeptr = OPENSSL_malloc_array(len, sizeof(struct ht_neighborhood_st));
- if (ret == NULL)
- return NULL;
- }
- memset(ret, 0, sizeof(struct ht_neighborhood_st) * len);
- return ret;
-}
-
-static void internal_free_nop(HT_VALUE *v)
-{
- return;
-}
-
-static uint64_t internal_ht_hash_fn(HT_KEY *key)
-{
- return ossl_fnv1a_hash(key->keybuf, key->keysize);
-}
-
-HT *ossl_ht_new(const HT_CONFIG *conf)
-{
- HT *new = OPENSSL_zalloc(sizeof(*new));
-
- if (new == NULL)
- return NULL;
-
- if (conf->lockless_reads && conf->no_rcu)
- goto err;
-
- if (!conf->no_rcu) {
- new->atomic_lock = CRYPTO_THREAD_lock_new();
- if (new->atomic_lock == NULL)
- goto err;
- }
- memcpy(&new->config, conf, sizeof(*conf));
-
- if (new->config.init_neighborhoods != 0) {
- new->wpd.neighborhood_len = new->config.init_neighborhoods;
- /* round up to the next power of 2 */
- new->wpd.neighborhood_len--;
- new->wpd.neighborhood_len |= new->wpd.neighborhood_len >> 1;
- new->wpd.neighborhood_len |= new->wpd.neighborhood_len >> 2;
- new->wpd.neighborhood_len |= new->wpd.neighborhood_len >> 4;
- new->wpd.neighborhood_len |= new->wpd.neighborhood_len >> 8;
- new->wpd.neighborhood_len |= new->wpd.neighborhood_len >> 16;
- new->wpd.neighborhood_len++;
- } else {
- new->wpd.neighborhood_len = DEFAULT_NEIGH_LEN;
- }
-
- if (new->config.ht_free_fn == NULL)
- new->config.ht_free_fn = internal_free_nop;
-
- new->md = OPENSSL_zalloc(sizeof(*new->md));
- if (new->md == NULL)
- goto err;
-
- new->md->neighborhoods = alloc_new_neighborhood_list(new->wpd.neighborhood_len,
- &new->md->neighborhood_ptr_to_free);
- if (new->md->neighborhoods == NULL)
- goto err;
- new->md->neighborhood_mask = new->wpd.neighborhood_len - 1;
-
- if (!conf->no_rcu) {
- new->lock = ossl_rcu_lock_new(1, conf->ctx);
- if (new->lock == NULL)
- goto err;
- }
- if (new->config.ht_hash_fn == NULL)
- new->config.ht_hash_fn = internal_ht_hash_fn;
-
- return new;
-
-err:
- if (!conf->no_rcu) {
- CRYPTO_THREAD_lock_free(new->atomic_lock);
- ossl_rcu_lock_free(new->lock);
- }
- if (new->md != NULL)
- OPENSSL_free(new->md->neighborhood_ptr_to_free);
- OPENSSL_free(new->md);
- OPENSSL_free(new);
- return NULL;
-}
-
-int ossl_ht_read_lock(HT *htable)
-{
- if (htable->config.no_rcu)
- return 1;
-
- return ossl_rcu_read_lock(htable->lock);
-}
-
-void ossl_ht_read_unlock(HT *htable)
-{
- if (htable->config.no_rcu)
- return;
-
- ossl_rcu_read_unlock(htable->lock);
-}
-
-void ossl_ht_write_lock(HT *htable)
-{
- if (htable->config.no_rcu)
- return;
-
- ossl_rcu_write_lock(htable->lock);
- htable->wpd.need_sync = 0;
-}
-
-void ossl_ht_write_unlock(HT *htable)
-{
- int need_sync = htable->wpd.need_sync;
-
- if (htable->config.no_rcu)
- return;
-
- htable->wpd.need_sync = 0;
- ossl_rcu_write_unlock(htable->lock);
- if (need_sync)
- ossl_synchronize_rcu(htable->lock);
-}
-
-static void free_oldmd(void *arg)
-{
- struct ht_mutable_data_st *oldmd = arg;
- size_t i, j;
- size_t neighborhood_len = (size_t)oldmd->neighborhood_mask + 1;
- struct ht_internal_value_st *v;
-
- for (i = 0; i < neighborhood_len; i++) {
- PREFETCH_NEIGHBORHOOD(oldmd->neighborhoods[i + 1]);
- for (j = 0; j < NEIGHBORHOOD_LEN; j++) {
- if (oldmd->neighborhoods[i].entries[j].value != NULL) {
- v = oldmd->neighborhoods[i].entries[j].value;
- v->ht->config.ht_free_fn((HT_VALUE *)v);
- free_value(v);
- }
- }
- }
-
- OPENSSL_free(oldmd->neighborhood_ptr_to_free);
- OPENSSL_free(oldmd);
-}
-
-static int ossl_ht_flush_internal(HT *h)
-{
- struct ht_mutable_data_st *newmd = NULL;
- struct ht_mutable_data_st *oldmd = NULL;
- CRYPTO_RCU_CB_ITEM *cbi = NULL;
-
- newmd = OPENSSL_zalloc(sizeof(*newmd));
- if (newmd == NULL)
- return 0;
-
- newmd->neighborhoods = alloc_new_neighborhood_list(DEFAULT_NEIGH_LEN,
- &newmd->neighborhood_ptr_to_free);
- if (newmd->neighborhoods == NULL) {
- OPENSSL_free(newmd);
- return 0;
- }
-
- newmd->neighborhood_mask = DEFAULT_NEIGH_LEN - 1;
-
- if (!h->config.no_rcu) {
- cbi = ossl_rcu_cb_item_new();
- if (cbi == NULL) {
- OPENSSL_free(newmd->neighborhood_ptr_to_free);
- OPENSSL_free(newmd);
- return 0;
- }
-
- /* Swap the old and new mutable data sets */
- oldmd = ossl_rcu_deref(&h->md);
- ossl_rcu_assign_ptr(&h->md, &newmd);
- } else {
- oldmd = h->md;
- h->md = newmd;
- }
-
- /* Set the number of entries to 0 */
- h->wpd.value_count = 0;
- h->wpd.neighborhood_len = DEFAULT_NEIGH_LEN;
-
- if (!h->config.no_rcu) {
- ossl_rcu_call(h->lock, cbi, free_oldmd, oldmd);
- h->wpd.need_sync = 1;
- } else {
- free_oldmd(oldmd);
- }
-
- return 1;
-}
-
-int ossl_ht_flush(HT *h)
-{
- return ossl_ht_flush_internal(h);
-}
-
-void ossl_ht_free(HT *h)
-{
- int flush_ok;
-
- if (h == NULL)
- return;
-
- if (h->config.no_rcu) {
- free_oldmd(h->md);
- } else {
- ossl_ht_write_lock(h);
- flush_ok = ossl_ht_flush_internal(h);
- ossl_ht_write_unlock(h);
- /* Freeing the lock does a final sync for us */
- CRYPTO_THREAD_lock_free(h->atomic_lock);
- ossl_rcu_lock_free(h->lock);
- if (flush_ok) {
- OPENSSL_free(h->md->neighborhood_ptr_to_free);
- OPENSSL_free(h->md);
- } else {
- free_oldmd(h->md);
- }
- }
- OPENSSL_free(h);
-}
-
-size_t ossl_ht_count(HT *h)
-{
- size_t count;
-
- count = h->wpd.value_count;
- return count;
-}
-
-void ossl_ht_foreach_until(HT *h, int (*cb)(HT_VALUE *obj, void *arg),
- void *arg)
-{
- size_t i, j;
- struct ht_mutable_data_st *md;
-
- md = ossl_rcu_deref(&h->md);
- for (i = 0; i < md->neighborhood_mask + 1; i++) {
- PREFETCH_NEIGHBORHOOD(md->neighborhoods[i + 1]);
- for (j = 0; j < NEIGHBORHOOD_LEN; j++) {
- if (md->neighborhoods[i].entries[j].value != NULL) {
- if (!cb((HT_VALUE *)md->neighborhoods[i].entries[j].value, arg))
- goto out;
- }
- }
- }
-out:
- return;
-}
-
-HT_VALUE_LIST *ossl_ht_filter(HT *h, size_t max_len,
- int (*filter)(HT_VALUE *obj, void *arg),
- void *arg)
-{
- struct ht_mutable_data_st *md;
- HT_VALUE_LIST *list = OPENSSL_zalloc(sizeof(HT_VALUE_LIST)
- + (sizeof(HT_VALUE *) * max_len));
- size_t i, j;
- struct ht_internal_value_st *v;
-
- if (list == NULL)
- return NULL;
-
- /*
- * The list array lives just beyond the end of
- * the struct
- */
- list->list = (HT_VALUE **)(list + 1);
-
- md = ossl_rcu_deref(&h->md);
- for (i = 0; i < md->neighborhood_mask + 1; i++) {
- PREFETCH_NEIGHBORHOOD(md->neighborhoods[i + 1]);
- for (j = 0; j < NEIGHBORHOOD_LEN; j++) {
- v = md->neighborhoods[i].entries[j].value;
- if (v != NULL && filter((HT_VALUE *)v, arg)) {
- list->list[list->list_len++] = (HT_VALUE *)v;
- if (list->list_len == max_len)
- goto out;
- }
- }
- }
-out:
- return list;
-}
-
-void ossl_ht_value_list_free(HT_VALUE_LIST *list)
-{
- OPENSSL_free(list);
-}
-
-static int compare_hash(uint64_t hash1, uint64_t hash2)
-{
- return (hash1 == hash2);
-}
-
-static void free_old_neigh_table(void *arg)
-{
- struct ht_mutable_data_st *oldmd = arg;
-
- OPENSSL_free(oldmd->neighborhood_ptr_to_free);
- OPENSSL_free(oldmd);
-}
-
-/*
- * Increase hash table bucket list
- * must be called with write_lock held
- */
-static int grow_hashtable(HT *h, size_t oldsize)
-{
- struct ht_mutable_data_st *newmd;
- struct ht_mutable_data_st *oldmd = ossl_rcu_deref(&h->md);
- CRYPTO_RCU_CB_ITEM *cbi = NULL;
- int rc = 0;
- uint64_t oldi, oldj, newi, newj;
- uint64_t oldhash;
- struct ht_internal_value_st *oldv;
- int rehashed;
- size_t newsize = oldsize * 2;
-
- if (h->config.lockless_reads)
- goto out;
-
- if ((newmd = OPENSSL_zalloc(sizeof(*newmd))) == NULL)
- goto out;
-
- /* bucket list is always a power of 2 */
- newmd->neighborhoods = alloc_new_neighborhood_list(oldsize * 2,
- &newmd->neighborhood_ptr_to_free);
- if (newmd->neighborhoods == NULL)
- goto out_free;
-
- /* being a power of 2 makes for easy mask computation */
- newmd->neighborhood_mask = (newsize - 1);
-
- /*
- * Now we need to start rehashing entries
- * Note we don't need to use atomics here as the new
- * mutable data hasn't been published
- */
- for (oldi = 0; oldi < h->wpd.neighborhood_len; oldi++) {
- PREFETCH_NEIGHBORHOOD(oldmd->neighborhoods[oldi + 1]);
- for (oldj = 0; oldj < NEIGHBORHOOD_LEN; oldj++) {
- oldv = oldmd->neighborhoods[oldi].entries[oldj].value;
- if (oldv == NULL)
- continue;
- oldhash = oldmd->neighborhoods[oldi].entries[oldj].hash;
- newi = oldhash & newmd->neighborhood_mask;
- rehashed = 0;
- for (newj = 0; newj < NEIGHBORHOOD_LEN; newj++) {
- if (newmd->neighborhoods[newi].entries[newj].value == NULL) {
- newmd->neighborhoods[newi].entries[newj].value = oldv;
- newmd->neighborhoods[newi].entries[newj].hash = oldhash;
- rehashed = 1;
- break;
- }
- }
- if (rehashed == 0) {
- /* we ran out of space in a neighborhood, grow again */
- OPENSSL_free(newmd->neighborhood_ptr_to_free);
- OPENSSL_free(newmd);
- return grow_hashtable(h, newsize);
- }
- }
- }
-
- /*
- * Pre allocate the rcu callback item before assigning the newmd.
- */
- if (!h->config.no_rcu) {
- cbi = ossl_rcu_cb_item_new();
- if (cbi == NULL)
- goto out_free;
- }
-
- /*
- * Now that our entries are all hashed into the new bucket list
- * update our bucket_len and target_max_load
- */
- h->wpd.neighborhood_len = newsize;
-
- /*
- * Now we replace the old mutable data with the new
- */
- if (!h->config.no_rcu) {
- ossl_rcu_assign_ptr(&h->md, &newmd);
- ossl_rcu_call(h->lock, cbi, free_old_neigh_table, oldmd);
- h->wpd.need_sync = 1;
- } else {
- h->md = newmd;
- free_old_neigh_table(oldmd);
- }
- /*
- * And we're done
- */
- rc = 1;
-
-out:
- return rc;
-out_free:
- OPENSSL_free(newmd->neighborhood_ptr_to_free);
- OPENSSL_free(newmd);
- goto out;
-}
-
-static void free_old_ht_value(void *arg)
-{
- HT_VALUE *h = (HT_VALUE *)arg;
-
- /*
- * Note, this is only called on replacement,
- * the caller is responsible for freeing the
- * held data, we just need to free the wrapping
- * struct here
- */
- OPENSSL_free(h);
-}
-
-static ossl_inline int match_key(HT_KEY *a, HT_KEY *b)
-{
- /*
- * keys match if they are both present, the same size
- * and compare equal in memory
- */
- PREFETCH(a->keybuf);
- PREFETCH(b->keybuf);
- if (a->keybuf != NULL && b->keybuf != NULL)
- return a->keysize == b->keysize
- && !memcmp(a->keybuf, b->keybuf, a->keysize);
-
- return 1;
-}
-
-static int ossl_ht_insert_locked(HT *h, uint64_t hash,
- struct ht_internal_value_st *newval,
- HT_VALUE **olddata)
-{
- struct ht_mutable_data_st *md = h->md;
- uint64_t neigh_idx_start = hash & md->neighborhood_mask;
- uint64_t neigh_idx = neigh_idx_start;
- size_t j;
- uint64_t ihash;
- HT_VALUE *ival;
- size_t empty_idx = SIZE_MAX;
- int lockless_reads = h->config.lockless_reads;
-
- do {
- PREFETCH_NEIGHBORHOOD(md->neighborhoods[neigh_idx]);
-
- for (j = 0; j < NEIGHBORHOOD_LEN; j++) {
- if (!h->config.no_rcu)
- ival = ossl_rcu_deref(&md->neighborhoods[neigh_idx].entries[j].value);
- else
- ival = (HT_VALUE *)md->neighborhoods[neigh_idx].entries[j].value;
- if (ival == NULL) {
- empty_idx = j;
- /* lockless_reads implies no deletion, we can break out */
- if (lockless_reads)
- goto not_found;
- continue;
- }
- if (!h->config.no_rcu) {
- if (!CRYPTO_atomic_load(&md->neighborhoods[neigh_idx].entries[j].hash,
- &ihash, h->atomic_lock))
- return 0;
- } else {
- ihash = md->neighborhoods[neigh_idx].entries[j].hash;
- }
- if (compare_hash(hash, ihash) && match_key(&newval->value.key, &ival->key)) {
- if (olddata == NULL) {
- /* This would insert a duplicate -> fail */
- return 0;
- }
- /* Do a replacement */
- if (!h->config.no_rcu) {
- CRYPTO_RCU_CB_ITEM *cbi = ossl_rcu_cb_item_new();
- if (cbi == NULL)
- return 0;
- if (!CRYPTO_atomic_store(&md->neighborhoods[neigh_idx].entries[j].hash,
- hash, h->atomic_lock)) {
- ossl_rcu_cb_item_free(cbi);
- return 0;
- }
- *olddata = (HT_VALUE *)md->neighborhoods[neigh_idx].entries[j].value;
- ossl_rcu_assign_ptr(&md->neighborhoods[neigh_idx].entries[j].value,
- &newval);
- ossl_rcu_call(h->lock, cbi, free_old_ht_value, *olddata);
- } else {
- md->neighborhoods[neigh_idx].entries[j].hash = hash;
- *olddata = (HT_VALUE *)md->neighborhoods[neigh_idx].entries[j].value;
- md->neighborhoods[neigh_idx].entries[j].value = newval;
- }
- h->wpd.need_sync = 1;
- return 1;
- }
- }
- if (!lockless_reads)
- break;
- /* Continue search in subsequent neighborhoods */
- neigh_idx = (neigh_idx + 1) & md->neighborhood_mask;
- } while (neigh_idx != neigh_idx_start);
-
-not_found:
- /* If we get to here, its just an insert */
- if (empty_idx == SIZE_MAX)
- return -1; /* out of space */
- if (!h->config.no_rcu) {
- if (!CRYPTO_atomic_store(&md->neighborhoods[neigh_idx].entries[empty_idx].hash,
- hash, h->atomic_lock))
- return 0;
- ossl_rcu_assign_ptr(&md->neighborhoods[neigh_idx].entries[empty_idx].value,
- &newval);
- } else {
- md->neighborhoods[neigh_idx].entries[empty_idx].hash = hash;
- md->neighborhoods[neigh_idx].entries[empty_idx].value = newval;
- }
- h->wpd.value_count++;
- return 1;
-}
-
-static struct ht_internal_value_st *alloc_new_value(HT *h, HT_KEY *key,
- void *data,
- uintptr_t *type)
-{
- struct ht_internal_value_st *tmp;
- size_t nvsize = sizeof(*tmp);
-
- if (h->config.collision_check == 1)
- nvsize += key->keysize;
-
- tmp = OPENSSL_malloc(nvsize);
-
- if (tmp == NULL)
- return NULL;
-
- tmp->ht = h;
- tmp->value.value = data;
- tmp->value.type_id = type;
- tmp->value.key.keybuf = NULL;
- if (h->config.collision_check) {
- tmp->value.key.keybuf = (uint8_t *)(tmp + 1);
- tmp->value.key.keysize = key->keysize;
- memcpy(tmp->value.key.keybuf, key->keybuf, key->keysize);
- }
-
- return tmp;
-}
-
-static void free_value(struct ht_internal_value_st *v)
-{
- OPENSSL_free(v);
-}
-
-int ossl_ht_insert(HT *h, HT_KEY *key, HT_VALUE *data, HT_VALUE **olddata)
-{
- struct ht_internal_value_st *newval = NULL;
- uint64_t hash;
- int rc = 0;
- int i;
-
- if (data->value == NULL)
- goto out;
-
- rc = -1;
- newval = alloc_new_value(h, key, data->value, data->type_id);
- if (newval == NULL)
- goto out;
-
- if (key->cached_hash)
- hash = key->cached_hash;
- else
- hash = key->cached_hash = newval->value.key.cached_hash = h->config.ht_hash_fn(key);
-
- /*
- * we have to take our lock here to prevent other changes
- * to the bucket list
- */
- for (i = 0;
- (rc = ossl_ht_insert_locked(h, hash, newval, olddata)) == -1
- && i <= (int)NEIGHBORHOOD_LEN;
- ++i)
- if (!grow_hashtable(h, h->wpd.neighborhood_len)) {
- rc = -1;
- break;
- }
-
- if (rc <= 0)
- free_value(newval);
-
-out:
- return rc;
-}
-
-HT_VALUE *ossl_ht_get(HT *h, HT_KEY *key)
-{
- struct ht_mutable_data_st *md;
- uint64_t hash;
- uint64_t neigh_idx_start;
- uint64_t neigh_idx;
- struct ht_internal_value_st *ival = NULL;
- size_t j;
- uint64_t ehash;
- int lockless_reads = h->config.lockless_reads;
-
- if (key->cached_hash)
- hash = key->cached_hash;
- else
- hash = key->cached_hash = h->config.ht_hash_fn(key);
-
- if (!h->config.no_rcu)
- md = ossl_rcu_deref(&h->md);
- else
- md = h->md;
- neigh_idx = neigh_idx_start = hash & md->neighborhood_mask;
- do {
- PREFETCH_NEIGHBORHOOD(md->neighborhoods[neigh_idx]);
- for (j = 0; j < NEIGHBORHOOD_LEN; j++) {
- if (!h->config.no_rcu)
- ival = ossl_rcu_deref(&md->neighborhoods[neigh_idx].entries[j].value);
- else
- ival = md->neighborhoods[neigh_idx].entries[j].value;
- if (ival == NULL) {
- if (lockless_reads)
- /* lockless_reads implies no deletion, we can break out */
- return NULL;
- continue;
- }
- if (!h->config.no_rcu) {
- if (!CRYPTO_atomic_load(&md->neighborhoods[neigh_idx].entries[j].hash,
- &ehash, h->atomic_lock))
- return NULL;
- } else {
- ehash = md->neighborhoods[neigh_idx].entries[j].hash;
- }
- if (compare_hash(hash, ehash) && match_key(&ival->value.key, key))
- return (HT_VALUE *)ival;
- }
- if (!lockless_reads)
- break;
- /* Continue search in subsequent neighborhoods */
- neigh_idx = (neigh_idx + 1) & md->neighborhood_mask;
- } while (neigh_idx != neigh_idx_start);
-
- return NULL;
-}
-
-static void free_old_entry(void *arg)
-{
- struct ht_internal_value_st *v = arg;
-
- v->ht->config.ht_free_fn((HT_VALUE *)v);
- free_value(v);
-}
-
-int ossl_ht_delete(HT *h, HT_KEY *key)
-{
- uint64_t hash;
- uint64_t neigh_idx;
- size_t j;
- struct ht_internal_value_st *v = NULL;
- HT_VALUE *nv = NULL;
- int rc = 0;
-
- if (h->config.lockless_reads)
- return 0;
-
- if (key->cached_hash)
- hash = key->cached_hash;
- else
- hash = key->cached_hash = h->config.ht_hash_fn(key);
-
- neigh_idx = hash & h->md->neighborhood_mask;
- PREFETCH_NEIGHBORHOOD(h->md->neighborhoods[neigh_idx]);
- for (j = 0; j < NEIGHBORHOOD_LEN; j++) {
- v = (struct ht_internal_value_st *)h->md->neighborhoods[neigh_idx].entries[j].value;
- if (v == NULL)
- continue;
- if (compare_hash(hash, h->md->neighborhoods[neigh_idx].entries[j].hash)
- && match_key(key, &v->value.key)) {
- if (!h->config.no_rcu) {
- CRYPTO_RCU_CB_ITEM *cbi = ossl_rcu_cb_item_new();
- if (cbi == NULL)
- break;
- if (!CRYPTO_atomic_store(&h->md->neighborhoods[neigh_idx].entries[j].hash,
- 0, h->atomic_lock)) {
- ossl_rcu_cb_item_free(cbi);
- break;
- }
- ossl_rcu_assign_ptr(&h->md->neighborhoods[neigh_idx].entries[j].value, &nv);
- ossl_rcu_call(h->lock, cbi, free_old_entry, v);
- } else {
- h->md->neighborhoods[neigh_idx].entries[j].hash = 0;
- h->md->neighborhoods[neigh_idx].entries[j].value = NULL;
- free_old_entry(v);
- }
- h->wpd.value_count--;
- h->wpd.need_sync = 1;
- rc = 1;
- break;
- }
- }
-
- return rc;
-}
-
-HT_VALUE *ossl_ht_deref_value(HT *h, HT_VALUE **val)
-{
- HT_VALUE *v;
-
- if (!h->config.no_rcu)
- v = ossl_rcu_deref(val);
- else
- v = *val;
-
- return v;
-}
-
-void *ossl_ht_inner_value(HT *h, HT_VALUE *v)
-{
- void *inner;
-
- if (!h->config.no_rcu) {
- inner = v->value;
- } else {
- inner = v->value;
- OPENSSL_free(v);
- }
-
- return inner;
-}
diff --git a/crypto/property/property.c b/crypto/property/property.c
index 673a690d47..19264bafbc 100644
--- a/crypto/property/property.c
+++ b/crypto/property/property.c
@@ -243,12 +243,7 @@ static void impl_cache_flush_alg(ALGORITHM *alg, STORED_ALGORITHMS *sa)
QUERY *q;
int i;
- /*
- * Instead of iterating over the hashtable with the
- * ossl_ht_foreach_until function, we just traverse the
- * linked list, as it much faster this way, as we avoid having
- * to visit lots of potentially empty nodes
- */
+ /* Traverse the cache lists themselves; there is no table to walk */
for (i = 0; i < MAX_CACHE_LINES; i++) {
if (!CRYPTO_atomic_load_ptr((void **)&sa->cache_lists[i], (void **)&q, sa->alock))
return;
diff --git a/crypto/x509/by_dir.c b/crypto/x509/by_dir.c
index 2314d21e77..1a73e68a24 100644
--- a/crypto/x509/by_dir.c
+++ b/crypto/x509/by_dir.c
@@ -363,11 +363,10 @@ static int get_cert_by_subject_ex(X509_LOOKUP *xl, X509_LOOKUP_TYPE type,
if (ossl_x509_store_read_lock(xl->store_ctx) == 0)
goto finish;
- if (xl->store_ctx->objs_ht)
- objs = ossl_x509_store_ht_get_by_name(xl->store_ctx, name);
- else
- objs = xl->store_ctx->objs;
- if (objs != NULL) {
+ if (xl->store_ctx->objs_ht != NULL) {
+ tmp = ossl_x509_store_ht_get_by_subject(xl->store_ctx, type,
+ name);
+ } else if ((objs = xl->store_ctx->objs) != NULL) {
j = sk_X509_OBJECT_find(objs, &stmp);
tmp = sk_X509_OBJECT_value(objs, j);
}
diff --git a/crypto/x509/by_store.c b/crypto/x509/by_store.c
index 38496699b3..b22c11d2dc 100644
--- a/crypto/x509/by_store.c
+++ b/crypto/x509/by_store.c
@@ -222,17 +222,14 @@ static int by_store_subject(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
OSSL_STORE_SEARCH_free(criterion);
if (ok) {
- STACK_OF(X509_OBJECT) *store_objects;
X509_STORE *store = X509_LOOKUP_get_store(ctx);
if (!ossl_x509_store_read_lock(store))
return 0;
if (store->objs_ht != NULL)
- store_objects = ossl_x509_store_ht_get_by_name(store, name);
- else
- store_objects = store->objs;
- if (store_objects != NULL)
- tmp = X509_OBJECT_retrieve_by_subject(store_objects, type, name);
+ tmp = ossl_x509_store_ht_get_by_subject(store, type, name);
+ else if (store->objs != NULL)
+ tmp = X509_OBJECT_retrieve_by_subject(store->objs, type, name);
X509_STORE_unlock(store);
}
diff --git a/crypto/x509/x509_local.h b/crypto/x509/x509_local.h
index 1f19414588..bb646c979a 100644
--- a/crypto/x509/x509_local.h
+++ b/crypto/x509/x509_local.h
@@ -16,6 +16,7 @@
#include "internal/hashtable.h"
#include <crypto/asn1.h>
+#include <crypto/x509.h>
#define X509V3_conf_add_error_name_value(val) \
ERR_add_error_data(4, "name=", (val)->name, ", value=", (val)->value)
@@ -127,9 +128,13 @@ struct x509_lookup_st {
X509_STORE *store_ctx; /* who owns us */
};
-typedef struct {
- HT_KEY key_header;
-} OBJS_KEY;
+/*
+ * An X509_STORE's table of names (a certificate's subject, a CRL's issuer).
+ * Its elements are the store's objects themselves: one per name, the first
+ * added under it, which holds the other objects sharing that name.
+ */
+DEFINE_QUEUE_OF(x509_objs, X509_OBJECT);
+DEFINE_HTABLE_DYN_OF(x509_objs, X509_OBJECT, 3, 24);
/*
* This is used to hold everything. It is used for all certificate
@@ -139,8 +144,8 @@ typedef struct {
struct x509_store_st {
/* The following is a cache of trusted certs */
int cache; /* if true, stash any hits */
- /* Maps X509_NAME -> STACK_OF(X509_OBJECT) */
- HT *objs_ht;
+ /* Maps X509_NAME -> the X509_OBJECTs of that name */
+ OSSL_HTABLE(x509_objs) *objs_ht;
/*
* Deprecated. Used only in the X509_STORE_get0_objects() for backward
* compatibility.
@@ -191,8 +196,23 @@ int ossl_x509_signing_allowed(const X509 *issuer, const X509 *subject);
int ossl_x509_store_ctx_get_by_subject(const X509_STORE_CTX *ctx, X509_LOOKUP_TYPE type,
const X509_NAME *name, X509_OBJECT *ret);
__owur int ossl_x509_store_read_lock(X509_STORE *xs);
-STACK_OF(X509_OBJECT) *ossl_x509_store_ht_get_by_name(const X509_STORE *store,
- const X509_NAME *xn);
+
+/**
+ * @brief Looks up the first object of a given type and subject name in the
+ * store's hash table.
+ *
+ * The caller must hold the store's lock, and the store must not have been
+ * converted by X509_STORE_get0_objects().
+ *
+ * @param store Store to search.
+ * @param type Type of object wanted, X509_LU_X509 or X509_LU_CRL.
+ * @param xn Subject name (issuer name for a CRL) to look up.
+ *
+ * @returns the matching object, which remains owned by the store, or NULL if
+ * there is none.
+ */
+X509_OBJECT *ossl_x509_store_ht_get_by_subject(const X509_STORE *store,
+ X509_LOOKUP_TYPE type, const X509_NAME *xn);
int ossl_x509_check_rfc822(X509 *x, const char *chk, size_t chklen,
unsigned int flags);
int ossl_x509_check_smtputf8(X509 *x, const char *chk, size_t chklen,
diff --git a/crypto/x509/x509_lu.c b/crypto/x509/x509_lu.c
index 382991792f..d6d30e28d5 100644
--- a/crypto/x509/x509_lu.c
+++ b/crypto/x509/x509_lu.c
@@ -9,15 +9,12 @@
#include <stdio.h>
#include "internal/cryptlib.h"
-#include "internal/hashtable.h"
#include "internal/refcount.h"
#include <openssl/x509.h>
#include "crypto/x509.h"
#include <openssl/x509v3.h>
#include "x509_local.h"
-#define X509_OBJS_HT_BUCKETS 8
-
X509_LOOKUP *X509_LOOKUP_new(X509_LOOKUP_METHOD *method)
{
X509_LOOKUP *ret = OPENSSL_zalloc(sizeof(*ret));
@@ -182,37 +179,91 @@ static int x509_object_cmp(const X509_OBJECT *const *a,
return ret;
}
-static void objs_ht_free(HT_VALUE *v)
+/*
+ * Free the table of names and, if |free_objs|, the objects in it. Otherwise
+ * the objects are left unlinked for the caller, which holds them elsewhere.
+ */
+static void objs_ht_free(OSSL_HTABLE(x509_objs) *ht, int free_objs)
{
- STACK_OF(X509_OBJECT) *objs = v->value;
+ X509_OBJECT *head, *headn;
+ size_t i, n;
- sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
+ if (ht == NULL)
+ return;
+ n = ossl_htable_x509_objs_num_buckets(ht);
+ for (i = 0; i < n; i++)
+ OSSL_HTABLE_FOREACH_DELSAFE (head, headn, x509_objs, ht, i) {
+ if (free_objs) {
+ sk_X509_OBJECT_pop_free(head->same, X509_OBJECT_free);
+ X509_OBJECT_free(head);
+ } else {
+ /* The buckets are discarded whole: no unlinking needed */
+ sk_X509_OBJECT_free(head->same);
+ head->same = NULL;
+ ossl_queue_x509_objs_init_elem(head);
+ }
+ }
+ ossl_htable_x509_objs_cleanup(ht);
+ OPENSSL_free(ht);
}
-static void objs_ht_init_key(OBJS_KEY *key, const X509_NAME *xn)
+/*
+ * The objects of one name, by index: the first one added, |head|, which is
+ * the element of the table, then the ones in |head->same|. NULL past the
+ * last, and for any index if |head| is NULL.
+ */
+static ossl_inline X509_OBJECT *objs_value(X509_OBJECT *head, int i)
{
- /* Empty names have no canonical buffer, but the hash table copies the key. */
- HT_INIT_KEY(key);
- key->key_header.keybuf = xn->canon_enc != NULL ? xn->canon_enc : (unsigned char *)"";
- key->key_header.keysize = xn->canon_enclen;
+ return i == 0 || head == NULL ? head
+ : sk_X509_OBJECT_value(head->same, i - 1);
+}
+
+/*
+ * Call |cb| for every object, those of one name together and in the order
+ * they were added, until it returns 0. The store must be locked.
+ */
+static void objs_ht_foreach_until(OSSL_HTABLE(x509_objs) *ht,
+ int (*cb)(X509_OBJECT *obj, void *arg), void *arg)
+{
+ X509_OBJECT *head, *obj;
+ size_t i, n = ossl_htable_x509_objs_num_buckets(ht);
+ int j;
+
+ for (i = 0; i < n; i++)
+ OSSL_HTABLE_FOREACH (head, x509_objs, ht, i)
+ for (j = 0; (obj = objs_value(head, j)) != NULL; j++)
+ if (!cb(obj, arg))
+ return;
+}
+
+/* The name an object is filed under: a CRL's issuer, a certificate's subject */
+static const X509_NAME *x509_object_name(const X509_OBJECT *obj)
+{
+ return obj->type == X509_LU_CRL ? obj->data.crl->crl.issuer
+ : obj->data.x509->cert_info.subject;
+}
+
+/* The first object of |type| among those of the name led by |head|, or NULL */
+static X509_OBJECT *objs_first_of_type(X509_OBJECT *head, X509_LOOKUP_TYPE type)
+{
+ X509_OBJECT *obj;
+ int i;
+
+ for (i = 0; (obj = objs_value(head, i)) != NULL; i++)
+ if (obj->type == type)
+ break;
+ return obj;
}
X509_STORE *X509_STORE_new(void)
{
X509_STORE *ret = OPENSSL_zalloc(sizeof(*ret));
- HT_CONFIG htconf = {
- .ht_free_fn = objs_ht_free,
- .collision_check = 1,
- .init_neighborhoods = X509_OBJS_HT_BUCKETS,
- .no_rcu = 1,
- };
if (ret == NULL)
return NULL;
- if ((ret->objs_ht = ossl_ht_new(&htconf)) == NULL) {
- ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
+ if ((ret->objs_ht = OPENSSL_malloc(sizeof(*ret->objs_ht))) == NULL)
goto err;
- }
+ ossl_htable_x509_objs_init(ret->objs_ht);
if ((ret->objs = sk_X509_OBJECT_new(x509_object_cmp)) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
@@ -246,7 +297,7 @@ err:
X509_VERIFY_PARAM_free(ret->param);
sk_X509_OBJECT_free(ret->objs);
sk_X509_LOOKUP_free(ret->get_cert_methods);
- ossl_ht_free(ret->objs_ht);
+ objs_ht_free(ret->objs_ht, 1);
CRYPTO_THREAD_lock_free(ret->lock);
OPENSSL_free(ret);
return NULL;
@@ -279,7 +330,7 @@ void X509_STORE_free(X509_STORE *xs)
X509_VERIFY_PARAM_free(xs->param);
CRYPTO_THREAD_lock_free(xs->lock);
CRYPTO_FREE_REF(&xs->references);
- ossl_ht_free(xs->objs_ht);
+ objs_ht_free(xs->objs_ht, 1);
OPENSSL_free(xs);
}
@@ -340,84 +391,103 @@ X509_OBJECT *X509_STORE_CTX_get_obj_by_subject(X509_STORE_CTX *ctx,
return ret;
}
-STACK_OF(X509_OBJECT) *ossl_x509_store_ht_get_by_name(const X509_STORE *store,
+/*
+ * The first of the store's objects named |xn|, of whichever type, or NULL.
+ * The hash of |xn| was computed along with its canonical encoding, so the
+ * name is not hashed again, and it is compared with the names of the objects
+ * stored under that same hash only. The store must be locked.
+ */
+static X509_OBJECT *objs_ht_get_by_name(const X509_STORE *store,
const X509_NAME *xn)
{
- HT_VALUE *v;
- OBJS_KEY key;
- int ret;
+ X509_OBJECT *obj;
if (xn->canon_enc == NULL || xn->modified) {
- ret = i2d_X509_NAME((X509_NAME *)xn, NULL);
- if (ret < 0)
+ if (i2d_X509_NAME((X509_NAME *)xn, NULL) < 0)
return NULL;
}
- objs_ht_init_key(&key, xn);
- v = ossl_ht_get(store->objs_ht, TO_HT_KEY(&key));
- if (v == NULL)
- return NULL;
- v = ossl_rcu_deref(&v);
+ OSSL_HTABLE_FIND(obj, x509_objs, store->objs_ht, xn->canon_hash,
+ X509_NAME_cmp(x509_object_name(obj), xn) == 0);
- return v->value;
+ return obj;
}
-static int x509_name_objs_ht_insert(const X509_STORE *store, const X509_NAME *xn,
- STACK_OF(X509_OBJECT) *objs, X509_OBJECT *obj)
+/*
+ * The first of the store's objects of |type| named |xn|, or NULL. The store
+ * must be locked and must not have been converted by
+ * X509_STORE_get0_objects().
+ */
+X509_OBJECT *ossl_x509_store_ht_get_by_subject(const X509_STORE *store,
+ X509_LOOKUP_TYPE type, const X509_NAME *xn)
{
- int ret = 0, added = 0;
- OBJS_KEY key;
- HT_VALUE val = { 0 };
+ return objs_first_of_type(objs_ht_get_by_name(store, xn), type);
+}
- if (objs != NULL) {
- added = sk_X509_OBJECT_push(objs, obj) != 0;
- return added;
- }
+/* Whether |obj| has the type of |x|, a certificate or a CRL, and equals it */
+static int x509_object_same(const X509_OBJECT *obj, const X509_OBJECT *x)
+{
+ if (obj->type != x->type)
+ return 0;
+ return x->type == X509_LU_X509
+ ? X509_cmp(obj->data.x509, x->data.x509) == 0
+ : X509_CRL_match(obj->data.crl, x->data.crl) == 0;
+}
- if (xn->canon_enc == NULL || xn->modified) {
- ret = i2d_X509_NAME((X509_NAME *)xn, NULL);
- if (ret < 0)
- return 0;
- }
+/*
+ * Whether the objects of the name led by |head| include one equal to |x|, a
+ * certificate or a CRL of that name. They all have the same name, so only
+ * the type and the contents can differ.
+ */
+static int x509_name_objs_match(const X509_OBJECT *head, const X509_OBJECT *x)
+{
+ int i, num;
- objs = sk_X509_OBJECT_new(x509_object_cmp);
- if (objs == NULL)
+ if (head == NULL)
return 0;
+ if (x509_object_same(head, x))
+ return 1;
+ for (i = 0, num = sk_X509_OBJECT_num(head->same); i < num; i++)
+ if (x509_object_same(sk_X509_OBJECT_value(head->same, i), x))
+ return 1;
+ return 0;
+}
- added = sk_X509_OBJECT_push(objs, obj) != 0;
- if (added == 0) {
- sk_X509_OBJECT_free(objs);
- return 0;
+/*
+ * Add |obj| under the name |xn|: to the objects led by |head|, the first one
+ * of that name, or as a new element of the table if there is none yet, which
+ * allocates nothing and only fails for a name that cannot be encoded.
+ */
+static int x509_name_objs_ht_insert(const X509_STORE *store, const X509_NAME *xn,
+ X509_OBJECT *head, X509_OBJECT *obj)
+{
+ obj->same = NULL;
+ if (head != NULL) {
+ if (head->same == NULL
+ && (head->same = sk_X509_OBJECT_new_null()) == NULL)
+ return 0;
+ return sk_X509_OBJECT_push(head->same, obj) != 0;
}
- objs_ht_init_key(&key, xn);
- val.value = (void *)objs;
- ret = ossl_ht_insert(store->objs_ht, TO_HT_KEY(&key), &val, NULL);
- if (ret != 1) {
- sk_X509_OBJECT_free(objs);
- return 0;
+ if (xn->canon_enc == NULL || xn->modified) {
+ if (i2d_X509_NAME((X509_NAME *)xn, NULL) < 0)
+ return 0;
}
+ ossl_queue_x509_objs_init_elem(obj);
+ ossl_htable_x509_objs_add(store->objs_ht, obj, xn->canon_hash);
return 1;
}
-static int obj_ht_foreach_certs(HT_VALUE *v, void *arg)
+static int obj_ht_foreach_certs(X509_OBJECT *obj, void *arg)
{
STACK_OF(X509) **sk = arg;
- STACK_OF(X509_OBJECT) *objs = v->value;
- int i, r;
+ X509 *cert = X509_OBJECT_get0_X509(obj);
- for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
- X509 *cert = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(objs, i));
-
- if (cert == NULL)
- continue;
- r = X509_add_cert(*sk, cert, X509_ADD_FLAG_UP_REF);
- if (r == 0) {
- OSSL_STACK_OF_X509_free(*sk);
- *sk = NULL;
- return 0;
- }
+ if (cert != NULL && !X509_add_cert(*sk, cert, X509_ADD_FLAG_UP_REF)) {
+ OSSL_STACK_OF_X509_free(*sk);
+ *sk = NULL;
+ return 0;
}
return 1;
@@ -453,7 +523,6 @@ int ossl_x509_store_ctx_get_by_subject(const X509_STORE_CTX *ctx, X509_LOOKUP_TY
X509_STORE *store = ctx->store;
X509_LOOKUP *lu;
X509_OBJECT stmp, *tmp = NULL;
- STACK_OF(X509_OBJECT) *objs;
int i, j;
if (store == NULL)
@@ -464,13 +533,10 @@ int ossl_x509_store_ctx_get_by_subject(const X509_STORE_CTX *ctx, X509_LOOKUP_TY
if (!ossl_x509_store_read_lock(store))
return 0;
- if (store->objs_ht != NULL) {
- objs = ossl_x509_store_ht_get_by_name(store, name);
- if (objs != NULL)
- tmp = X509_OBJECT_retrieve_by_subject(objs, type, name);
- } else {
+ if (store->objs_ht != NULL)
+ tmp = ossl_x509_store_ht_get_by_subject(store, type, name);
+ else
tmp = X509_OBJECT_retrieve_by_subject(store->objs, type, name);
- }
X509_STORE_unlock(store);
if (tmp == NULL || type == X509_LU_CRL) {
@@ -510,7 +576,7 @@ int X509_STORE_CTX_get_by_subject(const X509_STORE_CTX *ctx,
static int x509_store_add_obj(X509_STORE *store, X509_OBJECT *obj)
{
const X509_NAME *xn;
- STACK_OF(X509_OBJECT) *objs = NULL;
+ X509_OBJECT *head;
int ret = 0, added = 0;
if (obj->type == X509_LU_CRL)
@@ -536,11 +602,11 @@ static int x509_store_add_obj(X509_STORE *store, X509_OBJECT *obj)
}
if (store->objs_ht != NULL) {
- objs = ossl_x509_store_ht_get_by_name(store, xn);
- if (objs != NULL && X509_OBJECT_retrieve_match(objs, obj)) {
+ head = objs_ht_get_by_name(store, xn);
+ if (x509_name_objs_match(head, obj)) {
ret = 1;
} else {
- added = x509_name_objs_ht_insert(store, xn, objs, obj);
+ added = x509_name_objs_ht_insert(store, xn, head, obj);
ret = added != 0;
}
} else {
@@ -758,33 +824,15 @@ static X509_OBJECT *x509_object_dup(const X509_OBJECT *obj)
}
#ifndef OPENSSL_NO_DEPRECATED_4_0
-static int obj_ht_to_stack(HT_VALUE *v, void *arg)
+static int obj_ht_to_stack(X509_OBJECT *obj, void *arg)
{
STACK_OF(X509_OBJECT) **sk = arg;
- STACK_OF(X509_OBJECT) *objs = v->value;
- X509_OBJECT *obj;
- int i;
- for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
- obj = sk_X509_OBJECT_value(objs, i);
- if (sk_X509_OBJECT_push(*sk, obj) == 0)
- goto err;
+ if (sk_X509_OBJECT_push(*sk, obj) == 0) {
+ sk_X509_OBJECT_zero(*sk);
+ return 0;
}
- return 1;
-
-err:
- sk_X509_OBJECT_zero(*sk);
-
- return 0;
-}
-
-static int obj_ht_zero_stacks(HT_VALUE *v, void *arg)
-{
- STACK_OF(X509_OBJECT) *objs = v->value;
-
- sk_X509_OBJECT_zero(objs);
-
return 1;
}
@@ -793,11 +841,11 @@ STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(const X509_STORE *xs)
X509_STORE *store = (X509_STORE *)xs;
if (xs->objs_ht != NULL) {
- ossl_ht_foreach_until(xs->objs_ht, obj_ht_to_stack, &store->objs);
+ objs_ht_foreach_until(xs->objs_ht, obj_ht_to_stack, &store->objs);
if (sk_X509_OBJECT_num(store->objs) > 0
- || ossl_ht_count(xs->objs_ht) == 0) {
- ossl_ht_foreach_until(xs->objs_ht, obj_ht_zero_stacks, NULL);
- ossl_ht_free(xs->objs_ht);
+ || ossl_htable_is_empty(xs->objs_ht)) {
+ /* The objects are in |store->objs| now */
+ objs_ht_free(xs->objs_ht, 0);
store->objs_ht = NULL;
} else {
return NULL;
@@ -808,30 +856,19 @@ STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(const X509_STORE *xs)
}
#endif
-static int obj_ht_foreach_object(HT_VALUE *v, void *arg)
+static int obj_ht_foreach_object(X509_OBJECT *obj, void *arg)
{
STACK_OF(X509_OBJECT) **sk = arg;
- STACK_OF(X509_OBJECT) *objs = v->value;
- X509_OBJECT *dup, *obj;
- int i;
+ X509_OBJECT *dup = x509_object_dup(obj);
- for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
- obj = sk_X509_OBJECT_value(objs, i);
- dup = x509_object_dup(obj);
- if (dup == NULL)
- goto err;
- if (sk_X509_OBJECT_push(*sk, dup) == 0)
- goto err;
+ if (dup == NULL || sk_X509_OBJECT_push(*sk, dup) == 0) {
+ X509_OBJECT_free(dup);
+ sk_X509_OBJECT_pop_free(*sk, X509_OBJECT_free);
+ *sk = NULL;
+ return 0;
}
return 1;
-
-err:
- X509_OBJECT_free(dup);
- sk_X509_OBJECT_pop_free(*sk, X509_OBJECT_free);
- *sk = NULL;
-
- return 0;
}
STACK_OF(X509_OBJECT) *X509_STORE_get1_objects(X509_STORE *store)
@@ -851,7 +888,7 @@ STACK_OF(X509_OBJECT) *X509_STORE_get1_objects(X509_STORE *store)
X509_STORE_unlock(store);
return NULL;
}
- ossl_ht_foreach_until(store->objs_ht, obj_ht_foreach_object, &objs);
+ objs_ht_foreach_until(store->objs_ht, obj_ht_foreach_object, &objs);
} else {
objs = sk_X509_OBJECT_deep_copy(store->objs, x509_object_dup,
X509_OBJECT_free);
@@ -876,7 +913,7 @@ STACK_OF(X509) *X509_STORE_get1_all_certs(X509_STORE *store)
goto out_free;
if (store->objs_ht != NULL) {
- ossl_ht_foreach_until(store->objs_ht, obj_ht_foreach_certs, &sk);
+ objs_ht_foreach_until(store->objs_ht, obj_ht_foreach_certs, &sk);
} else {
for (int i = 0; i < sk_X509_OBJECT_num(store->objs); i++) {
X509 *cert = X509_OBJECT_get0_X509(sk_X509_OBJECT_value(store->objs, i));
@@ -907,9 +944,9 @@ STACK_OF(X509) *X509_STORE_CTX_get1_certs(const X509_STORE_CTX *ctx,
int i, idx = -1, cnt = 0;
STACK_OF(X509) *sk = NULL;
X509 *x;
- X509_OBJECT *obj;
+ X509_OBJECT *obj, *head = NULL;
X509_STORE *store = ctx->store;
- STACK_OF(X509_OBJECT) *objs;
+ STACK_OF(X509_OBJECT) *objs = NULL;
if (store == NULL)
return sk_X509_new_null();
@@ -917,15 +954,16 @@ STACK_OF(X509) *X509_STORE_CTX_get1_certs(const X509_STORE_CTX *ctx,
if (!ossl_x509_store_read_lock(store))
return NULL;
+ /* In a table of names |idx| only tells whether there is a certificate */
if (store->objs_ht != NULL) {
- objs = ossl_x509_store_ht_get_by_name(store, nm);
- if (objs != NULL)
- idx = x509_object_idx_cnt(objs, X509_LU_X509, nm, &cnt);
+ head = objs_ht_get_by_name(store, nm);
+ if (objs_first_of_type(head, X509_LU_X509) != NULL)
+ idx = 0;
} else {
objs = store->objs;
idx = x509_object_idx_cnt(objs, X509_LU_X509, nm, &cnt);
}
- if (idx < 0 || objs == NULL) {
+ if (idx < 0) {
/*
* Nothing found in cache: do lookup to possibly add new objects to
* cache
@@ -937,18 +975,32 @@ STACK_OF(X509) *X509_STORE_CTX_get1_certs(const X509_STORE_CTX *ctx,
if (!ossl_x509_store_read_lock(store))
return NULL;
if (store->objs_ht != NULL) {
- objs = ossl_x509_store_ht_get_by_name(store, nm);
- if (objs == NULL)
- goto end;
+ /* The lookup may have found a certificate and not cached it */
+ head = objs_ht_get_by_name(store, nm);
+ if (objs_first_of_type(head, X509_LU_X509) != NULL)
+ idx = 0;
} else {
objs = store->objs;
+ idx = x509_object_idx_cnt(objs, X509_LU_X509, nm, &cnt);
}
- idx = x509_object_idx_cnt(objs, X509_LU_X509, nm, &cnt);
}
sk = sk_X509_new_null();
if (idx < 0 || sk == NULL)
goto end;
+ if (store->objs_ht != NULL) {
+ /* Every object led by |head| has the name |nm| */
+ for (i = 0; (obj = objs_value(head, i)) != NULL; i++) {
+ if (obj->type != X509_LU_X509)
+ continue;
+ if (!X509_add_cert(sk, obj->data.x509, X509_ADD_FLAG_UP_REF)) {
+ X509_STORE_unlock(store);
+ OSSL_STACK_OF_X509_free(sk);
+ return NULL;
+ }
+ }
+ goto end;
+ }
for (i = idx; cnt > 0 && i < sk_X509_OBJECT_num(objs); i++) {
obj = sk_X509_OBJECT_value(objs, i);
if (obj->type != X509_LU_X509)
@@ -981,7 +1033,7 @@ STACK_OF(X509_CRL) *X509_STORE_CTX_get1_crls(const X509_STORE_CTX *ctx,
int i = 1, idx, cnt = 0;
STACK_OF(X509_CRL) *sk;
X509_CRL *x;
- X509_OBJECT *obj;
+ X509_OBJECT *obj, *head;
X509_STORE *store = ctx->store;
STACK_OF(X509_OBJECT) *objs;
@@ -996,13 +1048,28 @@ STACK_OF(X509_CRL) *X509_STORE_CTX_get1_crls(const X509_STORE_CTX *ctx,
sk_X509_CRL_free(sk);
return NULL;
}
- if (store->objs_ht) {
- objs = ossl_x509_store_ht_get_by_name(store, nm);
- if (objs == NULL)
- goto end;
- } else {
- objs = store->objs;
+ if (store->objs_ht != NULL) {
+ /* Every object led by the first one named |nm| has that name */
+ head = objs_ht_get_by_name(store, nm);
+ for (i = 0; (obj = objs_value(head, i)) != NULL; i++) {
+ if (obj->type != X509_LU_CRL)
+ continue;
+ x = obj->data.crl;
+ if (!X509_CRL_up_ref(x)) {
+ X509_STORE_unlock(store);
+ sk_X509_CRL_pop_free(sk, X509_CRL_free);
+ return NULL;
+ }
+ if (!sk_X509_CRL_push(sk, x)) {
+ X509_STORE_unlock(store);
+ X509_CRL_free(x);
+ sk_X509_CRL_pop_free(sk, X509_CRL_free);
+ return NULL;
+ }
+ }
+ goto end;
}
+ objs = store->objs;
idx = x509_object_idx_cnt(objs, X509_LU_CRL, nm, &cnt);
if (idx < 0)
goto end;
diff --git a/crypto/x509/x_name.c b/crypto/x509/x_name.c
index e965dee4c8..dbf490b9ee 100644
--- a/crypto/x509/x_name.c
+++ b/crypto/x509/x_name.c
@@ -15,6 +15,7 @@
#include "crypto/x509.h"
#include "crypto/asn1.h"
#include "x509_local.h"
+#include "internal/hashfunc.h"
/*
* Maximum length of X509_NAME: much larger than anything we should
@@ -324,6 +325,8 @@ static int x509_name_canon(X509_NAME *a)
OPENSSL_free(a->canon_enc);
a->canon_enc = NULL;
a->canon_enclen = 0;
+ /* The hash of no bytes, for the empty name and for a failure below */
+ a->canon_hash = ossl_fnv1a_hash(NULL, 0);
/* Special case: empty X509_NAME => null encoding */
if (sk_X509_NAME_ENTRY_num(a->entries) == 0) {
a->canon_enclen = 0;
@@ -382,6 +385,7 @@ static int x509_name_canon(X509_NAME *a)
a->canon_enc = buf;
a->canon_enclen = len;
+ a->canon_hash = ossl_fnv1a_hash(buf, len);
buf = NULL;
ret = 1;
diff --git a/doc/internal/man3/ossl_ht_new.pod b/doc/internal/man3/ossl_ht_new.pod
deleted file mode 100644
index 7ad33efbbe..0000000000
--- a/doc/internal/man3/ossl_ht_new.pod
+++ /dev/null
@@ -1,382 +0,0 @@
-=pod
-
-=head1 NAME
-
-ossl_ht_new, ossl_ht_free,
-ossl_ht_read_lock, ossl_ht_read_unlock,
-ossl_ht_write_lock, ossl_ht_write_unlock,
-ossl_ht_flush, ossl_ht_insert,
-ossl_ht_delete, ossl_ht_count,
-ossl_ht_foreach_until, ossl_ht_filter,
-ossl_ht_value_list_free, ossl_ht_get,
-ossl_ht_put, HT_START_KEY_DEFN,
-HT_END_KEY_DEFN, HT_DEF_KEY_FIELD_CHAR_ARRAY,
-HT_DEF_KEY_FIELD_UINT8T_ARRAY, HT_DEF_KEY_FIELD,
-HT_INIT_KEY, HT_KEY_RESET, HT_SET_KEY_FIELD,
-HT_SET_KEY_STRING, HT_SET_KEY_BLOB,
-TO_HT_KEY, FROM_HT_KEY,
-IMPLEMENT_HT_VALUE_TYPE_FNS
-- internal rcu locked hashtables
-
-=head1 SYNOPSIS
-
- HT *ossl_ht_new(const HT_CONFIG *conf);
- void ossl_ht_free(HT *htable);
- void ossl_ht_read_lock(HT *htable);
- void ossl_ht_read_unlock(HT *htable);
- void ossl_ht_write_lock(HT *htable);
- void ossl_ht_write_unlock(HT *htable);
- int ossl_ht_flush(HT *htable);
- int ossl_ht_insert(HT *htable, HT_KEY *key, HT_VALUE *data, HT_VALUE **olddata);
- int ossl_ht_delete(HT *htable, HT_KEY *key);
- size_t ossl_ht_count(HT *htable);
- void ossl_ht_foreach_until(HT *htable, int (*cb)(HT_VALUE *obj, void *arg), void *arg);
- HT_VALUE_LIST *ossl_ht_filter(HT *htable, size_t max_len, int (*filter)(HT_VALUE *obj));
- void ossl_ht_value_list_free(HT_VALUE_LIST *list);
- HT_VALUE *ossl_ht_get(HT *htable, HT_KEY *key);
- void ossl_ht_put(HT_VALUE *value);
- HT_START_KEY_DEFN(keyname);
- HT_END_KEY_DEFN(keyname);
- HT_DEF_KEY_FIELD(name, type);
- HT_DEF_KEY_FIELD_CHAR_ARRAY(name, size);
- HT_DEF_KEY_FIELD_UINT8T_ARRAY(name, size);
- HT_INIT_KEY(key);
- HT_KEY_RESET(key);
- HT_SET_KEY_FIELD(key, member, value);
- HT_SET_KEY_STRING(key, member, value);
- HT_SET_KEY_BLOB(key, member, value, len);
- TO_HT_KEY(key);
- FROM_HT_KEY(key, type);
- IMPLEMENT_HT_VALUE_TYPE_FNS(vtype, name, pfx);
-
-=head1 DESCRIPTION
-
-This API provides a library-internal implementation of a hashtable that provides
-reference counted object retrieval under the protection of an rcu lock. API
-type safety is offered via conversion macros to and from the generic B<HT_VALUE>
-type.
-
-=over 2
-
-=item *
-
-ossl_ht_new() returns a new B<HT> (hashtable object) used to store data
-elements based on a defined key. The call accepts an HT_CONFIG pointer which
-contains configurations options for hashtable. Current config options consist
-of:
- I<ht_free_fn> The function to call to free a value, may be NULL.
- I<ht_hash_fn> The function to generate a hash value for a key, may be NULL.
- I<init_neighborhoods> The initial number of neighborhoods in the hash table.
- I<no_rcu> Disables RCU locking.
-
-Note that init_bucket_len may be set to zero, which will use the default initial
-bucket size, which will be automatically expanded with the hash table load
-average reaches 0.75.
-
-Note that lockless_read operation implies behavioral restrictions. Specifically
-only element additions are allowed, deletion operations will fail
- Hash table growth is inhibited. init_bucket_len should be set to an
- appropriate value to prevent performance degradation
- The table owner is responsible for ensuring there are no readers during a
- freeing of the table.
-
-Note that lockless_write operations are done at your own risk. Lockless
- operation in a multithreaded environment will cause data corruption. It
- is the callers responsibility in this mode of operation to provide thread
- synchronization.
-
-Note that if RCU locks are disabled, calls to ossl_ht_[read/write]_[lock/unlock]
-have no effect.
-
-=item *
-
-ossl_ht_free() frees an allocated hash table. Each element in the table
-will have its reference count dropped, and, if said count reaches zero, the hash
-tables registered free function will be called to release the element data.
-
-=item *
-
-ossl_ht_read_lock(), ossl_ht_read_unlock(), ossl_ht_write_lock() and
-ossl_ht_write_unlock() lock the table for reading and writing/modification.
-These function are not required for use in the event a table is to be used in a
-lockless fashion, but if they are not used, it is the responsibility of the caller
-to ensure thread synchronization. Note that an rcu lock is used internally for these
-operations, so for table modifying actions (ossl_ht_flush() and ossl_ht_delete()
-the write lock must be taken and released to ensure rcu synchronization takes
-place.
-
-=item *
-
-ossl_ht_flush() empties a hash table. All elements will have their
-reference counts decremented, and, on reaching zero, the free function will be
-called to release the element data.
-
-=item *
-
-ossl_ht_insert() inserts an B<HT_VALUE> element into the hash table, to be
-hashed using the corresponding B<HT_KEY> value. The returned pointer olddata must
-be freed only when RCU is disabled and insert performs a replacement.
-
-=item *
-
-ossl_ht_delete() deletes an entry from the hashtable indexed by the passed
-B<HT_KEY> value.
-
-=item *
-
-ossl_ht_count() returns the number of elements within the hash table.
-
-=item *
-
-ossl_ht_foreach_until() iterates over all elements in the hash table, calling
-the passed callback function for each. The return value of the callback
-indicates if the iteration should continue or not. Returning 1 indicates
-iteration should continue, while returning 0 indicates that iteration should
-terminate.
-
-Note that the iteration is done under read lock protection, and as such
-modifications to the table are disallowed in the callback function.
-Modification to the value content are permitted, if the caller is able to
-properly synchronize such modifications with other threads.
-
-=item *
-
-ossl_ht_filter() iterates over all elements of the hash table, calling
-the filter callback for each element. If the callback returns 1, the
-corresponding B<HT_VALUE> is placed on a list, and its reference count incremented.
-The completed list is returned to the caller as an B<HT_VALUE_LIST> object
-
-=item *
-
-ossl_ht_value_list_free() frees an B<HT_VALUE_LIST>. For each element on
-the list, its reference count is decremented, and after traversing the list, the
-list object is freed. Note, NULL elements are allowed on the list, but for any
-element which is taken from the list by a caller, they must call
-ossl_ht_put() on the B<HT_VALUE> to prevent memory leaks.
-
-=item *
-
-ossl_ht_get() performs a lookup of an B<HT_KEY> in the hashtable, returning
-its corresponding value.
-
-=item *
-
-HT_START_KEY_DEFN() Begins the definition of a key type. the keyname parameter
-defines the structure name, and presets a common key header.
-
-=item *
-
-HT_END_KEY_DEFN() Finalizes a key definition. the keyname parameter (which may
-differ from the name passed in HT_START_KEY_DEFN(), defines the key type name.
-The resulting type may be converted to an HT_KEY variable via the HT_TO_KEY()
-macro, and back using the HT_FROM_KEY() macro.
-
-=item *
-
-HT_DEF_KEY_FIELD() Allows for the creation of data fields within a key. Note,
-this macro can be used for any data type, but it is recommended that strings and
-binary arrays be created with the HT_DEF_KEY_FIELD_CHAR_ARRAY() and
-HT_DEF_KEY_FIELD_UINT8T_ARRAY() macros to ensure proper in-lining of key data.
-
-=item *
-
-HT_DEF_KEY_FIELD_CHAR_ARRAY() Creates a string field of fixed size
-within a key definition. Note these items will be NULL terminated.
-
-=item *
-
-HT_DEF_KEY_FIELD_UINT8T_ARRAY() Creates an array of uint8_t elements within a
-key.
-
-=item *
-
-HT_INIT_KEY() Initializes a key for use. Can be called multiple times, but must
-be called at least once before using in any hashtable method.
-
-=item *
-
-HT_KEY_RESET() Resets a key's data to all zeros.
-
-=item *
-
-HT_SET_KEY_FIELD() Sets a field in a key (as defined by HT_DEF_KEY_FIELD()) to a
-given value.
-
-=item *
-
-HT_SET_KEY_STRING() Performs a strncpy() of a source string to the destination
-key field.
-
-=item *
-
-HT_SET_KEY_BLOB() Performs a memcpy() of a source uint8_t buffer to a
-destination key field.
-
-=item *
-
-TO_HT_KEY() Converts a key type as defined by HT_START_KEY_DEFN() and
-HE_END_KEY_DEFN() to the generic HT_KEY type
-
-=item *
-
-FROM_HT_KEY() Converts an HT_KEY back to a specific key type as defined by
-HT_START_KEY_DEFN() and HT_END_KEY_DEFN()
-
-=item *
-
-IMPLEMENT_HT_VALUE_TYPE_FNS() creates template conversion functions for
-manipulating the hashtable using specific data types. This macro accepts two
-parameters, a NAME, which is used to prefix the hashtable function so that it
-may be associated with a specific hash table, and TYPE which defines the type of
-data the instantiated function accepts. The list of functions instantiated by
-this macro are below.
-
-=over 2
-
-=item *
-
-int ossl_ht_NAME_TYPE_insert(HT* h, HT_KEY *key, <type> *value, HT_VALUE **olddata)
-Inserts a value to the hash table of type TYPE into the hash table using the
-provided key. If olddata is not NULL, and a matching key already exists in the
-table, the operation is a replacement, and the old data is returned in this
-pointer
-
-=item *
-
-<TYPE> ossl_ht_NAME_TYPE_get(HT *h, HT_KEY *key, HT_VALUE **v)
-Looks up an item in the hash table based on key, and returns the data it found,
-if any. v holds a pointer to the B<HT_VALUE> associated with the data.
-
-=item *
-
-<TYPE> *ossl_ht_NAME_TYPE_from_value(HT_VALUE *v)
-Validates that the B<HT_VALUE> provided matches the TYPE specified, and returns the
-value data. If there is a type mismatch, NULL is returned
-
-=item *
-
-HT_VALUE *ossl_ht_NAME_TYPE_to_value(<TYPE> *data)
-Converts the data pointer provided to an B<HT_VALUE> object
-
-=item *
-
-int ossl_ht_NAME_TYPE_type(HT_VALUE *v)
-Returns true if the B<HT_VALUE> object passed in is of type <TYPE>
-
-=back
-
-=back
-
-=head1 RETURN VALUES
-
-ossl_ht_new() returns an B<HT*> struct on success and NULL on error
-
-void ossl_ht_free(HT *htable);
-
-ossl_ht_flush() and ossl_ht_insert() return 1 on success and 0 on error
-
-ossl_ht_delete() returns 1 if the key was successfully deleted, and 0 if the
-key was not found.
-
-ossl_ht_count() returns the number of elements in the hash table
-
-ossl_ht_filter() returns an B<HT_VALUE_LIST> of all elements matching the
-provided filter
-
-ossl_ht_get() returns an B<HT_VALUE> pointer, or NULL if the element was not
-found.
-
-ossl_ht_insert() returns 1 if an element was inserted, 0 if the element is
-already present, -1 on fatal errors (memory allocation or growth not allowed).
-
-=head1 EXAMPLES
-
-#include <stdio.h>
-#include <string.h>
-
-#include <openssl/err.h>
-#include <openssl/crypto.h>
-#include <internal/hashtable.h>
-
-HT_START_KEY_DEFN(intkey)
-HT_DEF_KEY_FIELD(myintkey, int)
-HT_END_KEY_DEFN(INTKEY)
-
-IMPLEMENT_HT_VALUE_TYPE_FNS(int, test, static)
-
-static void int_free_fn(HT_VALUE *v)
-{
- int *i = ossl_crypto_test_int_from_value(v);
-
- fprintf(stderr, "Freeing an element\n");
- OPENSSL_free(i);
-}
-
-static int test_int_hashtable(void)
-{
- /*
- * our config says:
- * int_free_fn - Our free handler
- * NULL - Use default hash fn
- * 0 - use default initial bucket size
- */
- HT_CONFIG hash_conf = {
- int_free_fn,
- NULL,
- 0
- };
- INTKEY key;
- HT *ht = NULL;
- HT_VALUE *v;
- int rc;
- int *newval = OPENSSL_malloc(sizeof(int));
-
- ht = ossl_ht_new(&hash_conf);
-
- if (ht == NULL)
- return 0;
-
- if (newval == NULL)
- goto out;
-
- *newval = 1;
-
- /* insert */
- HT_INIT_KEY(&key);
- HT_SET_KEY_FIELD(&key, myintkey, 47);
- ossl_ht_write_lock(ht);
- rc = ossl_ht_test_int_insert(ht, TO_HT_KEY(&key), newval, NULL);
- ossl_ht_write_unlock(ht);
- if (rc == 0)
- goto out;
-
- /* num_items */
- if (ossl_ht_count(ht) != 1)
- goto out;
-
- /* lookup */
- HT_RESET_KEY(&key);
- HT_SET_KEY_FIELD(&key, myintkey, 47);
- ossl_ht_read_lock(ht);
- v = ossl_ht_get(ht, TO_HT_KEY(&key);
- fprintf(stderr, "found element with key 47 holding value %d\n",
- *ossl_ht_test_int_from_value(v));
- ossl_ht_read_unlock(ht);
-
- rc = 1;
-end:
- /* this will call the free function for our element */
- ossl_ht_free(ht);
- return rc;
-}
-
-=head1 COPYRIGHT
-
-Copyright 2024 The OpenSSL Project Authors. All Rights Reserved.
-
-Licensed under the Apache License 2.0 (the "License"). You may not use
-this file except in compliance with the License. You can obtain a copy
-in the file LICENSE in the source distribution or at
-L<https://www.openssl.org/source/license.html>.
-
-=cut
diff --git a/fuzz/build.info b/fuzz/build.info
index fd654c5da0..f0e0fc5c63 100644
--- a/fuzz/build.info
+++ b/fuzz/build.info
@@ -134,7 +134,7 @@ IF[{- !$disabled{"fuzz-afl"} || !$disabled{"fuzz-libfuzzer"} -}]
SOURCE[hashtable]=hashtable.c driver.c
INCLUDE[hashtable]=../include {- $ex_inc -}
- DEPEND[hashtable]=../libcrypto {- $ex_lib -}
+ DEPEND[hashtable]=../libcrypto.a {- $ex_lib -}
SOURCE[acert]=acert.c driver.c
INCLUDE[acert]=../include {- $ex_inc -}
@@ -340,7 +340,7 @@ IF[{- !$disabled{tests} -}]
INCLUDE[decoder-test]=../include ../test/mfail
DEPEND[decoder-test]=../libcrypto.a
- SOURCE[hashtable-test]=hashtable.c $FUZZTESTSRC fuzz_rand.c
+ SOURCE[hashtable-test]=hashtable.c $FUZZTESTSRC
INCLUDE[hashtable-test]=../include ../test/mfail
DEPEND[hashtable-test]=../libcrypto.a
diff --git a/fuzz/hashtable.c b/fuzz/hashtable.c
index 2e503cc1a4..c862388ce0 100644
--- a/fuzz/hashtable.c
+++ b/fuzz/hashtable.c
@@ -9,49 +9,62 @@
*/
/*
- * Test hashtable operation.
+ * Fuzz the intrusive hash tables of internal/hashtable.h.
+ *
+ * The same elements go into four tables, one of each kind: a static table
+ * (DEFINE_HTABLE_OF), a keyed one (DEFINE_HTABLE_KEYED_OF), a growable one
+ * (DEFINE_HTABLE_DYN_OF), and a static one that is added to and read through
+ * the lock-free interface (DEFINE_HTABLE_RCU_OF). An element has a link for
+ * each table, so it can be in any number of them at a time. A model records
+ * which tables an element is in and under which hash, and the tables are
+ * checked against it as the operations go.
+ *
+ * The input is a sequence of 11-byte records. The fuzzer of the ossl_ht hash
+ * table, which this one replaces, took one such record per input, so its
+ * corpus applies here:
+ *
+ * u8 the operation in the low six bits, modulo OP_END, and FLAG_ALT
+ * u16 little endian: the element in the low eight bits; in bits 8 to 11
+ * the tables to work on, all four if none of them is set; in bits 12
+ * to 15 how many more of the elements that follow it to work on
+ * u64 little endian: the hash to add or look up under, or an argument
+ *
+ * An operation on several elements takes them under consecutive hashes, so
+ * a few records are enough to fill the tables well beyond their buckets.
+ *
+ * The tables are empty at the start of every input and emptied at its end,
+ * so an input behaves the same whatever ran before it. The first 16 bytes of
+ * the input, zero padded, also serve as the key of the keyed table.
+ *
+ * The ossl_ht fuzzer kept its table from one input to the next instead, so
+ * an input of its corpus is a single operation that finds the tables empty
+ * here. test/recipes/99-test_fuzz_hashtable.t therefore also runs the
+ * records of the whole corpus as one input.
*/
-#include <limits.h>
-#include <stdio.h>
+
+#include <string.h>
+#include <openssl/crypto.h>
#include <openssl/err.h>
-#include <openssl/bio.h>
-#include <internal/common.h>
-#include <internal/hashtable.h>
+#include "crypto/siphash.h"
+#include "internal/hashtable.h"
#include "fuzzer.h"
/*
- * Make the key space very small here to make lookups
- * easy to predict for the purposes of validation
- * A two byte key gives us 65536 possible entries
- * so we can allocate a flat table to compare to
- */
-HT_START_KEY_DEFN(fuzzer_key)
-HT_DEF_KEY_FIELD(fuzzkey, uint16_t)
-HT_END_KEY_DEFN(FUZZER_KEY)
-
-#define FZ_FLAG_ALLOCATED (1 << 0)
-typedef struct fuzzer_value_st {
- uint64_t flags;
- uint64_t value;
-} FUZZER_VALUE;
-
-IMPLEMENT_HT_VALUE_TYPE_FNS(FUZZER_VALUE, fz, static)
-
-static size_t skipped_values = 0;
-static size_t inserts = 0;
-static size_t replacements = 0;
-static size_t deletes = 0;
-static size_t flushes = 0;
-static size_t lookups = 0;
-static size_t foreaches = 0;
-static size_t filters = 0;
-static int valfound;
-
-static FUZZER_VALUE *prediction_table = NULL;
-static HT *fuzzer_table = NULL;
-
-/*
- * Operational values
+ * The first three work on every element the record names, the others once.
+ *
+ * OP_INSERT Add the element if it is not in the table. If it is, promote
+ * it with _ruc() under the given hash (FLAG_ALT), or find it.
+ * OP_DELETE Remove the element if it is in the table.
+ * OP_LOOKUP Find the element under the hash it is in the table with, or
+ * under the given hash (FLAG_ALT), which may not lead to it.
+ * OP_FLUSH Empty the table: remove every element from within
+ * _doall_arg(), or (FLAG_ALT) clean the table up and initialise
+ * it again.
+ * OP_FOREACH Check the whole table against the model.
+ * OP_FILTER Walk the element's bucket and remove from it the elements the
+ * given value selects.
+ * OP_RESERVE Reserve buckets for the given number of elements; growable
+ * table only.
*/
#define OP_INSERT 0
#define OP_DELETE 1
@@ -59,297 +72,661 @@ static HT *fuzzer_table = NULL;
#define OP_FLUSH 3
#define OP_FOREACH 4
#define OP_FILTER 5
-#define OP_END 6
+#define OP_RESERVE 6
+#define OP_END 7
#define OP_MASK 0x3f
-#define INSERT_REPLACE_MASK 0x40
+#define FLAG_ALT 0x40
#define OPERATION(x) (((x) & OP_MASK) % OP_END)
-#define IS_REPLACE(x) ((x) & INSERT_REPLACE_MASK)
-static int table_iterator(HT_VALUE *v, void *arg)
-{
- uint16_t keyval = (*(uint16_t *)arg);
- FUZZER_VALUE *f = ossl_ht_fz_FUZZER_VALUE_from_value(v);
+#define FZ_RECORD 11
- if (f != NULL && f == &prediction_table[keyval]) {
- valfound = 1;
- return 0;
- }
+/* Few enough elements that operations keep meeting the ones in the tables */
+#define FZ_ELEMS 256
+
+enum {
+ T_STATIC,
+ T_KEYED,
+ T_DYN,
+ T_RCU,
+ T_COUNT
+};
+
+#define FZ_ALL_TABLES ((1u << T_COUNT) - 1)
+
+typedef struct fz_elem_st {
+ OSSL_QUEUE_MEMBER(fzs);
+ OSSL_QUEUE_MEMBER(fzk);
+ OSSL_HTABLE_MEMBER(fzd);
+ OSSL_QUEUE_MEMBER(fzr);
+ unsigned int num; /* which of the FZ_ELEMS elements it is */
+} FZ_ELEM;
+
+/*
+ * Small tables, of 8, 4 and 16 buckets and, for the growable one, of 2 that
+ * double four times: a couple of records fill any of them, make chains and
+ * take the growable table to its maximum and past it.
+ */
+DEFINE_QUEUE_OF(fzs, FZ_ELEM);
+DEFINE_HTABLE_OF(fzs, FZ_ELEM, 3);
- return 1;
+DEFINE_QUEUE_OF(fzk, FZ_ELEM);
+DEFINE_HTABLE_KEYED_OF(fzk, FZ_ELEM, 2);
+
+#define FZD_MAX_BITS 5
+#define FZD_MAX_BUCKETS ((size_t)1 << FZD_MAX_BITS)
+DEFINE_QUEUE_OF(fzd, FZ_ELEM);
+DEFINE_HTABLE_DYN_OF(fzd, FZ_ELEM, 1, FZD_MAX_BITS);
+
+DEFINE_QUEUE_OF(fzr, FZ_ELEM);
+DEFINE_HTABLE_OF(fzr, FZ_ELEM, 4);
+DEFINE_HTABLE_RCU_OF(fzr, FZ_ELEM);
+
+/*
+ * The model: what is known of an element without asking a table. The
+ * element itself is allocated when the first table gets it and freed when
+ * the last one lets go of it, so that a link some table kept to it shows.
+ */
+typedef struct fz_model_st {
+ FZ_ELEM *e;
+ uint64_t hash[T_COUNT]; /* the hash it is in each table under */
+ unsigned char in[T_COUNT]; /* whether it is in each table */
+ unsigned char seen; /* by the _doall_arg() of a check */
+} FZ_MODEL;
+
+/* What _doall_arg() calls for each element */
+typedef void FZ_VISIT(FZ_ELEM *e, void *arg);
+
+/* The operations of one table, for the code that is the same for all four */
+typedef struct fz_table_st {
+ void (*init)(void);
+ void (*cleanup)(void);
+ void (*add)(FZ_ELEM *e, uint64_t hash);
+ void (*del)(FZ_ELEM *e);
+ void (*ruc)(FZ_ELEM *e, uint64_t hash);
+ FZ_ELEM *(*find)(const FZ_ELEM *e, uint64_t hash);
+ FZ_ELEM *(*head)(uint64_t hash);
+ size_t (*walk)(void);
+ void (*doall)(FZ_VISIT *fn, void *arg);
+ void (*filter)(uint64_t hash, uint64_t drop);
+ int (*hashed)(const FZ_ELEM *e);
+ void (*init_elem)(FZ_ELEM *e);
+ size_t (*num)(void);
+ size_t (*num_buckets)(void);
+ /* The hash of |m|, or with |alt| some other hash, made from |value| */
+ uint64_t (*hash)(const FZ_MODEL *m, uint64_t value, int alt);
+ /* FIND compares the whole hash, not only the bucket it selects */
+ int whole_hash;
+ /* What only this kind of table has, or NULL */
+ void (*check)(void);
+ void (*reserve)(uint64_t value);
+} FZ_TABLE;
+
+static FZ_MODEL fz_model[FZ_ELEMS];
+static size_t fz_count[T_COUNT]; /* the model's number of elements */
+static unsigned char fz_key[OSSL_HTABLE_KEY_SIZE];
+
+static int fz_cond(int t, const FZ_ELEM *p, uint64_t hash, const FZ_ELEM *e);
+static uint64_t fz_check_elem(int t, const FZ_ELEM *p, size_t bucket);
+static void fz_filter_elem(int t, FZ_ELEM *p, uint64_t drop);
+
+/*
+ * The table |name| and its operations, which every kind of table spells the
+ * same way. |t| is the table's index in the model. _add() is unused for a
+ * table that is added to in another way.
+ */
+#define FZ_DEFINE_TABLE(name, t) \
+ static OSSL_HTABLE(name) name##_table; \
+ static void name##_cleanup(void) \
+ { \
+ ossl_htable_##name##_cleanup(&name##_table); \
+ } \
+ static ossl_unused void name##_add(FZ_ELEM *e, uint64_t hash) \
+ { \
+ ossl_htable_##name##_add(&name##_table, e, hash); \
+ } \
+ static void name##_del(FZ_ELEM *e) \
+ { \
+ ossl_htable_##name##_del(&name##_table, e); \
+ } \
+ static void name##_ruc(FZ_ELEM *e, uint64_t hash) \
+ { \
+ ossl_htable_##name##_ruc(&name##_table, e, hash); \
+ } \
+ static FZ_ELEM *name##_find(const FZ_ELEM *e, uint64_t hash) \
+ { \
+ FZ_ELEM *p; \
+ \
+ OSSL_HTABLE_FIND(p, name, &name##_table, hash, \
+ fz_cond(t, p, hash, e)); \
+ return p; \
+ } \
+ static FZ_ELEM *name##_head(uint64_t hash) \
+ { \
+ return ossl_htable_##name##_head(&name##_table, hash); \
+ } \
+ /* Check every element of every bucket and its links; return how many */ \
+ static size_t name##_walk(void) \
+ { \
+ FZ_ELEM *p, *last; \
+ OSSL_QUEUE *bucket; \
+ uint64_t hash; \
+ size_t i, total = 0; \
+ size_t n = ossl_htable_##name##_num_buckets(&name##_table); \
+ \
+ for (i = 0; i < n; i++) { \
+ bucket = ossl_htable_##name##_bucket(&name##_table, i); \
+ last = NULL; \
+ OSSL_HTABLE_FOREACH (p, name, &name##_table, i) { \
+ hash = fz_check_elem(t, p, i); \
+ /* A growable table stores the hash: this one */ \
+ OPENSSL_assert(ossl_htable_##name##_hash_eq(p, hash)); \
+ /* The back link leads to the element before */ \
+ OPENSSL_assert(ossl_queue_##name##_prev(bucket, p) == last); \
+ last = p; \
+ total++; \
+ } \
+ } \
+ return total; \
+ } \
+ static void name##_doall(FZ_VISIT *fn, void *arg) \
+ { \
+ ossl_htable_##name##_doall_arg(&name##_table, fn, arg); \
+ } \
+ /* Remove from the bucket of |hash| the elements that |drop| selects */ \
+ static void name##_filter(uint64_t hash, uint64_t drop) \
+ { \
+ FZ_ELEM *p, *pn; \
+ \
+ OSSL_HTABLE_FOREACH_DELSAFE (p, pn, name, &name##_table, hash) \
+ fz_filter_elem(t, p, drop); \
+ } \
+ static int name##_hashed(const FZ_ELEM *e) \
+ { \
+ return ossl_queue_##name##_hashed(e); \
+ } \
+ static void name##_init_elem(FZ_ELEM *e) \
+ { \
+ ossl_queue_##name##_init_elem(e); \
+ } \
+ static size_t name##_num(void) \
+ { \
+ return ossl_htable_num(&name##_table); \
+ } \
+ static size_t name##_num_buckets(void) \
+ { \
+ return ossl_htable_##name##_num_buckets(&name##_table); \
+ } \
+ struct fz_dummy_st_##name
+
+FZ_DEFINE_TABLE(fzs, T_STATIC);
+FZ_DEFINE_TABLE(fzk, T_KEYED);
+FZ_DEFINE_TABLE(fzd, T_DYN);
+FZ_DEFINE_TABLE(fzr, T_RCU);
+
+/* What differs from one kind of table to the next */
+
+static void fzs_init(void)
+{
+ ossl_htable_fzs_init(&fzs_table);
+}
+
+/* The fuzzer chooses the hashes of all tables but the keyed one */
+static uint64_t fz_given_hash(const FZ_MODEL *m, uint64_t value, int alt)
+{
+ return value;
}
-static int filter_iterator(HT_VALUE *v, void *arg)
+static void fzk_init(void)
{
- uint16_t keyval = (*(uint16_t *)arg);
- FUZZER_VALUE *f = ossl_ht_fz_FUZZER_VALUE_from_value(v);
+ ossl_htable_fzk_init(&fzk_table, fz_key);
+}
- if (f != NULL && f == &prediction_table[keyval])
- return 1;
+/* The keyed table hashes the element's number, or else |value| */
+static uint64_t fzk_hash(const FZ_MODEL *m, uint64_t value, int alt)
+{
+ uint64_t x = alt ? value : (uint64_t)(m - fz_model), h;
+ unsigned char le[8];
+ size_t i;
- return 0;
+ for (i = 0; i < sizeof(le); i++)
+ le[i] = (unsigned char)(x >> (8 * i));
+ h = ossl_htable_fzk_hash_u64(&fzk_table, x);
+ /* The integer form hashes the integer's little-endian bytes */
+ OPENSSL_assert(h == ossl_htable_fzk_hash(&fzk_table, le, sizeof(le)));
+ return h;
}
-static void fuzz_free_cb(HT_VALUE *v)
+/*
+ * The hash of the keyed table is SipHash-2-4 with a 64-bit result, which
+ * crypto/siphash implements too: the two agree on any key and any data.
+ */
+static void fzk_check_hash(const uint8_t *buf, size_t len)
{
- FUZZER_VALUE *f = ossl_ht_fz_FUZZER_VALUE_from_value(v);
+ SIPHASH sip;
+ unsigned char out[SIPHASH_MIN_DIGEST_SIZE];
+ uint64_t ref = 0;
+ size_t i;
- if (f != NULL)
- f->flags &= ~FZ_FLAG_ALLOCATED;
+ memset(&sip, 0, sizeof(sip));
+ OPENSSL_assert(SipHash_set_hash_size(&sip, sizeof(out))
+ && SipHash_Init(&sip, fz_key, 0, 0));
+ SipHash_Update(&sip, buf, len);
+ OPENSSL_assert(SipHash_Final(&sip, out, sizeof(out)));
+ for (i = 0; i < sizeof(out); i++)
+ ref |= (uint64_t)out[i] << (8 * i);
+ OPENSSL_assert(ossl_htable_fzk_hash(&fzk_table, buf, len) == ref);
}
-int FuzzerInitialize(int *argc, char ***argv)
+/* A growable table has had this many buckets since it was initialised */
+static size_t fzd_low_buckets;
+
+static void fzd_init(void)
{
- HT_CONFIG fuzz_conf = { NULL, fuzz_free_cb, NULL, 0, 1, 0 };
+ ossl_htable_fzd_init(&fzd_table);
+ fzd_low_buckets = fzd_num_buckets();
+}
- OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
- ERR_clear_error();
- prediction_table = OPENSSL_calloc(65537, sizeof(FUZZER_VALUE));
- if (prediction_table == NULL)
- return -1;
- fuzzer_table = ossl_ht_new(&fuzz_conf);
- if (fuzzer_table == NULL) {
- OPENSSL_free(prediction_table);
- return -1;
- }
+/* Its buckets are a power of two within its bounds, and it never shrinks */
+static void fzd_check(void)
+{
+ size_t n = fzd_num_buckets();
- return 0;
+ OPENSSL_assert((n & (n - 1)) == 0
+ && n >= fzd_low_buckets && n <= FZD_MAX_BUCKETS);
+ fzd_low_buckets = n;
}
-int FuzzerTestOneInput(const uint8_t *buf, size_t len)
+static void fzd_reserve(uint64_t value)
{
- uint8_t op_flags;
- uint16_t keyval;
- int rc;
- int rc_prediction = 1;
- size_t i;
- FUZZER_VALUE *valptr, *lval;
- FUZZER_KEY key;
- HT_VALUE *v = NULL;
- HT_VALUE tv;
- HT_VALUE_LIST *htvlist;
+ size_t want = (size_t)(value % (2 * FZD_MAX_BUCKETS + 1));
+ size_t had = fzd_num_buckets(), n;
- /*
- * We need at least 11 bytes to be able to do anything here
- * 1 byte to detect the operation to perform, 2 bytes
- * for the lookup key, and 8 bytes of value
- */
- if (len < 11) {
- skipped_values++;
- return -1;
+ if (!ossl_htable_fzd_reserve(&fzd_table, want)) {
+ /* Out of memory: the table is as it was */
+ OPENSSL_assert(fzd_num_buckets() == had);
+ return;
}
+ n = fzd_num_buckets();
+ /* A bucket for each of |want| elements, as far as the maximum allows */
+ OPENSSL_assert(n >= had && (n >= want || n == FZD_MAX_BUCKETS));
+ /* and no doubling beyond that */
+ OPENSSL_assert(n == had || n / 2 < want);
+}
- /*
- * parse out our operation flags and key
- */
- op_flags = buf[0];
- memcpy(&keyval, &buf[1], sizeof(uint16_t));
+/*
+ * The last table is added to with _add_rcu() and read with the lock-free
+ * macros, which must see what the locked ones see. Nothing here runs
+ * concurrently, so no reader exists while an element is removed or moved,
+ * and the table is otherwise treated as the static one is.
+ */
+static void fzr_init(void)
+{
+ ossl_htable_fzr_init(&fzr_table);
+}
- /*
- * Initialize our key
- */
- HT_INIT_KEY(&key);
+static void fzr_add_rcu(FZ_ELEM *e, uint64_t hash)
+{
+ ossl_htable_fzr_add_rcu(&fzr_table, e, hash);
+}
- /*
- * Now do our operation
- */
- switch (OPERATION(op_flags)) {
- case OP_INSERT:
- valptr = &prediction_table[keyval];
+static FZ_ELEM *fzr_find_rcu(const FZ_ELEM *e, uint64_t hash)
+{
+ FZ_ELEM *p;
- /* reset our key */
- HT_KEY_RESET(&key);
+ OSSL_HTABLE_FIND_RCU(p, fzr, &fzr_table, hash,
+ fz_cond(T_RCU, p, hash, e));
+ OPENSSL_assert(p == fzr_find(e, hash));
+ return p;
+}
- /* set the proper key value */
- HT_SET_KEY_FIELD(&key, fuzzkey, keyval);
+static FZ_ELEM *fzr_head_rcu(uint64_t hash)
+{
+ FZ_ELEM *p = ossl_htable_fzr_head_rcu(&fzr_table, hash);
- memcpy(&valptr->value, &buf[3], sizeof(uint64_t));
+ OPENSSL_assert(p == fzr_head(hash));
+ return p;
+}
- /* lock the table */
- ossl_ht_write_lock(fuzzer_table);
+static size_t fzr_walk_rcu(void)
+{
+ FZ_ELEM *p, *q;
+ size_t i, total = 0;
+
+ for (i = 0; i < fzr_num_buckets(); i++) {
+ q = fzr_head(i);
+ OSSL_HTABLE_FOREACH_RCU (p, fzr, &fzr_table, i) {
+ OPENSSL_assert(p == q);
+ q = ossl_queue_fzr_next(q);
+ total++;
+ }
+ OPENSSL_assert(q == NULL);
+ }
+ OPENSSL_assert(total == fzr_walk());
+ return total;
+}
- /*
- * do the insert/replace
- */
- if (IS_REPLACE(op_flags))
- rc = ossl_ht_fz_FUZZER_VALUE_insert(fuzzer_table, TO_HT_KEY(&key),
- valptr, &lval);
- else
- rc = ossl_ht_fz_FUZZER_VALUE_insert(fuzzer_table, TO_HT_KEY(&key),
- valptr, NULL);
+#define FZ_TABLE_OPS(name, add, find, head, walk) \
+ name##_init, name##_cleanup, add, name##_del, name##_ruc, \
+ find, head, walk, name##_doall, name##_filter, \
+ name##_hashed, name##_init_elem, name##_num, name##_num_buckets
+
+static const FZ_TABLE fz_tables[T_COUNT] = {
+ { FZ_TABLE_OPS(fzs, fzs_add, fzs_find, fzs_head, fzs_walk),
+ fz_given_hash, 0, NULL, NULL },
+ { FZ_TABLE_OPS(fzk, fzk_add, fzk_find, fzk_head, fzk_walk),
+ fzk_hash, 0, NULL, NULL },
+ { FZ_TABLE_OPS(fzd, fzd_add, fzd_find, fzd_head, fzd_walk),
+ fz_given_hash, 1, fzd_check, fzd_reserve },
+ { FZ_TABLE_OPS(fzr, fzr_add_rcu, fzr_find_rcu, fzr_head_rcu, fzr_walk_rcu),
+ fz_given_hash, 0, NULL, NULL },
+};
+
+/* The model, and the tables against it */
+
+static size_t fz_bucket(int t, uint64_t hash)
+{
+ return (size_t)hash & (fz_tables[t].num_buckets() - 1);
+}
- /*
- * unlock the table
- */
- ossl_ht_write_unlock(fuzzer_table);
+/* A new element for |m|, in no table yet, or NULL if there is no memory */
+static FZ_ELEM *fz_new_elem(FZ_MODEL *m)
+{
+ int t;
+
+ if ((m->e = OPENSSL_malloc(sizeof(*m->e))) == NULL)
+ return NULL;
+ m->e->num = (unsigned int)(m - fz_model);
+ for (t = 0; t < T_COUNT; t++)
+ fz_tables[t].init_elem(m->e);
+ return m->e;
+}
- /*
- * mark the entry as being allocated
- */
- if (rc == 1) {
- valptr->flags |= FZ_FLAG_ALLOCATED;
- IS_REPLACE(op_flags) ? replacements++ : inserts++;
- }
- break;
+/* |m| has left a table: free its element if that was the last one */
+static void fz_release(FZ_MODEL *m)
+{
+ int t;
- case OP_DELETE:
- valptr = &prediction_table[keyval];
+ for (t = 0; t < T_COUNT; t++)
+ if (m->in[t])
+ return;
+ OPENSSL_free(m->e);
+ m->e = NULL;
+}
- /* reset our key */
- HT_KEY_RESET(&key);
+/* An element met in a table is the one the model has under its number */
+static FZ_MODEL *fz_model_of(const FZ_ELEM *p)
+{
+ FZ_MODEL *m = &fz_model[p->num % FZ_ELEMS];
- /* set the proper key value */
- HT_SET_KEY_FIELD(&key, fuzzkey, keyval);
+ OPENSSL_assert(m->e == p);
+ return m;
+}
- /* lock the table */
- ossl_ht_write_lock(fuzzer_table);
+/* Whether a FIND under |hash| is to come across the element of |m| */
+static int fz_reaches(int t, const FZ_MODEL *m, uint64_t hash)
+{
+ if (!m->in[t])
+ return 0;
+ if (fz_tables[t].whole_hash)
+ return m->hash[t] == hash;
+ return fz_bucket(t, m->hash[t]) == fz_bucket(t, hash);
+}
- /*
- * do the delete
- */
- rc = ossl_ht_delete(fuzzer_table, TO_HT_KEY(&key));
+/*
+ * The condition of a FIND for |e| under |hash|, asked about |p|. It is only
+ * asked about elements of the bucket |hash| selects and, in a growable
+ * table, only about those stored under |hash| itself.
+ */
+static int fz_cond(int t, const FZ_ELEM *p, uint64_t hash, const FZ_ELEM *e)
+{
+ OPENSSL_assert(fz_reaches(t, fz_model_of(p), hash));
+ return p == e;
+}
- /*
- * unlock the table
- */
- ossl_ht_write_unlock(fuzzer_table);
+/* |p| was met in bucket number |bucket|; return the hash it is there under */
+static uint64_t fz_check_elem(int t, const FZ_ELEM *p, size_t bucket)
+{
+ const FZ_MODEL *m = fz_model_of(p);
- /*
- * successful deletion if there wasn't a conflict
- */
- if (rc == 1)
- deletes++;
+ OPENSSL_assert(m->in[t] && fz_bucket(t, m->hash[t]) == bucket);
+ return m->hash[t];
+}
- break;
+/* Take |m| out of table |t|, which it is in */
+static void fz_remove(int t, FZ_MODEL *m)
+{
+ fz_tables[t].del(m->e);
+ OPENSSL_assert(!fz_tables[t].hashed(m->e));
+ m->in[t] = 0;
+ fz_count[t]--;
+ fz_release(m);
+}
- case OP_LOOKUP:
- valptr = &prediction_table[keyval];
- lval = NULL;
+/* A filter met |p|, and removes it if |drop| has a bit set for its number */
+static void fz_filter_elem(int t, FZ_ELEM *p, uint64_t drop)
+{
+ FZ_MODEL *m = fz_model_of(p);
- /* reset our key */
- HT_KEY_RESET(&key);
+ OPENSSL_assert(m->in[t]);
+ if (((drop >> (p->num & 63)) & 1) != 0)
+ fz_remove(t, m);
+}
- /* set the proper key value */
- HT_SET_KEY_FIELD(&key, fuzzkey, keyval);
+static void fz_insert(int t, FZ_MODEL *m, uint64_t value, int alt)
+{
+ const FZ_TABLE *T = &fz_tables[t];
+ uint64_t hash = T->hash(m, value, 0);
+ size_t buckets = T->num_buckets();
+
+ if (!m->in[t]) {
+ /* Out of memory: the element stays out of the table */
+ if (m->e == NULL && fz_new_elem(m) == NULL)
+ return;
+ OPENSSL_assert(!T->hashed(m->e) && T->find(m->e, hash) == NULL);
+ T->add(m->e, hash);
+ m->in[t] = 1;
+ fz_count[t]++;
+ } else if (alt) {
+ /* Into another bucket if the hash is another one */
+ T->ruc(m->e, hash);
+ } else {
+ /* A caller looks before it adds, and finds the element */
+ OPENSSL_assert(T->find(m->e, m->hash[t]) == m->e);
+ return;
+ }
+ m->hash[t] = hash;
+ OPENSSL_assert(T->hashed(m->e) && T->find(m->e, hash) == m->e);
+ /*
+ * Added or promoted, the element leads its bucket, unless the table
+ * grew: that re-links the elements, which does not keep their order.
+ */
+ if (T->num_buckets() == buckets)
+ OPENSSL_assert(T->head(hash) == m->e);
+}
- /* lock the table for reading */
- if (!ossl_ht_read_lock(fuzzer_table))
- return 0;
+static void fz_delete(int t, FZ_MODEL *m)
+{
+ const FZ_TABLE *T = &fz_tables[t];
+ uint64_t hash;
- /*
- * If the value to find is not already allocated
- * then we expect a miss in the lookup
- * i.e. we predict a return code of NULL instead
- * of a pointer
- */
- if (!(valptr->flags & FZ_FLAG_ALLOCATED))
- valptr = NULL;
+ if (m->in[t]) {
+ hash = m->hash[t];
+ fz_remove(t, m);
+ OPENSSL_assert(T->find(m->e, hash) == NULL);
+ }
+ OPENSSL_assert(m->e == NULL || !T->hashed(m->e));
+}
- /*
- * do the lookup
- */
- lval = ossl_ht_fz_FUZZER_VALUE_get(fuzzer_table, TO_HT_KEY(&key), &v);
+static void fz_lookup(int t, const FZ_MODEL *m, uint64_t value, int alt)
+{
+ const FZ_TABLE *T = &fz_tables[t];
+ uint64_t hash = m->in[t] && !alt ? m->hash[t] : T->hash(m, value, alt);
- /*
- * unlock the table
- */
- ossl_ht_read_unlock(fuzzer_table);
+ OPENSSL_assert(T->find(m->e, hash)
+ == (fz_reaches(t, m, hash) ? m->e : NULL));
+}
- /*
- * Now check to make sure we did the right thing
- */
- if (valptr == NULL)
- OPENSSL_assert(lval == NULL);
- else
- OPENSSL_assert(lval == NULL || lval == valptr);
+/* For _doall_arg(), which may remove the element it hands out */
+static void fz_flush_cb(FZ_ELEM *e, void *arg)
+{
+ fz_remove(*(int *)arg, fz_model_of(e));
+}
+
+static void fz_flush(int t, int alt)
+{
+ const FZ_TABLE *T = &fz_tables[t];
+ FZ_MODEL *m;
+ if (!alt) {
+ T->doall(fz_flush_cb, &t);
+ } else {
/*
- * if we expect a positive lookup, make sure that
- * we can use the _type and to_value functions
+ * Cleanup neither visits nor unlinks the elements. Those that are in
+ * no other table are freed before it, which it must not notice. The
+ * others are cleared after it, before they are used again, and so
+ * is the table. Cleaning up twice is harmless.
*/
- if (valptr != NULL && lval != NULL) {
- OPENSSL_assert(ossl_ht_fz_FUZZER_VALUE_type(v) == 1);
+ for (m = fz_model; m < fz_model + FZ_ELEMS; m++)
+ if (m->in[t]) {
+ m->in[t] = 0;
+ fz_release(m);
+ m->in[t] = m->e != NULL;
+ }
+ T->cleanup();
+ T->cleanup();
+ for (m = fz_model; m < fz_model + FZ_ELEMS; m++)
+ if (m->in[t]) {
+ T->init_elem(m->e);
+ m->in[t] = 0;
+ }
+ fz_count[t] = 0;
+ T->init();
+ }
+ OPENSSL_assert(fz_count[t] == 0 && T->num() == 0 && T->walk() == 0);
+}
- v = ossl_ht_fz_FUZZER_VALUE_to_value(lval, &tv);
- OPENSSL_assert(v->value == lval);
- lookups++;
- }
+static void fz_seen_cb(FZ_ELEM *e, void *arg)
+{
+ fz_model_of(e)->seen++;
+}
- break;
+static void fz_foreach(int t)
+{
+ const FZ_TABLE *T = &fz_tables[t];
+ FZ_MODEL *m;
+
+ /* Bucket by bucket: every element is where its hash puts it */
+ OPENSSL_assert(T->walk() == fz_count[t]);
+ /* _doall_arg() hands out the elements of the table, each one once */
+ T->doall(fz_seen_cb, NULL);
+ for (m = fz_model; m < fz_model + FZ_ELEMS; m++) {
+ OPENSSL_assert(m->seen == m->in[t]
+ && (m->e != NULL && T->hashed(m->e)) == m->in[t]);
+ m->seen = 0;
+ }
+}
- case OP_FLUSH:
- /*
- * only flush the table rarely
- */
- if ((flushes % 100000) != 1) {
- skipped_values++;
- flushes++;
- return 0;
- }
+static void fz_filter(int t, const FZ_MODEL *m, uint64_t value)
+{
+ fz_tables[t].filter(m->in[t] ? m->hash[t] : value, value);
+}
- /*
- * lock the table
- */
- ossl_ht_write_lock(fuzzer_table);
- rc = ossl_ht_flush(fuzzer_table);
- ossl_ht_write_unlock(fuzzer_table);
+/* One record's operation on table |t|: on |run| elements from |first| on */
+static void fz_operate(int t, unsigned int op, int alt, unsigned int first,
+ unsigned int run, uint64_t value)
+{
+ const FZ_TABLE *T = &fz_tables[t];
+ FZ_MODEL *m = &fz_model[first];
+ unsigned int i;
- /*
- * now check to make sure everything is free
- */
- if (rc == 1) {
- for (i = 0; i < USHRT_MAX; i++)
- OPENSSL_assert((prediction_table[i].flags & FZ_FLAG_ALLOCATED) == 0);
- flushes++;
+ switch (op) {
+ case OP_INSERT:
+ case OP_DELETE:
+ case OP_LOOKUP:
+ for (i = 0; i < run; i++) {
+ m = &fz_model[(first + i) % FZ_ELEMS];
+ if (op == OP_INSERT)
+ fz_insert(t, m, value + i, alt);
+ else if (op == OP_DELETE)
+ fz_delete(t, m);
+ else
+ fz_lookup(t, m, value + i, alt);
}
break;
-
+ case OP_FLUSH:
+ fz_flush(t, alt);
+ break;
case OP_FOREACH:
- valfound = 0;
- valptr = &prediction_table[keyval];
-
- rc_prediction = 0;
- if (valptr->flags & FZ_FLAG_ALLOCATED)
- rc_prediction = 1;
-
- ossl_ht_foreach_until(fuzzer_table, table_iterator, &keyval);
-
- OPENSSL_assert(valfound == rc_prediction);
-
- foreaches++;
+ fz_foreach(t);
break;
-
case OP_FILTER:
- valptr = &prediction_table[keyval];
+ fz_filter(t, m, value);
+ break;
+ case OP_RESERVE:
+ if (T->reserve != NULL)
+ T->reserve(value);
+ break;
+ }
- rc_prediction = 0;
- if (valptr->flags & FZ_FLAG_ALLOCATED)
- rc_prediction = 1;
+ OPENSSL_assert(T->num() == fz_count[t]);
+ if (T->check != NULL)
+ T->check();
+}
- htvlist = ossl_ht_filter(fuzzer_table, 1, filter_iterator, &keyval);
- if (htvlist != NULL) {
- OPENSSL_assert(htvlist->list_len == (size_t)rc_prediction);
- ossl_ht_value_list_free(htvlist);
- filters++;
- }
- break;
+int FuzzerInitialize(int *argc, char ***argv)
+{
+ OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
+ ERR_clear_error();
+ return 0;
+}
+
+int FuzzerTestOneInput(const uint8_t *buf, size_t len)
+{
+ uint64_t value;
+ unsigned int sel, tables;
+ size_t i;
+ int t;
- default:
+ /* One record at least: an operation, an element and a value */
+ if (len < FZ_RECORD)
return -1;
+
+ memset(fz_key, 0, sizeof(fz_key));
+ memcpy(fz_key, buf, len < sizeof(fz_key) ? len : sizeof(fz_key));
+ for (t = 0; t < T_COUNT; t++)
+ fz_tables[t].init();
+ fzk_check_hash(buf, len);
+
+ for (; len >= FZ_RECORD; buf += FZ_RECORD, len -= FZ_RECORD) {
+ sel = buf[1] | (unsigned int)buf[2] << 8;
+ tables = (sel >> 8) & FZ_ALL_TABLES;
+ if (tables == 0)
+ tables = FZ_ALL_TABLES;
+ for (value = 0, i = 0; i < 8; i++)
+ value |= (uint64_t)buf[3 + i] << (8 * i);
+
+ for (t = 0; t < T_COUNT; t++)
+ if ((tables & (1u << t)) != 0)
+ fz_operate(t, OPERATION(buf[0]), (buf[0] & FLAG_ALT) != 0,
+ sel % FZ_ELEMS, 1 + (sel >> 12), value);
}
+ /*
+ * Check what is left and empty the tables, one way or the other, which
+ * frees every element, then give back what the tables allocated.
+ */
+ for (t = 0; t < T_COUNT; t++) {
+ fz_foreach(t);
+ fz_flush(t, t & 1);
+ fz_tables[t].cleanup();
+ }
+ for (i = 0; i < FZ_ELEMS; i++)
+ OPENSSL_assert(fz_model[i].e == NULL);
return 0;
}
void FuzzerCleanup(void)
{
- ossl_ht_free(fuzzer_table);
- OPENSSL_free(prediction_table);
-
- fprintf(stderr, "skipped_values: %zu inserts: %zu replacements: %zu deletes %zu\n"
- "flushes: %zu lookups: %zu foreaches %zu filters %zu\n",
- skipped_values, inserts, replacements, deletes,
- flushes, lookups, foreaches, filters);
-
OPENSSL_cleanup();
}
diff --git a/include/crypto/x509.h b/include/crypto/x509.h
index 6343322ecd..4fc98fad7b 100644
--- a/include/crypto/x509.h
+++ b/include/crypto/x509.h
@@ -12,6 +12,7 @@
#pragma once
#include "internal/refcount.h"
+#include "internal/hashtable.h"
#include <openssl/asn1.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
@@ -60,6 +61,12 @@ struct X509_name_st {
/* canonical encoding used for rapid Name comparison */
unsigned char *canon_enc;
int canon_enclen;
+ /*
+ * Hash of canon_enc, valid whenever canon_enc is: both are set together.
+ * It is not keyed, so that it can be computed once per name and shared
+ * by every table the name is looked up in.
+ */
+ uint64_t canon_hash;
} /* X509_NAME */;
/* Signature info structure */
@@ -328,6 +335,14 @@ struct x509_object_st {
X509 *x509;
X509_CRL *crl;
} data;
+ /*
+ * For an object held in an X509_STORE's table of names, unused in any
+ * other object. The first object added under a name is the element of
+ * the table, and |same| of that object holds the others of the name in
+ * the order they were added; it is NULL while there are none.
+ */
+ OSSL_HTABLE_MEMBER(x509_objs);
+ STACK_OF(X509_OBJECT) *same;
};
int ossl_a2i_ipadd(unsigned char *ipout, const char *ipasc);
diff --git a/include/internal/hashfunc.h b/include/internal/hashfunc.h
index a8f66cf8e7..4d99a04128 100644
--- a/include/internal/hashfunc.h
+++ b/include/internal/hashfunc.h
@@ -12,6 +12,7 @@
#include <openssl/e_os2.h>
#include <stddef.h>
+#include <stdint.h>
#include <limits.h>
/**
@@ -38,6 +39,12 @@ static ossl_unused ossl_inline uint64_t ossl_hash_mix64(uint64_t x)
return x;
}
+/* A pointer's identity, mixed, as a 64-bit hash value. */
+static ossl_unused ossl_inline uint64_t ossl_hash_ptr(const void *p)
+{
+ return ossl_hash_mix64((uint64_t)(uintptr_t)p);
+}
+
/* A 64-bit value, mixed, as an LHASH hash value. */
static ossl_unused ossl_inline unsigned long ossl_lh_hash_u64(uint64_t x)
{
@@ -55,4 +62,76 @@ static ossl_unused ossl_inline unsigned long ossl_lh_hash_ptr(const void *p)
return ossl_lh_hash_u64((uint64_t)(uintptr_t)p);
}
+/*
+ * One-shot SipHash-2-4 with a 64-bit result under the 128-bit key |k|, the
+ * same function as SipHash_Init(ctx, k, 0, 0) with an 8-byte hash size. It
+ * is the keyed hash for tables whose keys an attacker chooses. Unlike
+ * crypto/siphash it is inline, keeps no context, and is available to libssl
+ * and the FIPS module, neither of which links crypto/siphash/siphash.c.
+ */
+#define OSSL_SIPHASH24_KEY_SIZE 16
+#define OSSL_SIPHASH24_C_ROUNDS 2
+#define OSSL_SIPHASH24_D_ROUNDS 4
+
+#define OSSL_SIPHASH24_ROTL_(x, b) (((x) << (b)) | ((x) >> (64 - (b))))
+#define OSSL_SIPHASH24_ROUND_(v0, v1, v2, v3) \
+ do { \
+ v0 += v1; \
+ v1 = OSSL_SIPHASH24_ROTL_(v1, 13); \
+ v1 ^= v0; \
+ v0 = OSSL_SIPHASH24_ROTL_(v0, 32); \
+ v2 += v3; \
+ v3 = OSSL_SIPHASH24_ROTL_(v3, 16); \
+ v3 ^= v2; \
+ v0 += v3; \
+ v3 = OSSL_SIPHASH24_ROTL_(v3, 21); \
+ v3 ^= v0; \
+ v2 += v1; \
+ v1 = OSSL_SIPHASH24_ROTL_(v1, 17); \
+ v1 ^= v2; \
+ v2 = OSSL_SIPHASH24_ROTL_(v2, 32); \
+ } while (0)
+
+static ossl_unused ossl_inline uint64_t
+ossl_siphash24_u8to64_le(const unsigned char *p)
+{
+ return (uint64_t)p[0] | (uint64_t)p[1] << 8 | (uint64_t)p[2] << 16
+ | (uint64_t)p[3] << 24 | (uint64_t)p[4] << 32 | (uint64_t)p[5] << 40
+ | (uint64_t)p[6] << 48 | (uint64_t)p[7] << 56;
+}
+
+static ossl_unused ossl_inline uint64_t
+ossl_siphash24_u64(const unsigned char k[OSSL_SIPHASH24_KEY_SIZE],
+ const void *data, size_t len)
+{
+ const unsigned char *in = data;
+ const unsigned char *end = in + (len & ~(size_t)7);
+ uint64_t k0 = ossl_siphash24_u8to64_le(k);
+ uint64_t k1 = ossl_siphash24_u8to64_le(k + 8);
+ uint64_t v0 = k0 ^ 0x736f6d6570736575ULL;
+ uint64_t v1 = k1 ^ 0x646f72616e646f6dULL;
+ uint64_t v2 = k0 ^ 0x6c7967656e657261ULL;
+ uint64_t v3 = k1 ^ 0x7465646279746573ULL;
+ uint64_t b = (uint64_t)len << 56, m;
+ size_t i;
+
+ for (; in != end; in += 8) {
+ m = ossl_siphash24_u8to64_le(in);
+ v3 ^= m;
+ for (i = 0; i < OSSL_SIPHASH24_C_ROUNDS; i++)
+ OSSL_SIPHASH24_ROUND_(v0, v1, v2, v3);
+ v0 ^= m;
+ }
+ for (i = 0; i < (len & 7); i++)
+ b |= (uint64_t)in[i] << (8 * i);
+ v3 ^= b;
+ for (i = 0; i < OSSL_SIPHASH24_C_ROUNDS; i++)
+ OSSL_SIPHASH24_ROUND_(v0, v1, v2, v3);
+ v0 ^= b;
+ v2 ^= 0xff;
+ for (i = 0; i < OSSL_SIPHASH24_D_ROUNDS; i++)
+ OSSL_SIPHASH24_ROUND_(v0, v1, v2, v3);
+ return v0 ^ v1 ^ v2 ^ v3;
+}
+
#endif
diff --git a/include/internal/hashtable.h b/include/internal/hashtable.h
index 281a7d01e0..4a25d0ff7a 100644
--- a/include/internal/hashtable.h
+++ b/include/internal/hashtable.h
@@ -1,5 +1,5 @@
/*
- * Copyright 2024-2026 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2026 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
@@ -7,497 +7,622 @@
* https://www.openssl.org/source/license.html
*/
-#ifndef OPENSSL_HASHTABLE_H
-#define OPENSSL_HASHTABLE_H
+#ifndef OSSL_INTERNAL_HASHTABLE_H
+#define OSSL_INTERNAL_HASHTABLE_H
#pragma once
-#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include <openssl/e_os2.h>
-#include <internal/rcu.h>
-#include "crypto/context.h"
-
-typedef struct ht_internal_st HT;
-
-/*
- * Represents a key to a hashtable
- */
-typedef struct ht_key_header_st {
- uint64_t cached_hash;
- size_t keysize;
- size_t bufsize;
- uint8_t *keybuf;
-} HT_KEY;
-
-/*
- * Represents a value in the hash table
- */
-typedef struct ht_value_st {
- void *value;
- uintptr_t *type_id;
- HT_KEY key;
-} HT_VALUE;
-
-/*
- * Represents a list of values filtered from a hash table
- */
-typedef struct ht_value_list_st {
- size_t list_len;
- HT_VALUE **list;
-} HT_VALUE_LIST;
-
-/*
- * Hashtable configuration
- */
-typedef struct ht_config_st {
- OSSL_LIB_CTX *ctx;
- void (*ht_free_fn)(HT_VALUE *obj);
- uint64_t (*ht_hash_fn)(HT_KEY *key);
- size_t init_neighborhoods;
- uint32_t collision_check;
- uint32_t lockless_reads;
- uint32_t no_rcu;
-} HT_CONFIG;
-
-/*
- * Hashtable key rules
- * Any struct can be used to formulate a hash table key, as long as the
- * following rules
- * 1) The first element of the struct defining the key must be an HT_KEY
- * 2) All struct elements must have a compile time defined length
- * 3) Pointers can be used, but the value of the pointer, rather than
- * the contents of the address it points to will be used to compute
- * the hash
- * The key definition macros will assist with enforcing these rules
- */
-
-/*
- * Starts the definition of a hash table key
- */
-#define HT_START_KEY_DEFN(keyname) \
- typedef struct keyname##_st { \
- HT_KEY key_header; \
- struct {
-
-/*
- * Ends a hash table key definitions
- */
-#define HT_END_KEY_DEFN(keyname) \
- } \
- keyfields; \
- } \
- keyname;
-
-/*
- * Defines a field in a hash table key
- */
-#define HT_DEF_KEY_FIELD(name, type) type name;
-
-/*
- * convenience macro to define a static char
- * array field in a hash table key
- */
-#define HT_DEF_KEY_FIELD_CHAR_ARRAY(name, size) \
- HT_DEF_KEY_FIELD(name[size], char)
-
-/*
- * Defines a uint8_t (blob) field in a hash table key
- */
-#define HT_DEF_KEY_FIELD_UINT8T_ARRAY(name, size) \
- HT_DEF_KEY_FIELD(name[size], uint8_t)
-
-/*
- * Initializes a key
- */
-#define HT_INIT_KEY(key) \
- do { \
- memset((key), 0, sizeof(*(key))); \
- (key)->key_header.keysize = (key)->key_header.bufsize = (sizeof(*(key)) - sizeof(HT_KEY)); \
- (key)->key_header.keybuf = (((uint8_t *)key) + sizeof(HT_KEY)); \
- } while (0)
-
-/*
- * Initializes a key as a raw buffer
- * This operates identically to HT_INIT_KEY
- * but it treats the provided key as a raw buffer
- * and iteratively accounts the running amount of
- * data copied into the key from the caller.
+#include <openssl/crypto.h>
+#include "internal/nelem.h"
+#include "internal/hashfunc.h"
+#include "internal/queue.h"
+#include "internal/rcu.h"
+#include "internal/threads_common.h"
+
+/*
+ * A table is an array of 1 << bits OSSL_QUEUE buckets plus an entry gauge.
+ * The number of buckets is fixed at compile time:
+ * DEFINE_HTABLE_OF(name, type, bits) defines the type OSSL_HTABLE(name) as
+ * the table of |type| elements linked through OSSL_QUEUE_MEMBER(name), with
+ * 1 << bits buckets. A table lives wherever it is declared (a struct
+ * member, a local, a static) and has no separate storage, so it never
+ * allocates, never rehashes and has nothing to free; chains simply grow when
+ * the table holds more elements than it has buckets. The caller passes the
+ * (already computed) hash to every operation and the table masks it with
+ * its compile-time bucket mask.
*
- * This MUST be used with the RAW macros below:
- * HT_COPY_RAW_KEY
- * HT_COPY_RAW_KEY_CASE
- */
-#define HT_INIT_RAW_KEY(key) \
- do { \
- HT_INIT_KEY((key)); \
- (key)->key_header.keysize = 0; \
- } while (0)
-
-/*
- * Helper function to copy raw data into a key
- * This should not be called independently
- * use the HT_COPY_RAW_KEY macro instead
- */
-static ossl_inline ossl_unused int ossl_key_raw_copy(HT_KEY *key, const uint8_t *buf, size_t len)
-{
- assert(key->keysize <= key->bufsize);
- if (len > key->bufsize - key->keysize)
- return 0;
- memcpy(&key->keybuf[key->keysize], buf, len);
- key->keysize += len;
- return 1;
-}
-
-/*
- * Copy data directly into a key
- * When initialized with HT_INIT_RAW_KEY, this macro
- * can be used to copy packed data into a key for hashtable usage
- * It is advantageous as it limits the amount of data that needs to
- * be hashed when doing inserts/lookups/deletes, as it tracks how much
- * key data is actually valid
- */
-#define HT_COPY_RAW_KEY(key, buf, len) ossl_key_raw_copy(key, buf, len)
-
-/*
- * Similar to HT_COPY_RAW_KEY but accepts a character buffer, and copies
- * data while converting case for case insensitive matches
- */
-#define HT_COPY_RAW_KEY_CASE(key, buf, len) \
- do { \
- size_t tmplen = (size_t)(len); \
- assert((key)->keysize <= (key)->bufsize); \
- if (tmplen > (key)->bufsize - (key)->keysize) \
- tmplen = (key)->bufsize - (key)->keysize; \
- ossl_ht_strcase((key), (char *)&((key)->keybuf[(key)->keysize]), buf, tmplen); \
- (key)->keysize += tmplen; \
- } while (0)
-
-#define HT_INIT_KEY_CACHED(key, hash) \
- do { \
- HT_INIT_KEY((key)); \
- (key)->key_header.cached_hash = hash; \
- } while (0)
-
-#define HT_INIT_KEY_EXTERNAL(key, buf, len) \
- do { \
- HT_INIT_KEY((key)); \
- (key)->key_header.keybuf = (buf); \
- (key)->key_header.keysize = (len); \
- (key)->key_header.bufsize = (len); \
- } while (0)
-
-#define HT_KEY_GET_HASH(key) (key)->key_header.cached_hash
-
-/*
- * Resets a hash table key to a known state
- */
-#define HT_KEY_RESET(key) \
- do { \
- memset((key)->key_header.keybuf, 0, (key)->key_header.keysize); \
- (key)->key_header.cached_hash = 0; \
- } while (0)
-
-/*
- * Sets a scalar field in a hash table key
- */
-#define HT_SET_KEY_FIELD(key, member, value) (key)->keyfields.member = value;
-
-/*
- * Sets a string field in a hash table key, preserving
- * null terminator
- */
-#define HT_SET_KEY_STRING(key, member, value) \
- do { \
- if ((value) != NULL) \
- strncpy((key)->keyfields.member, value, sizeof((key)->keyfields.member) - 1); \
- } while (0)
-
-/*
- * This is the same as HT_SET_KEY_STRING, except that it uses
- * ossl_ht_strcase to make the value being passed case insensitive
- * This is useful for instances in which we want upper and lower case
- * key value to hash to the same entry
- */
-#define HT_SET_KEY_STRING_CASE(key, member, value) \
- do { \
- ossl_ht_strcase(NULL, (key)->keyfields.member, value, sizeof((key)->keyfields.member) - 1); \
- } while (0)
-
-/*
- * Same as HT_SET_KEY_STRING but also takes length of the string.
- */
-#define HT_SET_KEY_STRING_N(key, member, value, len) \
- do { \
- if ((value) != NULL) { \
- if (len < sizeof((key)->keyfields.member)) \
- strncpy((key)->keyfields.member, value, len); \
- else \
- strncpy((key)->keyfields.member, value, sizeof((key)->keyfields.member) - 1); \
- } \
- } while (0)
-
-/* Same as HT_SET_KEY_STRING_CASE but also takes length of the string. */
-#define HT_SET_KEY_STRING_CASE_N(key, member, value, len) \
- do { \
- if ((size_t)len < sizeof((key)->keyfields.member)) \
- ossl_ht_strcase(NULL, (key)->keyfields.member, value, len); \
- else \
- ossl_ht_strcase(NULL, (key)->keyfields.member, value, sizeof((key)->keyfields.member) - 1); \
- } while (0)
-
-/*
- * Sets a uint8_t (blob) field in a hash table key
- */
-#define HT_SET_KEY_BLOB(key, member, value, len) \
- do { \
- if (value != NULL) \
- memcpy((key)->keyfields.member, value, len); \
- } while (0)
-
-/*
- * Converts a defined key type to an HT_KEY
- */
-#define TO_HT_KEY(key) &(key)->key_header
-
-/*
- * Converts an HT_KEY back to its defined
- * type
- */
-#define FROM_HT_KEY(key, type) (type)(key)
-
-/*
- * Implements the following type safe operations for a hash table
- * ossl_ht_NAME_TYPE_insert - insert a value to a hash table of type TYPE
- * ossl_ht_NAME_TYPE_get - gets a value of a specific type from the hash table
- * ossl_ht_NAME_TYPE_from_value - converts an HT_VALUE to its type
- * ossl_ht_NAME_TYPE_to_value - converts a TYPE to an HT_VALUE
- * ossl_ht_NAME_TYPE_type - boolean to detect if a value is of TYPE
- */
-#define IMPLEMENT_HT_VALUE_TYPE_FNS(vtype, name, pfx) \
- static uintptr_t name##_##vtype##_id = 0; \
- pfx ossl_unused int ossl_ht_##name##_##vtype##_insert(HT *h, HT_KEY *key, \
- vtype *data, \
- vtype **olddata) \
- { \
- HT_VALUE inval; \
- HT_VALUE *oval = NULL; \
- int rc; \
- \
- inval.value = data; \
- inval.type_id = &name##_##vtype##_id; \
- rc = ossl_ht_insert(h, key, &inval, olddata == NULL ? NULL : &oval); \
- if (oval != NULL) \
- *olddata = (vtype *)ossl_ht_inner_value(h, oval); \
- return rc; \
- } \
- \
- pfx ossl_unused vtype *ossl_ht_##name##_##vtype##_from_value(HT_VALUE *v) \
- { \
- uintptr_t *expect_type = &name##_##vtype##_id; \
- if (v == NULL) \
- return NULL; \
- if (v->type_id != expect_type) \
- return NULL; \
- return (vtype *)v->value; \
- } \
- \
- pfx ossl_unused vtype *ossl_unused ossl_ht_##name##_##vtype##_get(HT *h, \
- HT_KEY *key, \
- HT_VALUE **v) \
- { \
- HT_VALUE *vv; \
- vv = ossl_ht_get(h, key); \
- if (vv == NULL) \
- return NULL; \
- *v = ossl_ht_deref_value(h, &vv); \
- return ossl_ht_##name##_##vtype##_from_value(*v); \
- } \
- \
- pfx ossl_unused HT_VALUE *ossl_ht_##name##_##vtype##_to_value(vtype *data, \
- HT_VALUE *v) \
- { \
- v->type_id = &name##_##vtype##_id; \
- v->value = data; \
- return v; \
- } \
- \
- pfx ossl_unused int ossl_ht_##name##_##vtype##_type(HT_VALUE *h) \
- { \
- return h->type_id == &name##_##vtype##_id; \
+ * typedef struct foo_st { uint64_t key; OSSL_QUEUE_MEMBER(idx); } FOO;
+ * DEFINE_QUEUE_OF(idx, FOO);
+ * DEFINE_HTABLE_OF(idx, FOO, 10); 1024 buckets, 8 KB on LP64
+ *
+ * OSSL_HTABLE(idx) table; or static, = OSSL_HTABLE_INIT
+ * ossl_htable_idx_init(&table);
+ * ossl_queue_idx_init_elem(foo); unless foo was zeroed
+ * ossl_htable_idx_add(&table, foo, ossl_hash_mix64(foo->key));
+ * OSSL_HTABLE_FIND(p, idx, &table, ossl_hash_mix64(key), p->key == key);
+ * ossl_htable_idx_del(&table, foo);
+ *
+ * When the peer chooses the keys, use DEFINE_HTABLE_KEYED_OF instead; see
+ * the keyed tables section below. When the number of elements has no small
+ * bound, use the growable table DEFINE_HTABLE_DYN_OF, also below. Nothing
+ * here synchronises: the caller's lock covers every operation. For an
+ * insert-only table read without a lock, see DEFINE_HTABLE_RCU_OF, the last
+ * section below.
+ *
+ * Elements. An element's link records whether the element is in a table, so
+ * it must be clear before the element is added for the first time: the
+ * element comes from OPENSSL_zalloc() or from static storage, or
+ * ossl_queue_<name>_init_elem() is called on it. Adding asserts that the
+ * link is clear, and so reads it: over uninitialised memory a debug build
+ * may abort, and a release build, which has no assertion, hides the mistake.
+ * _del() clears the link again, so an element taken out of a table can be
+ * added straight back.
+ *
+ * Cleanup. ossl_htable_<name>_cleanup() ends the use of a table of any kind.
+ * It frees what the table allocated, which is nothing but the grown buckets
+ * of a growable table, and it never looks at the elements, so they may have
+ * been freed already. It does not unlink them either: an element that was
+ * still in the table is left with a link into buckets that are gone. Such an
+ * element must not be given to _del(), _del_init() or _ruc(), which write
+ * through that link; it is freed, or cleared with
+ * ossl_queue_<name>_init_elem() before it is added to a table again. To use
+ * the table itself again, _init() it first.
+ */
+
+/* The table type defined by DEFINE_HTABLE_OF(name, ...). */
+#define OSSL_HTABLE(name) OSSL_HTABLE_##name
+
+/* Sanity bound on |bits|: a table never has more than 1 << 30 buckets. */
+#define OSSL_HTABLE_MAX_BITS 30
+
+/* Static initialiser: every bucket empty and the gauge zero. */
+#define OSSL_HTABLE_INIT { { OSSL_QUEUE_INIT }, 0 }
+
+/* The entry gauge, for a pointer to a table of any kind. */
+#define ossl_htable_num(ht) ((ht)->num)
+#define ossl_htable_is_empty(ht) ((ht)->num == 0)
+
+/*
+ * The buckets of a static table (DEFINE_HTABLE_OF, DEFINE_HTABLE_KEYED_OF),
+ * whose count and mask are compile-time constants of the table's type. A
+ * growable table keeps them at run time and has no |buckets| member, so
+ * these three do not compile for one. ossl_htable_<name>_num_buckets() and
+ * ossl_htable_<name>_bucket() are defined for every kind of table.
+ */
+#define ossl_htable_num_buckets(ht) OSSL_NELEM((ht)->buckets)
+#define ossl_htable_mask(ht) ((uint64_t)ossl_htable_num_buckets(ht) - 1)
+#define ossl_htable_bucket(ht, hash) \
+ (&(ht)->buckets[(hash) & ossl_htable_mask(ht)])
+
+/*
+ * The table masks the hash with the bucket mask, so the low bits must be
+ * well mixed. Sequence-like keys (stream IDs, packet numbers) distribute
+ * perfectly by themselves and may be passed through unchanged; arbitrary
+ * integers and pointers should go through ossl_hash_mix64()/ossl_hash_ptr()
+ * (the splitmix64 finaliser, internal/hashfunc.h). Keys that an attacker
+ * controls need a keyed hash instead to resist hash flooding:
+ * DEFINE_HTABLE_KEYED_OF below.
+ */
+
+/*
+ * Define OSSL_HTABLE(name), the table of 1 << |bits| buckets of |type|
+ * elements linked through OSSL_QUEUE_MEMBER(name), and its operations. The
+ * matching DEFINE_QUEUE_OF(name, type) must come first.
+ */
+#define DEFINE_HTABLE_OF(name, type, bits) \
+ OSSL_HTABLE_BITS_CHECK_(name, bits); \
+ typedef struct ossl_htable_##name##_st { \
+ OSSL_QUEUE buckets[(size_t)1 << (bits)]; \
+ size_t num; /* elements currently in the table */ \
+ } OSSL_HTABLE(name); \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_init(OSSL_HTABLE(name) *ht) \
+ { \
+ ossl_htable_init_buckets(ht->buckets, ossl_htable_num_buckets(ht)); \
+ ht->num = 0; \
+ } \
+ OSSL_HTABLE_DEFINE_STATIC_ACCESS_(name, type) \
+ OSSL_HTABLE_DEFINE_OPS_(name, type) \
+ struct ossl_htable_dummy_st_##name
+
+/*
+ * Keyed tables, for keys the peer chooses.
+ *
+ * An unkeyed hash over wire data (the OIDs of a certificate's extensions, a
+ * peer address, a connection ID) lets the sender precompute keys that share
+ * a bucket and turn every lookup into a chain walk. DEFINE_HTABLE_KEYED_OF
+ * defines the same table with a 128-bit key, which
+ * ossl_htable_<name>_init(ht, key) copies from the caller, and generates
+ *
+ * uint64_t ossl_htable_<name>_hash(const table *ht, const void *data,
+ * size_t len);
+ * uint64_t ossl_htable_<name>_hash_u64(const table *ht, uint64_t x);
+ *
+ * which are SipHash-2-4 under that key (ossl_siphash24_u64() of
+ * internal/hashfunc.h). The hash is bound to the table by
+ * name at its definition: no function pointer is stored and every other
+ * operation still takes the computed hash, exactly as for an unkeyed table.
+ * OSSL_HTABLE_INIT cannot key a table, so a keyed table is always
+ * initialised at run time.
+ *
+ * The caller draws the key, a new one for each table. It has to be
+ * unpredictable to the peer, not secret, and where it comes from depends on
+ * the library the table is in. libcrypto uses ossl_rand_hash_salt()
+ * (crypto/rand.h), which has other sources to fall back on in a library
+ * context without a usable RAND, such as one with only the null provider:
+ * a certificate must not become invalid there because a table could not be
+ * keyed. That function is not available to libssl and the FIPS module,
+ * which use RAND_bytes_ex().
+ *
+ * DEFINE_QUEUE_OF(oid, OID_ENTRY);
+ * DEFINE_HTABLE_KEYED_OF(oid, OID_ENTRY, 6);
+ *
+ * unsigned char key[OSSL_HTABLE_KEY_SIZE];
+ *
+ * if (!ossl_rand_hash_salt(libctx, key, sizeof(key)))
+ * return 0;
+ * ossl_htable_oid_init(&table, key);
+ * h = ossl_htable_oid_hash(&table, OBJ_get0_data(obj), OBJ_length(obj));
+ * OSSL_HTABLE_FIND(p, oid, &table, h, OBJ_cmp(p->obj, obj) == 0);
+ */
+#define OSSL_HTABLE_KEY_SIZE OSSL_SIPHASH24_KEY_SIZE
+
+#define DEFINE_HTABLE_KEYED_OF(name, type, bits) \
+ OSSL_HTABLE_BITS_CHECK_(name, bits); \
+ typedef struct ossl_htable_##name##_st { \
+ OSSL_QUEUE buckets[(size_t)1 << (bits)]; \
+ size_t num; /* elements currently in the table */ \
+ unsigned char key[OSSL_HTABLE_KEY_SIZE]; /* set by _init() */ \
+ } OSSL_HTABLE(name); \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_init(OSSL_HTABLE(name) *ht, \
+ const unsigned char key[OSSL_HTABLE_KEY_SIZE]) \
+ { \
+ ossl_htable_init_buckets(ht->buckets, ossl_htable_num_buckets(ht)); \
+ ht->num = 0; \
+ memcpy(ht->key, key, sizeof(ht->key)); \
+ } \
+ static ossl_unused ossl_inline uint64_t \
+ ossl_htable_##name##_hash(const OSSL_HTABLE(name) *ht, const void *data, \
+ size_t len) \
+ { \
+ return ossl_siphash24_u64(ht->key, data, len); \
+ } \
+ static ossl_unused ossl_inline uint64_t \
+ ossl_htable_##name##_hash_u64(const OSSL_HTABLE(name) *ht, uint64_t x) \
+ { \
+ unsigned char b[8]; \
+ size_t i; \
+ \
+ for (i = 0; i < sizeof(b); i++) \
+ b[i] = (unsigned char)(x >> (8 * i)); \
+ return ossl_siphash24_u64(ht->key, b, sizeof(b)); \
+ } \
+ OSSL_HTABLE_DEFINE_STATIC_ACCESS_(name, type) \
+ OSSL_HTABLE_DEFINE_OPS_(name, type) \
+ struct ossl_htable_dummy_st_##name
+
+/*
+ * Growable tables.
+ *
+ * DEFINE_HTABLE_DYN_OF(name, type, min_bits, max_bits) defines
+ * OSSL_HTABLE(name) as a table that starts with 1 << min_bits buckets held
+ * in the table itself, and doubles its buckets, up to 1 << max_bits, as soon
+ * as it holds more elements than it has buckets, so chains stay short
+ * whatever the number of elements. Growing allocates the new bucket array;
+ * when that fails the table keeps its buckets and its longer chains and
+ * tries again at the next add, so add still cannot fail. The table never
+ * shrinks.
+ *
+ * The element embeds OSSL_HTABLE_MEMBER(name) instead of
+ * OSSL_QUEUE_MEMBER(name): the link plus the hash the element was added
+ * under. Growing re-links the elements by that stored hash without hashing
+ * them again, and OSSL_HTABLE_FIND compares it before evaluating |cond|, so
+ * a lookup only compares the keys of elements whose full 64-bit hash
+ * matches. Keep the member next to the key in the element so that both
+ * share a cache line.
+ *
+ * typedef struct foo_st { OSSL_HTABLE_MEMBER(idx); uint64_t key; } FOO;
+ * DEFINE_QUEUE_OF(idx, FOO);
+ * DEFINE_HTABLE_DYN_OF(idx, FOO, 4, 20); 16 buckets inline, up to 1M
+ *
+ * ossl_htable_idx_init(&table);
+ * ossl_queue_idx_init_elem(foo); unless foo was zeroed
+ * ossl_htable_idx_add(&table, foo, ossl_hash_mix64(foo->key));
+ * OSSL_HTABLE_FIND(p, idx, &table, ossl_hash_mix64(key), p->key == key);
+ * ossl_htable_idx_del(&table, foo);
+ * ossl_htable_idx_cleanup(&table); frees the grown buckets
+ *
+ * Every per-name operation and macro of a static table works on a growable
+ * one; ossl_htable_num_buckets(), ossl_htable_mask() and ossl_htable_bucket()
+ * above, which read the bucket count off a static table's type, do not
+ * compile for it. Since the buckets may live in the table itself, a growable
+ * table must not be copied or moved once initialised (the elements' links
+ * point into the buckets anyway, for either kind of table), has no static
+ * initialiser, and must be cleaned up with ossl_htable_<name>_cleanup(),
+ * which leaves the elements linked: see "Cleanup" above.
+ * ossl_htable_<name>_reserve(ht, n) grows the buckets up front for |n|
+ * elements.
+ */
+#define OSSL_HTABLE_MEMBER(name) \
+ OSSL_QNODE ossl_queue_##name; \
+ uint64_t ossl_htable_hash_##name
+
+/*
+ * The current buckets are |dyn_buckets|, not |buckets|, to keep the static
+ * tables' accessors, which take OSSL_NELEM() of |buckets|, from compiling.
+ */
+#define DEFINE_HTABLE_DYN_OF(name, type, min_bits, max_bits) \
+ OSSL_HTABLE_BITS_CHECK_(name, max_bits); \
+ typedef char ossl_htable_##name##_min_bits_check \
+ [(unsigned)(min_bits) <= (unsigned)(max_bits) ? 1 : -1]; \
+ typedef struct ossl_htable_##name##_st { \
+ OSSL_QUEUE *dyn_buckets; /* inline_buckets, or a grown heap array */ \
+ size_t mask; /* number of buckets - 1 */ \
+ size_t num; /* elements currently in the table */ \
+ OSSL_QUEUE inline_buckets[(size_t)1 << (min_bits)]; \
+ } OSSL_HTABLE(name); \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_init(OSSL_HTABLE(name) *ht) \
+ { \
+ ht->dyn_buckets = ht->inline_buckets; \
+ ht->mask = OSSL_NELEM(ht->inline_buckets) - 1; \
+ ht->num = 0; \
+ ossl_htable_init_buckets(ht->dyn_buckets, ht->mask + 1); \
+ } \
+ /* \
+ * Free the grown buckets. The elements are neither visited nor unlinked: \
+ * see "Cleanup" above. The table is left as _init() leaves it, so that a \
+ * second cleanup is harmless. \
+ */ \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_cleanup(OSSL_HTABLE(name) *ht) \
+ { \
+ if (ht->dyn_buckets != ht->inline_buckets) \
+ OPENSSL_free(ht->dyn_buckets); \
+ ossl_htable_##name##_init(ht); \
+ } \
+ static ossl_unused ossl_inline size_t \
+ ossl_htable_##name##_num_buckets(const OSSL_HTABLE(name) *ht) \
+ { \
+ return ht->mask + 1; \
+ } \
+ static ossl_unused ossl_inline OSSL_QUEUE * \
+ ossl_htable_##name##_bucket(const OSSL_HTABLE(name) *ht, uint64_t hash) \
+ { \
+ return &ht->dyn_buckets[(size_t)hash & ht->mask]; \
+ } \
+ static ossl_unused ossl_inline uint64_t \
+ ossl_htable_##name##_hash_of(const type *el) \
+ { \
+ return el->ossl_htable_hash_##name; \
+ } \
+ static ossl_unused ossl_inline int \
+ ossl_htable_##name##_hash_eq(const type *el, uint64_t hash) \
+ { \
+ return el->ossl_htable_hash_##name == hash; \
+ } \
+ /* Re-link every element into |n| buckets by its stored hash. */ \
+ static ossl_unused int \
+ ossl_htable_##name##_resize_(OSSL_HTABLE(name) *ht, size_t n) \
+ { \
+ OSSL_QUEUE *nb; \
+ type *p, *pn; \
+ size_t i; \
+ \
+ /* \
+ * Growing is best effort, so a failure here is not an error of the \
+ * operation that asked for it: no file and line, nothing is raised. \
+ */ \
+ nb = CRYPTO_malloc_array(n, sizeof(*nb), NULL, 0); \
+ if (nb == NULL) \
+ return 0; \
+ ossl_htable_init_buckets(nb, n); \
+ for (i = 0; i <= ht->mask; i++) \
+ OSSL_QUEUE_FOREACH_DELSAFE (p, pn, name, &ht->dyn_buckets[i]) { \
+ /* The old buckets are discarded whole: no unlinking needed */ \
+ ossl_queue_##name##_init_elem(p); \
+ ossl_queue_##name##_add( \
+ &nb[(size_t)p->ossl_htable_hash_##name & (n - 1)], p); \
+ } \
+ if (ht->dyn_buckets != ht->inline_buckets) \
+ OPENSSL_free(ht->dyn_buckets); \
+ ht->dyn_buckets = nb; \
+ ht->mask = n - 1; \
+ return 1; \
+ } \
+ /* \
+ * Grow the buckets for |n| elements at one per bucket, within max_bits. \
+ * Returns 0 if the allocation failed, the table being unchanged. \
+ */ \
+ static ossl_unused ossl_inline int \
+ ossl_htable_##name##_reserve(OSSL_HTABLE(name) *ht, size_t n) \
+ { \
+ size_t nb = ht->mask + 1; \
+ \
+ while (nb < n && nb < ((size_t)1 << (max_bits))) \
+ nb <<= 1; \
+ return nb == ht->mask + 1 || ossl_htable_##name##_resize_(ht, nb); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_add(OSSL_HTABLE(name) *ht, type *el, uint64_t hash) \
+ { \
+ el->ossl_htable_hash_##name = hash; \
+ ossl_queue_##name##_add(ossl_htable_##name##_bucket(ht, hash), el); \
+ if (++ht->num > ht->mask + 1 && ht->mask < ((size_t)1 << (max_bits)) - 1) \
+ (void)ossl_htable_##name##_resize_(ht, (ht->mask + 1) * 2); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_del(OSSL_HTABLE(name) *ht, type *el) \
+ { \
+ ossl_queue_##name##_del(el); \
+ ht->num--; \
+ } \
+ /* As for a static table; |hash| becomes the element's stored hash. */ \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_ruc(OSSL_HTABLE(name) *ht, type *el, uint64_t hash) \
+ { \
+ ossl_queue_##name##_del(el); \
+ el->ossl_htable_hash_##name = hash; \
+ ossl_queue_##name##_add(ossl_htable_##name##_bucket(ht, hash), el); \
+ } \
+ OSSL_HTABLE_DEFINE_COMMON_OPS_(name, type) \
+ struct ossl_htable_dummy_st_##name
+
+/* Implementation details shared by the table definitions. */
+
+#define OSSL_HTABLE_BITS_CHECK_(name, bits) \
+ typedef char ossl_htable_##name##_bits_check \
+ [(unsigned)(bits) <= OSSL_HTABLE_MAX_BITS ? 1 : -1]
+
+/*
+ * The per-name accessors of a static table, which the macros below use so
+ * that they work on either kind. A static table stores no hashes, so
+ * _hash_eq() lets every element through to the caller's comparison.
+ */
+#define OSSL_HTABLE_DEFINE_STATIC_ACCESS_(name, type) \
+ /* Marks a table that never re-links: DEFINE_HTABLE_RCU_OF */ \
+ typedef char ossl_htable_##name##_fixed_size; \
+ static ossl_unused ossl_inline size_t \
+ ossl_htable_##name##_num_buckets(const OSSL_HTABLE(name) *ht) \
+ { \
+ return ossl_htable_num_buckets(ht); \
+ } \
+ static ossl_unused ossl_inline OSSL_QUEUE * \
+ ossl_htable_##name##_bucket(const OSSL_HTABLE(name) *ht, \
+ uint64_t hash) \
+ { \
+ return (OSSL_QUEUE *)ossl_htable_bucket(ht, hash); \
+ } \
+ static ossl_unused ossl_inline int \
+ ossl_htable_##name##_hash_eq(const type *el, uint64_t hash) \
+ { \
+ (void)el; \
+ (void)hash; \
+ return 1; \
+ } \
+ /* Nothing to free. Same contract as for a growable table. */ \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_cleanup(OSSL_HTABLE(name) *ht) \
+ { \
+ (void)ht; \
}
-#define DECLARE_HT_VALUE_TYPE_FNS(vtype, name) \
- int ossl_ht_##name##_##vtype##_insert(HT *h, HT_KEY *key, vtype *data, \
- vtype **olddata); \
- vtype *ossl_ht_##name##_##vtype##_from_value(HT_VALUE *v); \
- vtype *ossl_unused ossl_ht_##name##_##vtype##_get(HT *h, \
- HT_KEY *key, \
- HT_VALUE **v); \
- HT_VALUE *ossl_ht_##name##_##vtype##_to_value(vtype *data, HT_VALUE *v); \
- int ossl_ht_##name##_##vtype##_type(HT_VALUE *h);
-
-/*
- * Helper function to construct case insensitive keys
- */
-static ossl_inline ossl_unused void ossl_ht_strcase(HT_KEY *key, char *tgt, const char *src, size_t len)
+static ossl_unused ossl_inline void
+ossl_htable_init_buckets(OSSL_QUEUE *buckets, size_t n)
{
size_t i;
-#if defined(CHARSET_EBCDIC) && !defined(CHARSET_EBCDIC_TEST)
- const long int case_adjust = ~0x40;
-#else
- const long int case_adjust = ~0x20;
-#endif
-
- if (src == NULL)
- return;
-
- /*
- * If we're passed a key, we're doing raw key copies
- * so check that we don't overflow here, and truncate if
- * we copy more space than we have available
- */
- if (key != NULL) {
- assert(key->keysize <= key->bufsize);
- if (len > key->bufsize - key->keysize)
- len = key->bufsize - key->keysize;
- }
- for (i = 0; i < len && src[i] != '\0'; i++)
- tgt[i] = case_adjust & src[i];
+ for (i = 0; i < n; i++)
+ ossl_queue_init(&buckets[i]);
}
-/*
- * Create a new hashtable
- */
-HT *ossl_ht_new(const HT_CONFIG *conf);
-
-/*
- * Frees a hash table, potentially freeing all elements
- */
-void ossl_ht_free(HT *htable);
-
-/*
- * Lock the table for reading
- */
-int ossl_ht_read_lock(HT *htable);
-
-/*
- * Lock the table for writing
- */
-void ossl_ht_write_lock(HT *htable);
-
-/*
- * Read unlock
- */
-void ossl_ht_read_unlock(HT *htable);
-
-/*
- * Write unlock
- */
-void ossl_ht_write_unlock(HT *htable);
-
-/*
- * Empties a hash table, potentially freeing all elements
- */
-int ossl_ht_flush(HT *htable);
-
-/*
- * Inserts an element to a hash table, optionally returning
- * replaced data to caller
- * Returns 1 if the insert was successful, 0 on duplicate without
- * replacement, invalid input, or another non-allocation failure, and -1
- * on allocation failure or if the table could not be grown.
- */
-int ossl_ht_insert(HT *htable, HT_KEY *key, HT_VALUE *data,
- HT_VALUE **olddata);
+#define OSSL_HTABLE_DEFINE_OPS_(name, type) \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_add(OSSL_HTABLE(name) *ht, type *el, uint64_t hash) \
+ { \
+ ossl_queue_##name##_add(ossl_htable_bucket(ht, hash), el); \
+ ht->num++; \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_del(OSSL_HTABLE(name) *ht, type *el) \
+ { \
+ ossl_queue_##name##_del(el); \
+ ht->num--; \
+ } \
+ /* \
+ * Recently-used-cache promotion: move |el| to the head of the bucket \
+ * for |hash| (which may differ from its current bucket if the key \
+ * changed). The entry count is unchanged. \
+ */ \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_ruc(OSSL_HTABLE(name) *ht, type *el, uint64_t hash) \
+ { \
+ ossl_queue_##name##_del(el); \
+ ossl_queue_##name##_add(ossl_htable_bucket(ht, hash), el); \
+ } \
+ OSSL_HTABLE_DEFINE_COMMON_OPS_(name, type)
+
+/* The operations that are the same for static and growable tables. */
+#define OSSL_HTABLE_DEFINE_COMMON_OPS_(name, type) \
+ static ossl_unused ossl_inline type * \
+ ossl_htable_##name##_head(const OSSL_HTABLE(name) *ht, uint64_t hash) \
+ { \
+ return ossl_queue_##name##_head(ossl_htable_##name##_bucket(ht, hash)); \
+ } \
+ /* \
+ * Visit every element. |fn| may remove the element it is handed but no \
+ * other one, and may not add elements. \
+ */ \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_doall_arg(OSSL_HTABLE(name) *ht, \
+ void (*fn)(type * el, void *arg), void *arg) \
+ { \
+ type *p, *pn; \
+ size_t i, n = ossl_htable_##name##_num_buckets(ht); \
+ \
+ for (i = 0; i < n; i++) \
+ OSSL_QUEUE_FOREACH_DELSAFE (p, pn, name, \
+ ossl_htable_##name##_bucket(ht, i)) \
+ fn(p, arg); \
+ }
-/*
- * Deletes a value from a hash table, based on key
- * Returns 1 if the key was removed, 0 if they key was not found
- */
-int ossl_ht_delete(HT *htable, HT_KEY *key);
+#define OSSL_HTABLE_FOREACH(p, name, ht, hash) \
+ OSSL_QUEUE_FOREACH (p, name, ossl_htable_##name##_bucket((ht), (hash)))
-/*
- * Returns number of elements in the hash table
- */
-size_t ossl_ht_count(HT *htable);
+#define OSSL_HTABLE_FOREACH_DELSAFE(p, pn, name, ht, hash) \
+ OSSL_QUEUE_FOREACH_DELSAFE (p, pn, name, \
+ ossl_htable_##name##_bucket((ht), (hash)))
/*
- * Iterates over each element in the table.
- * aborts the loop when cb returns 0
- * Contents of elements in the list may be modified during
- * this traversal, assuming proper thread safety is observed while doing
- * so (holding the table write lock is sufficient). However, elements of the
- * table may not be inserted or removed while iterating.
+ * Search the bucket for |hash|, leaving in |p| the first element for which
+ * |cond| (an expression over |p|) holds, or NULL. |hash| is evaluated once.
+ * In a growable table |cond| is only evaluated for the elements stored under
+ * the same |hash|.
*/
-void ossl_ht_foreach_until(HT *htable, int (*cb)(HT_VALUE *obj, void *arg),
- void *arg);
-/*
- * Returns a list of elements in a hash table based on
- * filter function return value. Returns NULL on error,
- * or an HT_VALUE_LIST object on success. Note it is possible
- * That a list will be returned with 0 entries, if none were found.
- * The zero length list must still be freed via ossl_ht_value_list_free
- */
-HT_VALUE_LIST *ossl_ht_filter(HT *htable, size_t max_len,
- int (*filter)(HT_VALUE *obj, void *arg),
- void *arg);
-/*
- * Frees the list returned from ossl_ht_filter
- */
-void ossl_ht_value_list_free(HT_VALUE_LIST *list);
+#define OSSL_HTABLE_FIND(p, name, ht, hash, cond) \
+ do { \
+ const uint64_t ossl_htable_find_hash_ = (hash); \
+ \
+ OSSL_HTABLE_FOREACH (p, name, ht, ossl_htable_find_hash_) \
+ if (ossl_htable_##name##_hash_eq(p, ossl_htable_find_hash_) \
+ && (cond)) \
+ break; \
+ } while (0)
/*
- * Fetches a value from the hash table, based
- * on key. Returns NULL if the element was not found.
- */
-HT_VALUE *ossl_ht_get(HT *htable, HT_KEY *key);
-
-/**
- * ossl_ht_deref_value - Dereference a value stored in a hash table entry
- * @h: The hash table handle
- * @val: Pointer to the value pointer inside the hash table
+ * Lock-free readers for an insert-only OSSL_HTABLE.
*
- * This helper returns the actual value stored in a hash table entry,
- * with awareness of whether the table is configured for RCU (Read-Copy-Update)
- * safe lookups.
+ * DEFINE_HTABLE_RCU_OF(name, type), placed after the DEFINE_HTABLE_OF or
+ * DEFINE_HTABLE_KEYED_OF of the same name, adds
*
- * If the hash table is configured to use RCU lookups, the function
- * calls ossl_rcu_deref() to safely read the value under RCU protection.
- * This ensures that the caller sees a consistent pointer in concurrent environments.
+ * void ossl_htable_<name>_add_rcu(table *ht, type *el, uint64_t hash);
+ * OSSL_HTABLE_FOREACH_RCU(p, name, ht, hash)
+ * OSSL_HTABLE_FIND_RCU(p, name, ht, hash, cond)
*
- * If RCU is not enabled (i.e. `h->config.no_rcu` is true), the function
- * simply dereferences @val directly.
+ * _add_rcu() publishes an element: it links the fully initialised element
+ * and then stores the bucket head with release semantics, so a reader that
+ * sees the element sees everything written to it beforehand. The two reader
+ * macros load the head and each link with acquire semantics. Readers take no
+ * lock and need no ossl_rcu_read_lock().
*
- * Return:
- * A pointer to the dereferenced hash table value (`HT_VALUE *`), or NULL if
- * the underlying pointer is NULL.
- */
-HT_VALUE *ossl_ht_deref_value(HT *p, HT_VALUE **val);
-
-/**
- * ossl_ht_inner_value - Extract the user payload from a hash table value
- * @h: The hash table handle
- * @v: The hash table value wrapper (HT_VALUE)
+ * The rules that make this safe:
*
- * This helper returns the user-provided payload stored inside a
- * hash table value container. The behavior differs depending on
- * whether the hash table is configured to use RCU (Read-Copy-Update)
- * for concurrency control.
+ * - Writers serialise among themselves (the caller's lock). Readers never
+ * block and never retry.
+ * - Elements are only ever added. While a reader may be running, an element
+ * must not be removed, moved (_del, _ruc) or freed, and the fields the
+ * readers' |cond| looks at must not change after _add_rcu(). There is
+ * therefore no grace period to wait for; the elements are freed when the
+ * table's owner is, once no reader can exist.
+ * - The table is of the fixed-size kind. A growable table re-links its
+ * elements when it grows, which would lead a concurrent reader into the
+ * wrong chain, so DEFINE_HTABLE_RCU_OF does not compile for a table
+ * defined with DEFINE_HTABLE_DYN_OF.
+ * - The entry gauge (ossl_htable_num()) and every non-_rcu operation belong
+ * to the writer side and need the writers' lock.
*
- * - If RCU is enabled, the function simply returns `v->value` without
- * modifying or freeing the container.
+ * typedef struct foo_st { uint64_t key; OSSL_QUEUE_MEMBER(idx); } FOO;
+ * DEFINE_QUEUE_OF(idx, FOO);
+ * DEFINE_HTABLE_OF(idx, FOO, 10);
+ * DEFINE_HTABLE_RCU_OF(idx, FOO);
*
- * - If RCU is disabled the container structure `v` is no longer needed once
- * the inner pointer has been extracted. In this case, the function frees
- * `v` and returns the inner `value` pointer directly.
+ * writer, under its lock:
+ * ossl_queue_idx_init_elem(foo); unless foo was zeroed
+ * foo->key = key;
+ * ossl_htable_idx_add_rcu(&table, foo, ossl_hash_mix64(key));
+ * reader, no lock:
+ * OSSL_HTABLE_FIND_RCU(p, idx, &table, ossl_hash_mix64(key),
+ * p->key == key);
*
- * Return:
- * A pointer to the user payload (`void *`) contained in the hash table
- * value wrapper.
+ * The ossl_rcu_*() primitives are internal to libcrypto, so this section is
+ * for libcrypto and the FIPS module only; libssl cannot link against them.
*/
-void *ossl_ht_inner_value(HT *h, HT_VALUE *v);
+/*
+ * A reader's load of a published link. ossl_rcu_deref() is a function call
+ * around one load; where that load is the compiler's own atomic (the same
+ * condition under which crypto/threads_pthread.c uses it), do it in place.
+ */
+#if defined(OSSL_USE_GCC_ATOMICS)
+#define ossl_htable_rcu_load_(pp) __atomic_load_n((pp), __ATOMIC_ACQUIRE)
+#else
+#define ossl_htable_rcu_load_(pp) ((OSSL_QNODE *)ossl_rcu_deref(pp))
#endif
+
+/* Publish |n| at the head of |q|. Writer side. */
+static ossl_unused ossl_inline void ossl_queue_add_head_rcu(OSSL_QUEUE *q,
+ OSSL_QNODE *n)
+{
+ OSSL_QNODE *head = q->head;
+
+ assert(!ossl_qnode_hashed(n));
+ n->next = head;
+ n->prev = &q->head;
+ /* |prev| is never followed by a reader */
+ if (head != NULL)
+ head->prev = &n->next;
+ ossl_rcu_assign_ptr(&q->head, &n);
+}
+
+/* The first node of |q|, for a reader. */
+static ossl_unused ossl_inline OSSL_QNODE *
+ossl_queue_head_rcu(const OSSL_QUEUE *q)
+{
+ return ossl_htable_rcu_load_(&((OSSL_QUEUE *)q)->head);
+}
+
+/* The node after |n|, for a reader. */
+static ossl_unused ossl_inline OSSL_QNODE *
+ossl_qnode_next_rcu(const OSSL_QNODE *n)
+{
+ return ossl_htable_rcu_load_(&((OSSL_QNODE *)n)->next);
+}
+
+#define DEFINE_HTABLE_RCU_OF(name, type) \
+ /* Only a fixed-size table defines this type; see above. */ \
+ typedef ossl_htable_##name##_fixed_size ossl_htable_##name##_rcu_check; \
+ static ossl_unused ossl_inline void \
+ ossl_htable_##name##_add_rcu(OSSL_HTABLE(name) *ht, type *el, \
+ uint64_t hash) \
+ { \
+ ossl_queue_add_head_rcu(ossl_htable_##name##_bucket(ht, hash), \
+ &el->ossl_queue_##name); \
+ ht->num++; \
+ } \
+ static ossl_unused ossl_inline type * \
+ ossl_htable_##name##_head_rcu(const OSSL_HTABLE(name) *ht, \
+ uint64_t hash) \
+ { \
+ return ossl_queue_##name##_entry( \
+ ossl_queue_head_rcu(ossl_htable_##name##_bucket(ht, hash))); \
+ } \
+ static ossl_unused ossl_inline type * \
+ ossl_htable_##name##_next_rcu(const type *el) \
+ { \
+ return ossl_queue_##name##_entry( \
+ ossl_qnode_next_rcu(&el->ossl_queue_##name)); \
+ } \
+ struct ossl_htable_rcu_dummy_st_##name
+
+#define OSSL_HTABLE_FOREACH_RCU(p, name, ht, hash) \
+ for ((p) = ossl_htable_##name##_head_rcu((ht), (hash)); (p) != NULL; \
+ (p) = ossl_htable_##name##_next_rcu(p))
+
+/*
+ * As OSSL_HTABLE_FIND, for a reader: leaves in |p| the first element of the
+ * bucket for |hash| for which |cond| holds, or NULL.
+ */
+#define OSSL_HTABLE_FIND_RCU(p, name, ht, hash, cond) \
+ do { \
+ const uint64_t ossl_htable_find_hash_ = (hash); \
+ \
+ OSSL_HTABLE_FOREACH_RCU (p, name, ht, ossl_htable_find_hash_) \
+ if (cond) \
+ break; \
+ } while (0)
+
+#endif /* OSSL_INTERNAL_HASHTABLE_H */
diff --git a/include/internal/queue.h b/include/internal/queue.h
new file mode 100644
index 0000000000..8f9c2546bb
--- /dev/null
+++ b/include/internal/queue.h
@@ -0,0 +1,299 @@
+/*
+ * Copyright 2026 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_QUEUE_H
+#define OSSL_INTERNAL_QUEUE_H
+#pragma once
+
+#include <stddef.h>
+#include <assert.h>
+#include <openssl/e_os2.h>
+
+#define OSSL_CONTAINER_OF(ptr, type, member) \
+ ((type *)((char *)(ptr) - offsetof(type, member)))
+
+#define OSSL_CONTAINER_OF_SAFE(ptr, type, member) \
+ ((ptr) == NULL ? NULL : OSSL_CONTAINER_OF(ptr, type, member))
+
+/*
+ * A node's |prev| does not point at the node before it but at the pointer that
+ * points at the node: the |next| of the node before it or, for the first node,
+ * the |head| of its queue.
+ *
+ * What that buys over a list whose nodes point at each other, such as
+ * OSSL_LIST (internal/list.h):
+ *
+ * - A head is one pointer, where OSSL_LIST has a head, a tail and a count.
+ * A table is an array of heads, most of them with no node or one, so it
+ * takes a third of the memory and, with 64-bit pointers, eight heads share
+ * a cache line.
+ * - A node is unlinked without its head: *n->prev = n->next is the same for
+ * the first node as for any other. Taking an element out of a table needs
+ * neither its key, nor its hash, nor the table; only the element.
+ * - |prev| is NULL exactly while the node is in no queue, so membership
+ * needs no flag of its own (ossl_qnode_hashed()).
+ * - An empty head is a NULL pointer, not a sentinel that points at itself as
+ * the head of a circular list is, so a zeroed or statically initialised
+ * table is empty and ready for use.
+ * - Walking forward follows |head| and |next| only, to a NULL: a node can be
+ * published to readers that hold no lock with a single store
+ * (DEFINE_HTABLE_RCU_OF of internal/hashtable.h).
+ *
+ * What it gives up: a queue has no tail and no count, and cannot be walked
+ * backwards from its end. A caller that needs the tail keeps it itself
+ * (ossl_queue_<name>_add_tail()). Where both ends, the order or the count
+ * matter and the heads are few, OSSL_LIST is the better fit.
+ *
+ * Since |prev| is the membership flag, a node must be clear before it is
+ * first used: zeroed along with the object that embeds it, or set up with
+ * ossl_qnode_init() or ossl_queue_<name>_init_elem(). Every add asserts that
+ * the node is in no queue, and ossl_qnode_hashed() and ossl_qnode_del_init()
+ * test the same thing; over uninitialised memory the answer is arbitrary.
+ * ossl_qnode_del() clears the node again.
+ */
+typedef struct ossl_qnode_st OSSL_QNODE;
+struct ossl_qnode_st {
+ OSSL_QNODE *next;
+ OSSL_QNODE **prev;
+};
+
+typedef struct ossl_queue_st {
+ OSSL_QNODE *head;
+} OSSL_QUEUE;
+
+#define OSSL_QUEUE_INIT { NULL }
+
+static ossl_inline void ossl_qnode_init(OSSL_QNODE *n)
+{
+ n->next = NULL;
+ n->prev = NULL;
+}
+
+static ossl_inline void ossl_queue_init(OSSL_QUEUE *a)
+{
+ a->head = NULL;
+}
+
+/* A node is "hashed" while it is linked into some queue. */
+static ossl_unused ossl_inline int ossl_qnode_hashed(const OSSL_QNODE *n)
+{
+ return n->prev != NULL;
+}
+
+static ossl_unused ossl_inline int ossl_qnode_unhashed(const OSSL_QNODE *n)
+{
+ return n->prev == NULL;
+}
+
+static ossl_unused ossl_inline int ossl_queue_empty(const OSSL_QUEUE *q)
+{
+ return q->head == NULL;
+}
+
+static ossl_unused ossl_inline OSSL_QNODE *ossl_queue_head(const OSSL_QUEUE *q)
+{
+ return q->head;
+}
+
+static ossl_unused ossl_inline OSSL_QNODE *ossl_qnode_next(const OSSL_QNODE *n)
+{
+ return n->next;
+}
+
+/*
+ * The node before |n| in |q|, or NULL when |n| is its head. |n->prev| points
+ * at the field that points at |n|: the head of |q| or the |next| of the node
+ * before it, which is how BSD's LIST_PREV finds it too.
+ */
+static ossl_unused ossl_inline OSSL_QNODE *ossl_qnode_prev(const OSSL_QUEUE *q,
+ const OSSL_QNODE *n)
+{
+ assert(ossl_qnode_hashed(n));
+ if ((const void *)n->prev == (const void *)&q->head)
+ return NULL;
+ return OSSL_CONTAINER_OF(n->prev, OSSL_QNODE, next);
+}
+
+static ossl_inline void ossl_queue_add_head(OSSL_QUEUE *q, OSSL_QNODE *n)
+{
+ OSSL_QNODE *head = q->head;
+
+ assert(!ossl_qnode_hashed(n));
+ n->next = head;
+ if (head != NULL)
+ head->prev = &n->next;
+ q->head = n;
+ n->prev = &q->head;
+}
+
+static ossl_inline void ossl_queue_add(OSSL_QUEUE *q, OSSL_QNODE *n)
+{
+ ossl_queue_add_head(q, n);
+}
+
+/* Insert |c| before |n|, which must already be in a queue. */
+static ossl_inline void ossl_qnode_add_before(OSSL_QNODE *c, OSSL_QNODE *n)
+{
+ assert(!ossl_qnode_hashed(c) && ossl_qnode_hashed(n));
+ c->prev = n->prev;
+ c->next = n;
+ n->prev = &c->next;
+ *(c->prev) = c;
+}
+
+/* Insert |c| after |p|, which must already be in a queue. */
+static ossl_inline void ossl_qnode_add_behind(OSSL_QNODE *c, OSSL_QNODE *p)
+{
+ assert(!ossl_qnode_hashed(c) && ossl_qnode_hashed(p));
+ c->next = p->next;
+ p->next = c;
+ c->prev = &p->next;
+ if (c->next != NULL)
+ c->next->prev = &c->next;
+}
+
+static ossl_inline void ossl_qnode_unlink(OSSL_QNODE *n)
+{
+ OSSL_QNODE *next = n->next, **prev = n->prev;
+
+ *prev = next;
+ if (next != NULL)
+ next->prev = prev;
+}
+
+/* Remove |n|, which must be in a queue, and reset it to the unhashed state. */
+static ossl_inline void ossl_qnode_del(OSSL_QNODE *n)
+{
+ assert(ossl_qnode_hashed(n));
+ ossl_qnode_unlink(n);
+ ossl_qnode_init(n);
+}
+
+/* Like ossl_qnode_del() but a no-op on a node that is not in a queue. */
+static ossl_inline void ossl_qnode_del_init(OSSL_QNODE *n)
+{
+ if (ossl_qnode_hashed(n))
+ ossl_qnode_del(n);
+}
+
+/* Move every node of |from| onto the (assumed empty) head |to|. */
+static ossl_unused ossl_inline void ossl_queue_move(OSSL_QUEUE *to,
+ OSSL_QUEUE *from)
+{
+ assert(ossl_queue_empty(to));
+ to->head = from->head;
+ if (to->head != NULL)
+ to->head->prev = &to->head;
+ from->head = NULL;
+}
+
+/* Define the field embedding an element in the queue |name|. */
+#define OSSL_QUEUE_MEMBER(name) OSSL_QNODE ossl_queue_##name
+
+#define DEFINE_QUEUE_OF(name, type) \
+ static ossl_unused ossl_inline type * \
+ ossl_queue_##name##_entry(OSSL_QNODE *n) \
+ { \
+ return OSSL_CONTAINER_OF_SAFE(n, type, ossl_queue_##name); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_queue_##name##_init_elem(type *e) \
+ { \
+ ossl_qnode_init(&e->ossl_queue_##name); \
+ } \
+ static ossl_unused ossl_inline int \
+ ossl_queue_##name##_hashed(const type *e) \
+ { \
+ return ossl_qnode_hashed(&e->ossl_queue_##name); \
+ } \
+ static ossl_unused ossl_inline type * \
+ ossl_queue_##name##_head(const OSSL_QUEUE *l) \
+ { \
+ return ossl_queue_##name##_entry(l->head); \
+ } \
+ static ossl_unused ossl_inline type * \
+ ossl_queue_##name##_next(const type *e) \
+ { \
+ return ossl_queue_##name##_entry(e->ossl_queue_##name.next); \
+ } \
+ static ossl_unused ossl_inline type * \
+ ossl_queue_##name##_prev(const OSSL_QUEUE *a, const type *e) \
+ { \
+ OSSL_QNODE *n = ossl_qnode_prev(a, &e->ossl_queue_##name); \
+ return ossl_queue_##name##_entry(n); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_queue_##name##_add(OSSL_QUEUE *l, type *e) \
+ { \
+ ossl_queue_add_head(l, &e->ossl_queue_##name); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_queue_##name##_add_before(type *e, type *next) \
+ { \
+ ossl_qnode_add_before(&e->ossl_queue_##name, \
+ &next->ossl_queue_##name); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_queue_##name##_add_behind(type *e, type *prev) \
+ { \
+ ossl_qnode_add_behind(&e->ossl_queue_##name, \
+ &prev->ossl_queue_##name); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_queue_##name##_del(type *e) \
+ { \
+ ossl_qnode_del(&e->ossl_queue_##name); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_queue_##name##_del_init(type *e) \
+ { \
+ ossl_qnode_del_init(&e->ossl_queue_##name); \
+ } \
+ /* \
+ * Append |e| to |l|, whose tail is |*tail| (NULL when empty), \
+ * and make it the tail. A queue has no tail of its own; this \
+ * and _del_keep_tail() keep one the caller holds right. \
+ */ \
+ static ossl_unused ossl_inline void \
+ ossl_queue_##name##_add_tail(OSSL_QUEUE *l, type **tail, \
+ type *e) \
+ { \
+ assert((*tail == NULL) == ossl_queue_empty(l)); \
+ if (*tail == NULL) \
+ ossl_queue_##name##_add(l, e); \
+ else \
+ ossl_queue_##name##_add_behind(e, *tail); \
+ *tail = e; \
+ } \
+ /* Remove |e|, moving |*tail| back if |e| was the tail. */ \
+ static ossl_unused ossl_inline void \
+ ossl_queue_##name##_del_keep_tail(const OSSL_QUEUE *l, \
+ type **tail, type *e) \
+ { \
+ if (e == *tail) \
+ *tail = ossl_queue_##name##_prev(l, e); \
+ ossl_queue_##name##_del(e); \
+ } \
+ struct ossl_queue_dummy_st_##name
+
+#define OSSL_QUEUE_WALK(it, q) \
+ for ((it) = (q)->head; (it) != NULL; (it) = (it)->next)
+
+#define OSSL_QUEUE_WALK_DELSAFE(it, t, q) \
+ for ((it) = (q)->head; (it) != NULL && (((t) = (it)->next), 1); (it) = (t))
+
+#define OSSL_QUEUE_FOREACH(p, name, l) \
+ for ((p) = ossl_queue_##name##_head(l); (p) != NULL; \
+ (p) = ossl_queue_##name##_next(p))
+
+#define OSSL_QUEUE_FOREACH_DELSAFE(p, pn, name, l) \
+ for ((p) = ossl_queue_##name##_head(l); \
+ (p) != NULL && (((pn) = ossl_queue_##name##_next(p)), 1); (p) = (pn))
+
+#endif /* OSSL_INTERNAL_QUEUE_H */
diff --git a/providers/fips-sources.checksums b/providers/fips-sources.checksums
index c7bd3a9e07..d7c563178b 100644
--- a/providers/fips-sources.checksums
+++ b/providers/fips-sources.checksums
@@ -247,7 +247,6 @@ f4f84cade98907fa9905334b6c3c046b430b12b1460edac0617d82ca763620ab crypto/ffc/ffc
56c52c6df6cd9282296f24b395e6a78deb35248e79a26186a75fc508262c47f7 crypto/ffc/ffc_params_generate.c
e9a500ddbe96cb5b302fd2db74fac0924a6ac45732df5ee1c09e82b19d06ccfd crypto/ffc/ffc_params_validate.c
f172c8c2112ee82716a7bc3a3e05d5cc26188c66b9d768ac1ff906845063d2cc crypto/hashtable/hashfunc.c
-21b74f0abd0f84390c90398bb2812565e183e0f35b2561ff20a52941ae67a86b crypto/hashtable/hashtable.c
95cbfbdd853f415d886928834f59d01a5fd08c71a154268c881dcbcc1131abc0 crypto/hmac/hmac.c
f1e386f65db354b5a0c4248d3df6ee690881aaa3fd4049fdc443f9eeb635f8e7 crypto/hmac/hmac_local.h
f9743f1646fbd8b61a2dd0422f42934912c1bfc95f6dcc38fa0a567e3e6b4e95 crypto/ia64cpuid.S
diff --git a/providers/fips.checksum b/providers/fips.checksum
index a3b78f828a..ad6a5b6990 100644
--- a/providers/fips.checksum
+++ b/providers/fips.checksum
@@ -1 +1 @@
-f1a0bd58b43534cf6d135e834d8765cf25ea1f527eafe030df9d10f3e0ef04ae providers/fips-sources.checksums
+a4ae6cedd00f29317ea6f09375f674467918ee924b59eabb081498a4bda8d44e providers/fips-sources.checksums
diff --git a/providers/fips.module.sources b/providers/fips.module.sources
index 948b639a9f..85921d8976 100644
--- a/providers/fips.module.sources
+++ b/providers/fips.module.sources
@@ -247,7 +247,6 @@ crypto/ffc/ffc_params.c
crypto/ffc/ffc_params_generate.c
crypto/ffc/ffc_params_validate.c
crypto/hashtable/hashfunc.c
-crypto/hashtable/hashtable.c
crypto/hmac/hmac.c
crypto/hmac/hmac_local.h
crypto/ia64cpuid.S
diff --git a/test/build.info b/test/build.info
index 134d87ea76..939783411e 100644
--- a/test/build.info
+++ b/test/build.info
@@ -82,7 +82,7 @@ IF[{- !$disabled{tests} -}]
nodefltctxtest evp_xof_test x509_load_cert_file_test bio_meth_test \
x509_acert_test x509_req_test strtoultest bio_pw_callback_test \
engine_stubs_test base64_simdutf_test base64_dec_avx2_test bio_eof_test \
- ech_test ossl_rbtree_test
+ ech_test ossl_rbtree_test queue_test htable_test
IF[{- !$disabled{'ech'} -}]
PROGRAMS{noinst}=ech_corrupt_test
@@ -1157,6 +1157,15 @@ IF[{- !$disabled{tests} -}]
INCLUDE[list_test]=../include ../apps/include
DEPEND[list_test]=libtestutil.a
+ SOURCE[queue_test]=queue_test.c
+ INCLUDE[queue_test]=../include ../apps/include
+ DEPEND[queue_test]=../libcrypto libtestutil.a
+
+ SOURCE[htable_test]=htable_test.c
+ INCLUDE[htable_test]=.. ../include ../apps/include
+ DEPEND[htable_test]=../libcrypto.a libtestutil.a
+ DEPEND[htable_test.o]=../crypto/objects/obj_dat.h
+
SOURCE[hmactest]=hmactest.c
INCLUDE[hmactest]=../include ../apps/include
DEPEND[hmactest]=../libcrypto.a libtestutil.a
@@ -1505,6 +1514,12 @@ ENDIF
DEPEND[timing_load_creds]=../libcrypto
ENDIF
+ # Times the namemap and the X509_STORE; not run by "make test"
+ PROGRAMS{noinst}=timing_namemap_x509store
+ SOURCE[timing_namemap_x509store]=timing_namemap_x509store.c
+ INCLUDE[timing_namemap_x509store]=.. ../include ../apps/include
+ DEPEND[timing_namemap_x509store]=../libcrypto.a
+
IF[{- !$disabled{'quic'} -}]
PROGRAMS{noinst}=quic_wire_test quic_ackm_test quic_record_test
PROGRAMS{noinst}=quic_fc_test quic_stream_test quic_cfq_test quic_txpim_test
diff --git a/test/htable_test.c b/test/htable_test.c
new file mode 100644
index 0000000000..668ff88535
--- /dev/null
+++ b/test/htable_test.c
@@ -0,0 +1,1543 @@
+/*
+ * Copyright 2026 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <stdio.h>
+#include <string.h>
+
+#include <openssl/asn1.h>
+#include <openssl/crypto.h>
+#include <openssl/err.h>
+#include <openssl/objects.h>
+#include <openssl/provider.h>
+#include <openssl/rand.h>
+#include <openssl/x509.h>
+#include <openssl/x509v3.h>
+
+#include "crypto/objects/obj_dat.h"
+#include "crypto/rand.h"
+#include "crypto/siphash.h"
+#include "crypto/x509.h"
+#include "internal/hashtable.h"
+#include "crypto/asn1/asn1_local.h"
+#include "internal/nelem.h"
+#include "testutil.h"
+
+/*
+ * Without threads, threadstest.h runs a "thread" to completion inside
+ * run_thread(), which the readers of test_rcu_threads cannot do: they wait
+ * for what the writer publishes after starting them.
+ */
+#if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG)
+#define HTABLE_TEST_THREADS
+#include "threadstest.h"
+#endif
+
+typedef struct entry_st {
+ uint64_t key;
+ int visits;
+ OSSL_QUEUE_MEMBER(ent);
+ OSSL_QUEUE_MEMBER(one);
+ OSSL_QUEUE_MEMBER(pub);
+ OSSL_HTABLE_MEMBER(dyn);
+ OSSL_HTABLE_MEMBER(cap);
+} ENTRY;
+
+#define ENT_BITS 4
+#define ENT_BUCKETS ((size_t)1 << ENT_BITS)
+DEFINE_QUEUE_OF(ent, ENTRY);
+DEFINE_HTABLE_OF(ent, ENTRY, ENT_BITS);
+
+/* A single-bucket table over the same elements, so every insertion collides */
+DEFINE_QUEUE_OF(one, ENTRY);
+DEFINE_HTABLE_OF(one, ENTRY, 0);
+
+static OSSL_HTABLE(ent) static_table = OSSL_HTABLE_INIT;
+
+/* A growable table: 4 buckets inline, up to 1024. */
+#define DYN_MIN_BITS 2
+#define DYN_MAX_BITS 10
+DEFINE_QUEUE_OF(dyn, ENTRY);
+DEFINE_HTABLE_DYN_OF(dyn, ENTRY, DYN_MIN_BITS, DYN_MAX_BITS);
+
+/* A growable table that stops at 8 buckets. */
+DEFINE_QUEUE_OF(cap, ENTRY);
+DEFINE_HTABLE_DYN_OF(cap, ENTRY, 1, 3);
+
+/* An insert-only table read without a lock; few buckets, long chains. */
+#define PUB_BITS 3
+DEFINE_QUEUE_OF(pub, ENTRY);
+DEFINE_HTABLE_OF(pub, ENTRY, PUB_BITS);
+DEFINE_HTABLE_RCU_OF(pub, ENTRY);
+
+static uint64_t key_hash(uint64_t key)
+{
+ return ossl_hash_mix64(key);
+}
+
+/* The number of non-empty buckets and the length of the longest chain. */
+static void chain_shape(const OSSL_QUEUE *buckets, size_t nbuckets,
+ size_t *used, size_t *max_chain)
+{
+ const OSSL_QNODE *n;
+ size_t i, len;
+
+ *used = 0;
+ *max_chain = 0;
+ for (i = 0; i < nbuckets; i++) {
+ len = 0;
+ OSSL_QUEUE_WALK (n, &buckets[i])
+ len++;
+ *used += len != 0;
+ if (len > *max_chain)
+ *max_chain = len;
+ }
+}
+
+static void init_entries(ENTRY *e, size_t n, uint64_t stride)
+{
+ size_t i;
+
+ for (i = 0; i < n; i++) {
+ e[i].key = (uint64_t)i * stride;
+ e[i].visits = 0;
+ ossl_queue_ent_init_elem(&e[i]);
+ ossl_queue_one_init_elem(&e[i]);
+ ossl_queue_dyn_init_elem(&e[i]);
+ ossl_queue_cap_init_elem(&e[i]);
+ }
+}
+
+static int check_empty(OSSL_HTABLE(ent) *ht)
+{
+ ENTRY *p;
+ size_t i;
+
+ if (!TEST_size_t_eq(ossl_htable_num(ht), 0)
+ || !TEST_true(ossl_htable_is_empty(ht))
+ || !TEST_size_t_eq(ossl_htable_num_buckets(ht), ENT_BUCKETS)
+ || !TEST_uint64_t_eq(ossl_htable_mask(ht), ENT_BUCKETS - 1)
+ || !TEST_ptr_eq(ossl_htable_bucket(ht, 0x123), &ht->buckets[3])
+ || !TEST_ptr_eq(ossl_htable_bucket(ht, UINT64_MAX),
+ &ht->buckets[ENT_BUCKETS - 1]))
+ return 0;
+ for (i = 0; i < ossl_htable_num_buckets(ht); i++)
+ if (!TEST_true(ossl_queue_empty(&ht->buckets[i])))
+ return 0;
+
+ /* A search of an empty table is a miss */
+ OSSL_HTABLE_FIND(p, ent, ht, 7, p->key == 7);
+ return TEST_ptr_null(p) && TEST_ptr_null(ossl_htable_ent_head(ht, 7));
+}
+
+/* A statically initialised table and a run-time initialised one agree. */
+static int test_init(void)
+{
+ OSSL_HTABLE(ent) table;
+
+ memset(&table, 0xff, sizeof(table));
+ ossl_htable_ent_init(&table);
+ return check_empty(&static_table) && check_empty(&table);
+}
+
+static void count_visit(ENTRY *e, void *arg)
+{
+ e->visits++;
+ (*(size_t *)arg)++;
+}
+
+static void del_visit(ENTRY *e, void *arg)
+{
+ ossl_htable_ent_del(arg, e);
+ e->visits++;
+}
+
+#define NENTRIES 64
+
+static int test_add_find_del(void)
+{
+ OSSL_HTABLE(ent) table;
+ ENTRY e[NENTRIES], *p;
+ size_t i, count = 0, used, max_chain;
+ uint64_t b;
+
+ ossl_htable_ent_init(&table);
+ init_entries(e, NENTRIES, 7919);
+
+ for (i = 0; i < NENTRIES; i++) {
+ ossl_htable_ent_add(&table, &e[i], key_hash(e[i].key));
+ if (!TEST_size_t_eq(ossl_htable_num(&table), i + 1)
+ || !TEST_true(ossl_queue_ent_hashed(&e[i])))
+ return 0;
+ }
+
+ chain_shape(table.buckets, ENT_BUCKETS, &used, &max_chain);
+ if (!TEST_false(ossl_htable_is_empty(&table))
+ || !TEST_size_t_le(used, ENT_BUCKETS)
+ || !TEST_size_t_ge(max_chain, NENTRIES / ENT_BUCKETS))
+ return 0;
+
+ /* Every element is found under its own key, and an unknown key is not */
+ for (i = 0; i < NENTRIES; i++) {
+ OSSL_HTABLE_FIND(p, ent, &table, key_hash(e[i].key), p->key == e[i].key);
+ if (!TEST_ptr_eq(p, &e[i]))
+ return 0;
+ }
+ OSSL_HTABLE_FIND(p, ent, &table, key_hash(1), p->key == 1);
+ if (!TEST_ptr_null(p))
+ return 0;
+
+ /* Each element sits in the bucket its hash selects, and nowhere else */
+ for (b = 0; b < ENT_BUCKETS; b++)
+ OSSL_HTABLE_FOREACH (p, ent, &table, b) {
+ if (!TEST_uint64_t_eq(key_hash(p->key) & ossl_htable_mask(&table), b))
+ return 0;
+ count++;
+ }
+ if (!TEST_size_t_eq(count, NENTRIES))
+ return 0;
+
+ /* doall visits every element exactly once */
+ count = 0;
+ ossl_htable_ent_doall_arg(&table, count_visit, &count);
+ if (!TEST_size_t_eq(count, NENTRIES))
+ return 0;
+ for (i = 0; i < NENTRIES; i++)
+ if (!TEST_int_eq(e[i].visits, 1))
+ return 0;
+
+ /* Deleting half leaves the other half findable, and they can come back */
+ for (i = 0; i < NENTRIES; i += 2)
+ ossl_htable_ent_del(&table, &e[i]);
+ if (!TEST_size_t_eq(ossl_htable_num(&table), NENTRIES / 2))
+ return 0;
+ for (i = 0; i < NENTRIES; i++) {
+ OSSL_HTABLE_FIND(p, ent, &table, key_hash(e[i].key), p->key == e[i].key);
+ if (i % 2 == 0) {
+ if (!TEST_false(ossl_queue_ent_hashed(&e[i])) || !TEST_ptr_null(p))
+ return 0;
+ } else if (!TEST_ptr_eq(p, &e[i])) {
+ return 0;
+ }
+ }
+ for (i = 0; i < NENTRIES; i += 2)
+ ossl_htable_ent_add(&table, &e[i], key_hash(e[i].key));
+ if (!TEST_size_t_eq(ossl_htable_num(&table), NENTRIES))
+ return 0;
+ for (i = 0; i < NENTRIES; i++) {
+ OSSL_HTABLE_FIND(p, ent, &table, key_hash(e[i].key), p->key == e[i].key);
+ if (!TEST_ptr_eq(p, &e[i]))
+ return 0;
+ }
+
+ /* doall may remove the element it is handed */
+ ossl_htable_ent_doall_arg(&table, del_visit, &table);
+ if (!TEST_size_t_eq(ossl_htable_num(&table), 0)
+ || !TEST_true(ossl_htable_is_empty(&table)))
+ return 0;
+ for (i = 0; i < NENTRIES; i++)
+ if (!TEST_false(ossl_queue_ent_hashed(&e[i]))
+ || !TEST_int_eq(e[i].visits, 2))
+ return 0;
+ chain_shape(table.buckets, ENT_BUCKETS, &used, &max_chain);
+ return TEST_size_t_eq(used, 0) && TEST_size_t_eq(max_chain, 0);
+}
+
+/* With a single bucket every element shares one chain, most recent first. */
+static int test_single_bucket(void)
+{
+ OSSL_HTABLE(one) table;
+ ENTRY e[10], *p, *pn;
+ size_t i, count = 0, used, max_chain;
+
+ ossl_htable_one_init(&table);
+ init_entries(e, OSSL_NELEM(e), 1);
+ if (!TEST_size_t_eq(ossl_htable_num_buckets(&table), 1)
+ || !TEST_uint64_t_eq(ossl_htable_mask(&table), 0)
+ || !TEST_ptr_eq(ossl_htable_bucket(&table, UINT64_MAX),
+ &table.buckets[0]))
+ return 0;
+
+ for (i = 0; i < OSSL_NELEM(e); i++)
+ ossl_htable_one_add(&table, &e[i], key_hash(e[i].key));
+ OSSL_HTABLE_FOREACH (p, one, &table, 12345) {
+ if (!TEST_size_t_lt(count, OSSL_NELEM(e))
+ || !TEST_ptr_eq(p, &e[OSSL_NELEM(e) - 1 - count]))
+ return 0;
+ count++;
+ }
+ chain_shape(table.buckets, 1, &used, &max_chain);
+ if (!TEST_size_t_eq(count, OSSL_NELEM(e))
+ || !TEST_size_t_eq(used, 1)
+ || !TEST_size_t_eq(max_chain, OSSL_NELEM(e)))
+ return 0;
+
+ /*
+ * Whatever hash a search is given, it lands in the one bucket and walks
+ * the chain to its key.
+ */
+ for (i = 0; i < OSSL_NELEM(e); i++) {
+ OSSL_HTABLE_FIND(p, one, &table, (uint64_t)i * 977, p->key == e[i].key);
+ if (!TEST_ptr_eq(p, &e[i]))
+ return 0;
+ }
+
+ /* A deletion-safe bucket walk may remove every element */
+ OSSL_HTABLE_FOREACH_DELSAFE (p, pn, one, &table, 0)
+ ossl_htable_one_del(&table, p);
+ return TEST_size_t_eq(ossl_htable_num(&table), 0)
+ && TEST_true(ossl_htable_is_empty(&table))
+ && TEST_ptr_null(ossl_htable_one_head(&table, 0));
+}
+
+/* Recently-used-cache promotion moves an element to the head of a bucket. */
+static int test_ruc(void)
+{
+ OSSL_HTABLE(ent) table;
+ ENTRY e[3], *p;
+ size_t i;
+
+ ossl_htable_ent_init(&table);
+ init_entries(e, OSSL_NELEM(e), 1);
+ for (i = 0; i < OSSL_NELEM(e); i++)
+ ossl_htable_ent_add(&table, &e[i], 5);
+ if (!TEST_ptr_eq(ossl_htable_ent_head(&table, 5), &e[2]))
+ return 0;
+
+ /* Promoting the tail makes it the head and keeps the count */
+ ossl_htable_ent_ruc(&table, &e[0], 5);
+ if (!TEST_ptr_eq(ossl_htable_ent_head(&table, 5), &e[0])
+ || !TEST_ptr_eq(ossl_queue_ent_next(&e[0]), &e[2])
+ || !TEST_ptr_eq(ossl_queue_ent_next(&e[2]), &e[1])
+ || !TEST_ptr_null(ossl_queue_ent_next(&e[1]))
+ || !TEST_size_t_eq(ossl_htable_num(&table), 3))
+ return 0;
+
+ /* Promoting under another hash moves the element to that bucket */
+ ossl_htable_ent_ruc(&table, &e[1], 9);
+ OSSL_HTABLE_FIND(p, ent, &table, 9, p->key == e[1].key);
+ if (!TEST_ptr_eq(p, &e[1])
+ || !TEST_ptr_eq(ossl_htable_ent_head(&table, 9), &e[1])
+ || !TEST_ptr_null(ossl_queue_ent_next(&e[1]))
+ || !TEST_ptr_eq(ossl_htable_ent_head(&table, 5), &e[0])
+ || !TEST_ptr_eq(ossl_queue_ent_next(&e[0]), &e[2])
+ || !TEST_ptr_null(ossl_queue_ent_next(&e[2]))
+ || !TEST_size_t_eq(ossl_htable_num(&table), 3))
+ return 0;
+ OSSL_HTABLE_FIND(p, ent, &table, 5, p->key == e[1].key);
+ return TEST_ptr_null(p);
+}
+
+/* The hash helpers spread keys over the low bits that select a bucket. */
+static int test_hash_mixing(void)
+{
+ unsigned char used[1024];
+ size_t i, n = 0, m = 0;
+ int local = 0;
+
+ /* Zero is the finaliser's fixed point; everything else moves */
+ if (!TEST_uint64_t_eq(ossl_hash_mix64(0), 0)
+ || !TEST_uint64_t_ne(ossl_hash_mix64(1), 1)
+ || !TEST_uint64_t_ne(ossl_hash_mix64(1), ossl_hash_mix64(2))
+ || !TEST_uint64_t_eq(ossl_hash_ptr(&local),
+ ossl_hash_mix64((uint64_t)(uintptr_t)&local)))
+ return 0;
+
+ /* Mixed sequential keys spread like random ones: about 63% of buckets */
+ memset(used, 0, sizeof(used));
+ for (i = 0; i < OSSL_NELEM(used); i++)
+ used[ossl_hash_mix64(i) & (OSSL_NELEM(used) - 1)] = 1;
+ for (i = 0; i < OSSL_NELEM(used); i++)
+ n += used[i];
+
+ /* Keys with a stride of four passed through raw use a quarter of them */
+ memset(used, 0, sizeof(used));
+ for (i = 0; i < OSSL_NELEM(used); i++)
+ used[(i << 2) & (OSSL_NELEM(used) - 1)] = 1;
+ for (i = 0; i < OSSL_NELEM(used); i++)
+ m += used[i];
+
+ return TEST_size_t_ge(n, OSSL_NELEM(used) / 2)
+ && TEST_size_t_eq(m, OSSL_NELEM(used) / 4);
+}
+
+/*
+ * scan_ext_flags() on a keyed intrusive table.
+ *
+ * ossl_x509v3_cache_extensions() scans the extensions of a certificate once,
+ * in scan_ext_flags() (crypto/x509/v3_purp.c), for a repeated extension,
+ * the freshest CRL extension and unsupported critical ones. Extensions with
+ * a built-in NID are deduplicated through a bitset; every other OID, which
+ * the author of an untrusted certificate chooses freely, goes through a
+ * SipHash-keyed hash table that exists only for the scan. The library
+ * allocates an OPENSSL_LHASH and an array of entry wrappers for it.
+ *
+ * The function below is that scan with the same signature, the same flags
+ * and the same loop; only the else branch differs, where the LHASH, the
+ * wrapper array and the streaming SipHash give way to a keyed OSSL_HTABLE in
+ * the frame, a pool of intrusive entries beside it (a heap pool only for a
+ * certificate with more extensions than the pool holds) and the table's
+ * own hash. The tests drive it through real X509 objects and check every
+ * certificate against the library's scan via X509_get_extension_flags().
+ */
+typedef struct oid_entry_st {
+ const ASN1_OBJECT *obj;
+ OSSL_QUEUE_MEMBER(oid);
+} OID_ENTRY;
+
+#define OID_BITS 3 /* 8 buckets: fewer than the extensions, so chains form */
+#define OID_BUCKETS ((size_t)1 << OID_BITS)
+#define SCAN_EXT_POOL 32 /* entries kept in the frame */
+DEFINE_QUEUE_OF(oid, OID_ENTRY);
+DEFINE_HTABLE_KEYED_OF(oid, OID_ENTRY, OID_BITS);
+
+static void scan_ext_flags(const X509 *x509, uint32_t *flags)
+{
+ OSSL_HTABLE(oid) table;
+ OID_ENTRY pool[SCAN_EXT_POOL], *ents = NULL;
+ size_t num_entries = 0;
+ uint8_t ex_bitset[(NUM_NID + 7) / 8];
+ int count = X509_get_ext_count(x509);
+
+ memset(ex_bitset, 0, sizeof(ex_bitset));
+ /* A certificate MUST NOT include more than one instance of an extension. */
+ for (int i = 0; i < count; i++) {
+ const X509_EXTENSION *ex = X509_get_ext(x509, i);
+ const ASN1_OBJECT *a = X509_EXTENSION_get_object(ex);
+ int nid = OBJ_obj2nid(a);
+
+ /*
+ * Known NIDs within the build-time bitset limit are checked for
+ * duplicates in constant time. Unknown OIDs and dynamically registered
+ * NIDs that exceed the limit fall back to duplicate detection via a
+ * hash table.
+ */
+ if (nid > NID_undef && nid < NUM_NID) {
+ unsigned int ex_bit = nid;
+
+ if ((ex_bitset[ex_bit >> 3] & (1u << (ex_bit & 7))) != 0) {
+ *flags |= EXFLAG_DUPLICATE;
+ break;
+ }
+ ex_bitset[ex_bit >> 3] |= (1u << (ex_bit & 7));
+ } else {
+ OID_ENTRY *p;
+ uint64_t h;
+
+ if (a->length < 1) {
+ *flags |= EXFLAG_INVALID;
+ break;
+ }
+ /*
+ * Key the table and pick the entry pool the first time an
+ * attacker-controlled OID is seen. The key is drawn as the
+ * library draws its own, with ossl_rand_hash_salt(), which
+ * still succeeds in a library context without a usable RAND.
+ * The table never outlives this function. Fail closed with
+ * EXFLAG_INVALID when no key can be drawn or a heap pool cannot
+ * be allocated, as the library does when its table cannot be
+ * set up.
+ */
+ if (ents == NULL) {
+ OSSL_LIB_CTX *libctx = NULL;
+ unsigned char key[OSSL_HTABLE_KEY_SIZE];
+
+ ossl_x509_get0_libctx(x509, &libctx, NULL);
+ if (!ossl_rand_hash_salt(libctx, key, sizeof(key))) {
+ *flags |= EXFLAG_INVALID;
+ break;
+ }
+ ossl_htable_oid_init(&table, key);
+ if (count <= SCAN_EXT_POOL) {
+ ents = pool;
+ } else if ((ents = OPENSSL_malloc_array(count, sizeof(*ents)))
+ == NULL) {
+ *flags |= EXFLAG_INVALID;
+ break;
+ }
+ }
+ h = ossl_htable_oid_hash(&table, a->data, a->length);
+ OSSL_HTABLE_FIND(p, oid, &table, h, OBJ_cmp(p->obj, a) == 0);
+ if (p != NULL) {
+ *flags |= EXFLAG_DUPLICATE;
+ break;
+ }
+ ents[num_entries].obj = a;
+ ossl_queue_oid_init_elem(&ents[num_entries]);
+ ossl_htable_oid_add(&table, &ents[num_entries], h);
+ num_entries++;
+ }
+ if (nid == NID_freshest_crl)
+ *flags |= EXFLAG_FRESHEST;
+ if (!X509_EXTENSION_get_critical(ex))
+ continue;
+ if (!X509_supported_extension(ex)) {
+ *flags |= EXFLAG_CRITICAL;
+ break;
+ }
+ }
+ if (ents != pool)
+ OPENSSL_free(ents);
+}
+
+/* The flags the scan sets, as opposed to the rest of the cache function */
+#define SCAN_FLAGS \
+ (EXFLAG_DUPLICATE | EXFLAG_INVALID | EXFLAG_CRITICAL | EXFLAG_FRESHEST)
+
+/*
+ * The table's hash is SipHash-2-4 under the key it was initialised with: it
+ * reproduces the reference vector and agrees with libcrypto's streaming
+ * SipHash under a drawn key.
+ */
+static int test_keyed_hash(void)
+{
+ /* SipHash-2-4 reference vector: key 00..0f, message 00..0e */
+ static const uint64_t ref = 0xa129ca6149be45e5ULL;
+ OSSL_HTABLE(oid) t, u;
+ SIPHASH sip = { 0 };
+ unsigned char msg[64], key[OSSL_HTABLE_KEY_SIZE];
+ unsigned char digest[SIPHASH_MIN_DIGEST_SIZE], le[8];
+ uint64_t v, x = 0x0123456789abcdefULL;
+ size_t i, j;
+
+ for (i = 0; i < sizeof(msg); i++)
+ msg[i] = (unsigned char)i;
+
+ /* init takes the caller's key and leaves an empty table */
+ memset(&t, 0xff, sizeof(t));
+ ossl_htable_oid_init(&t, msg);
+ for (i = 0; i < OID_BUCKETS; i++)
+ if (!TEST_true(ossl_queue_empty(&t.buckets[i])))
+ return 0;
+ if (!TEST_true(ossl_htable_is_empty(&t))
+ || !TEST_mem_eq(t.key, sizeof(t.key), msg, OSSL_HTABLE_KEY_SIZE)
+ || !TEST_uint64_t_eq(ossl_htable_oid_hash(&t, msg, 15), ref))
+ return 0;
+
+ if (!TEST_true(ossl_rand_hash_salt(NULL, key, sizeof(key))))
+ return 0;
+ ossl_htable_oid_init(&u, key);
+
+ /* Every length against SipHash_*() with an 8-byte hash size, u's key */
+ for (i = 0; i <= sizeof(msg); i++) {
+ if (!TEST_true(SipHash_set_hash_size(&sip, sizeof(digest)))
+ || !TEST_true(SipHash_Init(&sip, u.key, 0, 0)))
+ return 0;
+ SipHash_Update(&sip, msg, i);
+ if (!TEST_true(SipHash_Final(&sip, digest, sizeof(digest))))
+ return 0;
+ /* The digest is the hash value in little-endian byte order */
+ for (v = 0, j = 0; j < sizeof(digest); j++)
+ v |= (uint64_t)digest[j] << (8 * j);
+ if (!TEST_uint64_t_eq(ossl_htable_oid_hash(&u, msg, i), v))
+ return 0;
+ }
+
+ /* The integer form hashes the little-endian bytes */
+ for (i = 0; i < sizeof(le); i++)
+ le[i] = (unsigned char)(x >> (8 * i));
+ return TEST_uint64_t_eq(ossl_htable_oid_hash_u64(&u, x),
+ ossl_htable_oid_hash(&u, le, sizeof(le)))
+ && TEST_uint64_t_ne(ossl_htable_oid_hash_u64(&u, x),
+ ossl_htable_oid_hash_u64(&t, x));
+}
+
+/* ---- certificates for the scan ------------------------------------------ */
+
+static X509 *new_cert(void)
+{
+ X509 *x = X509_new();
+
+ if (!TEST_ptr(x))
+ return NULL;
+ if (!TEST_true(X509_set_version(x, X509_VERSION_3))) {
+ X509_free(x);
+ return NULL;
+ }
+ return x;
+}
+
+/* A built-in extension with a well-formed value the cache can parse */
+static int add_known(X509 *x, int nid, const char *value)
+{
+ X509_EXTENSION *ex = X509V3_EXT_nconf_nid(NULL, NULL, nid, value);
+ int ok;
+
+ if (!TEST_ptr(ex))
+ return 0;
+ ok = TEST_true(X509_add_ext(x, ex, -1));
+ X509_EXTENSION_free(ex);
+ return ok;
+}
+
+/* An extension of any OID with an opaque value (DER NULL) */
+static int add_raw(X509 *x, const ASN1_OBJECT *obj, int critical)
+{
+ static const unsigned char der_null[] = { 0x05, 0x00 };
+ ASN1_OCTET_STRING *data = ASN1_OCTET_STRING_new();
+ X509_EXTENSION *ex = NULL;
+ int ok = 0;
+
+ if (!TEST_ptr(data)
+ || !TEST_true(ASN1_OCTET_STRING_set(data, der_null, sizeof(der_null)))
+ || !TEST_ptr(ex = X509_EXTENSION_create_by_OBJ(NULL, obj, critical, data)))
+ goto end;
+ ok = TEST_true(X509_add_ext(x, ex, -1));
+end:
+ X509_EXTENSION_free(ex);
+ ASN1_OCTET_STRING_free(data);
+ return ok;
+}
+
+/* An unknown (NID_undef) extension under a private enterprise arc */
+static int add_unknown(X509 *x, unsigned int n, int critical)
+{
+ char txt[64];
+ ASN1_OBJECT *obj;
+ int ok = 0;
+
+ snprintf(txt, sizeof(txt), "1.3.6.1.4.1.99999.%u", n);
+ if (!TEST_ptr(obj = OBJ_txt2obj(txt, 1)))
+ return 0;
+ if (TEST_int_eq(OBJ_obj2nid(obj), NID_undef))
+ ok = add_raw(x, obj, critical);
+ ASN1_OBJECT_free(obj);
+ return ok;
+}
+
+/* Four standard extensions, two of them critical, as most certificates have */
+static int add_typical(X509 *x)
+{
+ return add_known(x, NID_basic_constraints, "critical,CA:TRUE")
+ && add_known(x, NID_key_usage, "critical,keyCertSign,cRLSign")
+ && add_known(x, NID_ext_key_usage, "serverAuth")
+ && add_known(x, NID_subject_alt_name, "DNS:example.com");
+}
+
+/*
+ * Run the scan on |x| and check it sets exactly |expect|; then run the
+ * library's cache on the same certificate and check its scan-owned flags
+ * agree, EXFLAG_INVALID excepted where the cache sets it for a reason the
+ * scan does not see (a repeated built-in extension fails X509_get_ext_d2i()).
+ * The cache is computed once per certificate and never invalidated, so a
+ * certificate goes through here once.
+ */
+static int check_scan(X509 *x, uint32_t expect)
+{
+ uint32_t flags = 0, lib, mask = SCAN_FLAGS;
+
+ scan_ext_flags(x, &flags);
+ if (!TEST_uint_eq(flags, expect))
+ return 0;
+ lib = X509_get_extension_flags(x);
+ ERR_clear_error();
+ if ((expect & EXFLAG_DUPLICATE) != 0)
+ mask &= ~EXFLAG_INVALID;
+ return TEST_uint_eq(lib & mask, expect & mask);
+}
+
+/* Build a fresh certificate with |build|(x, variant) and check its scan. */
+static int check_built(int (*build)(X509 *x, int variant), int variant,
+ uint32_t expect)
+{
+ X509 *x = new_cert();
+ int ret = 0;
+
+ if (x != NULL && build(x, variant) && check_scan(x, expect))
+ ret = 1;
+ X509_free(x);
+ return ret;
+}
+
+/* ---- the scan as an API ---------------------------------------------- */
+
+/* A common certificate sets nothing; the freshest CRL extension is flagged. */
+static int build_common(X509 *x, int freshest)
+{
+ return add_typical(x)
+ && add_raw(x, OBJ_nid2obj(NID_certificate_policies), 0)
+ && add_raw(x, OBJ_nid2obj(NID_info_access), 0)
+ && (!freshest || add_raw(x, OBJ_nid2obj(NID_freshest_crl), 0));
+}
+
+static int test_scan_typical(void)
+{
+ return check_built(build_common, 0, 0)
+ && check_built(build_common, 1, EXFLAG_FRESHEST);
+}
+
+/* A repeated built-in extension is caught by the bitset. */
+static int build_duplicate_known(X509 *x, int variant)
+{
+ return add_typical(x)
+ && add_unknown(x, 1, 0)
+ && add_known(x, NID_basic_constraints, "CA:FALSE");
+}
+
+static int test_scan_duplicate_known(void)
+{
+ return check_built(build_duplicate_known, 0, EXFLAG_DUPLICATE);
+}
+
+/*
+ * Private extensions go through the table: fewer than the table has
+ * buckets, exactly the frame pool, and twice that, so the chains and the
+ * heap pool are both exercised. Distinct OIDs set nothing; a repeat of the
+ * first as the last extension is a duplicate.
+ */
+static const size_t unknown_counts[] = {
+ OID_BUCKETS - 1, SCAN_EXT_POOL, 2 * SCAN_EXT_POOL
+};
+
+static int build_unknowns(X509 *x, int variant)
+{
+ size_t i, n = unknown_counts[variant >> 1];
+
+ for (i = 0; i < n; i++)
+ if (!add_unknown(x, (unsigned int)i, 0))
+ return 0;
+ return (variant & 1) == 0 || add_unknown(x, 0, 0);
+}
+
+static int test_scan_unknown(int idx)
+{
+ TEST_info("%zu private extensions", unknown_counts[idx]);
+ return check_built(build_unknowns, idx << 1, 0)
+ && check_built(build_unknowns, (idx << 1) | 1, EXFLAG_DUPLICATE);
+}
+
+/* A repeated private extension among built-in ones. */
+static int build_mixed(X509 *x, int repeat)
+{
+ return add_known(x, NID_basic_constraints, "critical,CA:TRUE")
+ && add_unknown(x, 7, 0)
+ && add_known(x, NID_key_usage, "critical,keyCertSign")
+ && add_unknown(x, 8, 0)
+ && add_known(x, NID_subject_alt_name, "DNS:example.com")
+ && (!repeat || add_unknown(x, 7, 0));
+}
+
+static int test_scan_duplicate_unknown(void)
+{
+ return check_built(build_mixed, 0, 0)
+ && check_built(build_mixed, 1, EXFLAG_DUPLICATE);
+}
+
+/*
+ * A library context without a usable RAND, here one with only the null
+ * provider, still yields a key for the table. The scan checks the private
+ * extensions of such a context's certificates as it does anywhere else, and
+ * as the library's scan does, instead of declaring them invalid.
+ */
+static int test_scan_no_rand(int repeat)
+{
+ OSSL_LIB_CTX *libctx = NULL;
+ OSSL_PROVIDER *nullprov = NULL;
+ X509 *x = NULL;
+ unsigned char buf[16];
+ int ret = 0;
+
+ /* Loading the null provider stops the default one from auto-loading */
+ if (!TEST_ptr(libctx = OSSL_LIB_CTX_new())
+ || !TEST_ptr(nullprov = OSSL_PROVIDER_load(libctx, "null"))
+ || !TEST_int_le(RAND_bytes_ex(libctx, buf, sizeof(buf), 0), 0))
+ goto end;
+ ERR_clear_error();
+ if (!TEST_ptr(x = X509_new_ex(libctx, NULL))
+ || !TEST_true(X509_set_version(x, X509_VERSION_3))
+ || !build_mixed(x, repeat)
+ || !check_scan(x, repeat ? EXFLAG_DUPLICATE : 0))
+ goto end;
+ ret = 1;
+end:
+ X509_free(x);
+ OSSL_PROVIDER_unload(nullprov);
+ OSSL_LIB_CTX_free(libctx);
+ return ret;
+}
+
+/*
+ * OIDs whose encodings are prefixes of one another are distinct extensions,
+ * and OBJ_cmp() alone tells them apart when they share a chain.
+ */
+static int build_prefixes(X509 *x, int variant)
+{
+ static const char *const txt[] = {
+ "1.3.6.1.4.1.99999",
+ "1.3.6.1.4.1.99999.1",
+ "1.3.6.1.4.1.99999.1.1",
+ "1.3.6.1.4.1.99999.1.2",
+ "1.3.6.1.4.1.99999.1.1.1",
+ };
+ ASN1_OBJECT *obj;
+ size_t i;
+ int ok;
+
+ for (i = 0; i < OSSL_NELEM(txt); i++) {
+ if (!TEST_ptr(obj = OBJ_txt2obj(txt[i], 1)))
+ return 0;
+ ok = TEST_int_eq(OBJ_obj2nid(obj), NID_undef) && add_raw(x, obj, 0);
+ ASN1_OBJECT_free(obj);
+ if (!ok)
+ return 0;
+ }
+ return 1;
+}
+
+static int test_scan_prefix_oids(void)
+{
+ return check_built(build_prefixes, 0, 0);
+}
+
+/*
+ * An unsupported critical extension stops the scan: a duplicate behind it
+ * is not reported, while a supported critical one (the two in
+ * add_typical()) is passed over. The other way round the duplicate wins.
+ */
+static int build_critical(X509 *x, int dup_first)
+{
+ if (dup_first)
+ return add_unknown(x, 3, 0)
+ && add_unknown(x, 3, 0)
+ && add_unknown(x, 4, 1);
+ return add_typical(x)
+ && add_unknown(x, 3, 1)
+ && add_unknown(x, 3, 0);
+}
+
+static int test_scan_critical(void)
+{
+ return check_built(build_critical, 0, EXFLAG_CRITICAL)
+ && check_built(build_critical, 1, EXFLAG_DUPLICATE);
+}
+
+/*
+ * A NID registered at run time lies beyond the bitset and is deduplicated
+ * through the table by encoding, like an unknown OID.
+ */
+static const char dynamic_oid[] = "1.3.6.1.4.1.99998.1";
+
+static int build_dynamic(X509 *x, int repeat)
+{
+ ASN1_OBJECT *dyn = OBJ_txt2obj(dynamic_oid, 1); /* the registered object */
+
+ return TEST_ptr(dyn)
+ && TEST_int_ge(OBJ_obj2nid(dyn), NUM_NID)
+ && add_typical(x)
+ && add_raw(x, dyn, 0)
+ && add_unknown(x, 5, 0)
+ && (!repeat || add_raw(x, dyn, 0));
+}
+
+static int test_scan_dynamic_nid(void)
+{
+ int nid;
+
+ if (!TEST_int_ne(nid = OBJ_create(dynamic_oid, "htableTestExt",
+ "htable test extension"),
+ NID_undef)
+ || !TEST_int_ge(nid, NUM_NID))
+ return 0;
+ return check_built(build_dynamic, 0, 0)
+ && check_built(build_dynamic, 1, EXFLAG_DUPLICATE);
+}
+
+/*
+ * A zero-length OID is invalid and stops the scan where it stands. Such an
+ * extension cannot be added through the API (X509_add_ext() copies the
+ * extension by encoding it, and an empty OBJECT IDENTIFIER does not encode),
+ * so it is pushed onto the certificate's extension stack directly.
+ */
+static int build_zero_length(X509 *x, int variant)
+{
+ static const unsigned char der_null[] = { 0x05, 0x00 };
+ ASN1_OBJECT *empty = NULL;
+ ASN1_OCTET_STRING *data = NULL;
+ X509_EXTENSION *ex = NULL;
+ int ok = 0;
+
+ if (!TEST_ptr(empty = ossl_asn1_object_new())
+ || !TEST_size_t_eq(OBJ_length(empty), 0)
+ || !TEST_ptr(data = ASN1_OCTET_STRING_new())
+ || !TEST_true(ASN1_OCTET_STRING_set(data, der_null, sizeof(der_null)))
+ || !add_unknown(x, 1, 0)
+ || !TEST_ptr(ex = X509_EXTENSION_create_by_OBJ(NULL, empty, 0, data))
+ || !TEST_true(sk_X509_EXTENSION_push(x->cert_info.extensions, ex)))
+ goto end;
+ ex = NULL; /* owned by the certificate now */
+ ok = add_unknown(x, 1, 0) /* a duplicate the scan never reaches */
+ && TEST_size_t_eq(
+ OBJ_length(X509_EXTENSION_get_object(X509_get_ext(x, 1))), 0);
+end:
+ X509_EXTENSION_free(ex);
+ ASN1_OCTET_STRING_free(data);
+ ASN1_OBJECT_free(empty);
+ return ok;
+}
+
+static int test_scan_zero_length_oid(void)
+{
+ return check_built(build_zero_length, 0, EXFLAG_INVALID);
+}
+
+/*
+ * Hash flooding. An attacker who knows the key can pick OIDs that all share
+ * a bucket; here the "known" key is all zeroes and the OIDs were chosen to
+ * collide under it. On a table given that key every one of them lands in
+ * one chain. On a table given a drawn key they spread like any other input,
+ * and a certificate carrying them scans the same either way.
+ */
+#define FLOOD_OIDS 48
+
+static ASN1_OBJECT *flood_oids[FLOOD_OIDS];
+
+static int build_flood(X509 *x, int repeat)
+{
+ size_t i;
+
+ for (i = 0; i < FLOOD_OIDS; i++)
+ if (!add_raw(x, flood_oids[i], 0))
+ return 0;
+ return !repeat || add_raw(x, flood_oids[0], 0);
+}
+
+static size_t table_max_chain(const OSSL_HTABLE(oid) *t, size_t *used)
+{
+ size_t max_chain;
+
+ chain_shape(t->buckets, OID_BUCKETS, used, &max_chain);
+ return max_chain;
+}
+
+static int test_scan_flood(void)
+{
+ static const unsigned char zero_key[OSSL_HTABLE_KEY_SIZE] = { 0 };
+ OSSL_HTABLE(oid) zero, salted;
+ OID_ENTRY ents[FLOOD_OIDS];
+ unsigned char key[OSSL_HTABLE_KEY_SIZE];
+ size_t i, n = 0, used;
+ unsigned int cand;
+ int ret = 0;
+
+ memset(flood_oids, 0, sizeof(flood_oids));
+ if (!TEST_true(ossl_rand_hash_salt(NULL, key, sizeof(key))))
+ goto end;
+ ossl_htable_oid_init(&zero, zero_key);
+ ossl_htable_oid_init(&salted, key);
+
+ /* Keep the candidates that hash to bucket 0 under the all-zero key */
+ for (cand = 0; n < FLOOD_OIDS && cand < 100000; cand++) {
+ char txt[64];
+ ASN1_OBJECT *o;
+
+ snprintf(txt, sizeof(txt), "1.3.6.1.4.1.99999.%u", cand);
+ if (!TEST_ptr(o = OBJ_txt2obj(txt, 1)))
+ goto end;
+ if ((ossl_htable_oid_hash(&zero, OBJ_get0_data(o), OBJ_length(o))
+ & ossl_htable_mask(&zero))
+ == 0)
+ flood_oids[n++] = o;
+ else
+ ASN1_OBJECT_free(o);
+ }
+ if (!TEST_size_t_eq(n, FLOOD_OIDS))
+ goto end;
+
+ /* Unsalted: one chain holding every OID */
+ for (i = 0; i < n; i++) {
+ ents[i].obj = flood_oids[i];
+ ossl_queue_oid_init_elem(&ents[i]);
+ ossl_htable_oid_add(&zero, &ents[i],
+ ossl_htable_oid_hash(&zero, OBJ_get0_data(flood_oids[i]),
+ OBJ_length(flood_oids[i])));
+ }
+ if (!TEST_size_t_eq(table_max_chain(&zero, &used), FLOOD_OIDS)
+ || !TEST_size_t_eq(used, 1))
+ goto end;
+
+ /*
+ * Salted: the chosen collisions do not carry over. 48 OIDs in 8
+ * buckets: the longest chain is 6 on average and reaching even half of
+ * them has odds below 1 in 10^12.
+ */
+ for (i = 0; i < n; i++) {
+ ossl_htable_oid_del(&zero, &ents[i]);
+ ossl_htable_oid_add(&salted, &ents[i],
+ ossl_htable_oid_hash(&salted, OBJ_get0_data(flood_oids[i]),
+ OBJ_length(flood_oids[i])));
+ }
+ if (!TEST_size_t_lt(table_max_chain(&salted, &used), FLOOD_OIDS / 2)
+ || !TEST_size_t_gt(used, 1)
+ || !TEST_true(ossl_htable_is_empty(&zero)))
+ goto end;
+
+ /* The scan of a certificate carrying the flood is unaffected by it */
+ if (!check_built(build_flood, 0, 0)
+ || !check_built(build_flood, 1, EXFLAG_DUPLICATE))
+ goto end;
+
+ ret = 1;
+end:
+ for (i = 0; i < OSSL_NELEM(flood_oids); i++)
+ ASN1_OBJECT_free(flood_oids[i]);
+ return ret;
+}
+
+/* Growable tables */
+
+/* The bucket count a growable table has after holding at most |n| entries. */
+static size_t dyn_expected_buckets(size_t n, unsigned int min_bits,
+ unsigned int max_bits)
+{
+ size_t nb = (size_t)1 << min_bits;
+
+ while (nb < n && nb < ((size_t)1 << max_bits))
+ nb <<= 1;
+ return nb;
+}
+
+#define DYN_N 1000
+
+static int test_dyn_grow(void)
+{
+ OSSL_HTABLE(dyn) table;
+ ENTRY *e = NULL, *p;
+ size_t i, used, max_chain;
+ int ret = 0;
+
+ ossl_htable_dyn_init(&table);
+ if (!TEST_ptr_eq(table.dyn_buckets, table.inline_buckets)
+ || !TEST_size_t_eq(ossl_htable_dyn_num_buckets(&table),
+ (size_t)1 << DYN_MIN_BITS)
+ || !TEST_true(ossl_htable_is_empty(&table))
+ || !TEST_ptr(e = OPENSSL_malloc(DYN_N * sizeof(*e))))
+ goto end;
+ init_entries(e, DYN_N, 7);
+
+ /* The buckets double as soon as the entries outnumber them */
+ for (i = 0; i < DYN_N; i++) {
+ ossl_htable_dyn_add(&table, &e[i], key_hash(e[i].key));
+ if (!TEST_size_t_eq(ossl_htable_num(&table), i + 1)
+ || !TEST_size_t_eq(ossl_htable_dyn_num_buckets(&table),
+ dyn_expected_buckets(i + 1, DYN_MIN_BITS, DYN_MAX_BITS))
+ || !TEST_uint64_t_eq(ossl_htable_dyn_hash_of(&e[i]),
+ key_hash(e[i].key)))
+ goto end;
+ }
+ if (!TEST_ptr_ne(table.dyn_buckets, table.inline_buckets))
+ goto end;
+
+ /* Growing re-linked every entry under the hash it was added with */
+ for (i = 0; i < DYN_N; i++) {
+ OSSL_HTABLE_FIND(p, dyn, &table, key_hash(e[i].key), p->key == e[i].key);
+ if (!TEST_ptr_eq(p, &e[i]))
+ goto end;
+ }
+ chain_shape(table.dyn_buckets, ossl_htable_dyn_num_buckets(&table), &used,
+ &max_chain);
+ if (!TEST_size_t_le(max_chain, 8))
+ goto end;
+
+ /* Deleting never shrinks the buckets */
+ for (i = 0; i < DYN_N; i += 2)
+ ossl_htable_dyn_del(&table, &e[i]);
+ if (!TEST_size_t_eq(ossl_htable_num(&table), DYN_N / 2)
+ || !TEST_size_t_eq(ossl_htable_dyn_num_buckets(&table),
+ dyn_expected_buckets(DYN_N, DYN_MIN_BITS, DYN_MAX_BITS)))
+ goto end;
+ for (i = 0; i < DYN_N; i++) {
+ OSSL_HTABLE_FIND(p, dyn, &table, key_hash(e[i].key), p->key == e[i].key);
+ if (!TEST_ptr_eq(p, i % 2 == 0 ? NULL : &e[i]))
+ goto end;
+ }
+
+ /* Cleanup gives back the grown buckets and leaves the table as new */
+ ossl_htable_dyn_cleanup(&table);
+ ret = TEST_ptr_eq(table.dyn_buckets, table.inline_buckets)
+ && TEST_true(ossl_htable_is_empty(&table))
+ && TEST_size_t_eq(ossl_htable_dyn_num_buckets(&table),
+ (size_t)1 << DYN_MIN_BITS);
+end:
+ ossl_htable_dyn_cleanup(&table);
+ OPENSSL_free(e);
+ return ret;
+}
+
+/* Past max_bits the table stops growing and its chains lengthen instead. */
+static int test_dyn_max_bits(void)
+{
+ OSSL_HTABLE(cap) table;
+ ENTRY e[64], *p;
+ size_t i;
+ int ret = 0;
+
+ ossl_htable_cap_init(&table);
+ init_entries(e, OSSL_NELEM(e), 1);
+ for (i = 0; i < OSSL_NELEM(e); i++)
+ ossl_htable_cap_add(&table, &e[i], key_hash(e[i].key));
+ if (!TEST_size_t_eq(ossl_htable_cap_num_buckets(&table), 8)
+ || !TEST_size_t_eq(ossl_htable_num(&table), OSSL_NELEM(e))
+ || !TEST_true(ossl_htable_cap_reserve(&table, 1000))
+ || !TEST_size_t_eq(ossl_htable_cap_num_buckets(&table), 8))
+ goto end;
+ for (i = 0; i < OSSL_NELEM(e); i++) {
+ OSSL_HTABLE_FIND(p, cap, &table, key_hash(e[i].key), p->key == e[i].key);
+ if (!TEST_ptr_eq(p, &e[i]))
+ goto end;
+ }
+ ret = 1;
+end:
+ ossl_htable_cap_cleanup(&table);
+ return ret;
+}
+
+/*
+ * In a growable table FIND compares the stored hash before evaluating the
+ * caller's condition; in a static table every element of the bucket reaches
+ * the condition.
+ */
+static int cond_calls;
+
+static int counted_eq(const ENTRY *p, uint64_t key)
+{
+ cond_calls++;
+ return p->key == key;
+}
+
+static int test_dyn_hash_compare(void)
+{
+ OSSL_HTABLE(dyn) dyn;
+ OSSL_HTABLE(ent) ent;
+ ENTRY e[4], *p;
+ size_t i;
+ int ret = 0;
+
+ ossl_htable_dyn_init(&dyn);
+ ossl_htable_ent_init(&ent);
+ init_entries(e, OSSL_NELEM(e), 1);
+ /* Four hashes that share bucket 1 in either table, all distinct */
+ for (i = 0; i < OSSL_NELEM(e); i++) {
+ ossl_htable_dyn_add(&dyn, &e[i], 1 + (uint64_t)i * 1024);
+ ossl_htable_ent_add(&ent, &e[i], 1 + (uint64_t)i * 1024);
+ }
+ if (!TEST_size_t_eq(ossl_htable_dyn_num_buckets(&dyn), 4)
+ || !TEST_ptr_eq(ossl_htable_dyn_head(&dyn, 1), &e[3]))
+ goto end;
+
+ /* e[0] is the tail of its chain: three hash mismatches, one compare */
+ cond_calls = 0;
+ OSSL_HTABLE_FIND(p, dyn, &dyn, 1, counted_eq(p, e[0].key));
+ if (!TEST_ptr_eq(p, &e[0]) || !TEST_int_eq(cond_calls, 1))
+ goto end;
+ cond_calls = 0;
+ OSSL_HTABLE_FIND(p, dyn, &dyn, 1 + 4096, counted_eq(p, e[0].key));
+ if (!TEST_ptr_null(p) || !TEST_int_eq(cond_calls, 0))
+ goto end;
+
+ /* A matching hash with a different key still misses */
+ cond_calls = 0;
+ OSSL_HTABLE_FIND(p, dyn, &dyn, 1 + 1024, counted_eq(p, e[0].key));
+ if (!TEST_ptr_null(p) || !TEST_int_eq(cond_calls, 1))
+ goto end;
+
+ cond_calls = 0;
+ OSSL_HTABLE_FIND(p, ent, &ent, 1, counted_eq(p, e[0].key));
+ if (!TEST_ptr_eq(p, &e[0]) || !TEST_int_eq(cond_calls, 4))
+ goto end;
+ ret = 1;
+end:
+ ossl_htable_dyn_cleanup(&dyn);
+ return ret;
+}
+
+static int test_dyn_reserve(void)
+{
+ OSSL_HTABLE(dyn) table;
+ ENTRY e[3], *p;
+ size_t i;
+ int ret = 0;
+
+ ossl_htable_dyn_init(&table);
+ init_entries(e, OSSL_NELEM(e), 1);
+ for (i = 0; i < OSSL_NELEM(e); i++)
+ ossl_htable_dyn_add(&table, &e[i], key_hash(e[i].key));
+
+ /* Fewer than there are buckets: nothing to do */
+ if (!TEST_true(ossl_htable_dyn_reserve(&table, 2))
+ || !TEST_ptr_eq(table.dyn_buckets, table.inline_buckets)
+ /* Up to the next power of two, entries carried over */
+ || !TEST_true(ossl_htable_dyn_reserve(&table, 100))
+ || !TEST_size_t_eq(ossl_htable_dyn_num_buckets(&table), 128)
+ /* Bounded by max_bits */
+ || !TEST_true(ossl_htable_dyn_reserve(&table, 100000))
+ || !TEST_size_t_eq(ossl_htable_dyn_num_buckets(&table),
+ (size_t)1 << DYN_MAX_BITS))
+ goto end;
+ for (i = 0; i < OSSL_NELEM(e); i++) {
+ OSSL_HTABLE_FIND(p, dyn, &table, key_hash(e[i].key), p->key == e[i].key);
+ if (!TEST_ptr_eq(p, &e[i]))
+ goto end;
+ }
+ ret = 1;
+end:
+ ossl_htable_dyn_cleanup(&table);
+ return ret;
+}
+
+/* Allocation failure while growing: the table carries on with its buckets. */
+static CRYPTO_malloc_fn saved_malloc;
+static CRYPTO_realloc_fn saved_realloc;
+static CRYPTO_free_fn saved_free;
+static int fail_mallocs;
+
+static void *failing_malloc(size_t num, const char *file, int line)
+{
+ if (fail_mallocs)
+ return NULL;
+ return saved_malloc(num, file, line);
+}
+
+static int test_dyn_grow_failure(void)
+{
+ OSSL_HTABLE(dyn) table;
+ ENTRY e[16], *p;
+ size_t i;
+ int wrapped = 0, ret = 0;
+
+ /*
+ * The library lets its allocator be replaced only until the default one
+ * has been used, which the test framework prevents by installing its
+ * own (mfail) first. Without that one, as with
+ * OPENSSL_TEST_MFAIL_DISABLE=1, there is nothing that may be wrapped.
+ */
+ if (!mfail_is_installed())
+ return TEST_skip("needs the mfail allocator, which is not installed");
+
+ ossl_htable_dyn_init(&table);
+ init_entries(e, OSSL_NELEM(e), 1);
+ CRYPTO_get_mem_functions(&saved_malloc, &saved_realloc, &saved_free);
+ if (!TEST_true(CRYPTO_set_mem_functions(failing_malloc, saved_realloc,
+ saved_free)))
+ goto end;
+ wrapped = 1;
+
+ fail_mallocs = 1;
+ for (i = 0; i < 8; i++)
+ ossl_htable_dyn_add(&table, &e[i], key_hash(e[i].key));
+ if (!TEST_false(ossl_htable_dyn_reserve(&table, 64)))
+ goto end;
+ fail_mallocs = 0;
+ if (!TEST_ptr_eq(table.dyn_buckets, table.inline_buckets)
+ || !TEST_size_t_eq(ossl_htable_dyn_num_buckets(&table),
+ (size_t)1 << DYN_MIN_BITS)
+ || !TEST_size_t_eq(ossl_htable_num(&table), 8))
+ goto end;
+ for (i = 0; i < 8; i++) {
+ OSSL_HTABLE_FIND(p, dyn, &table, key_hash(e[i].key), p->key == e[i].key);
+ if (!TEST_ptr_eq(p, &e[i]))
+ goto end;
+ }
+
+ /* An add whose grow fails still adds, and raises no error */
+ ERR_clear_error();
+ fail_mallocs = 1;
+ ossl_htable_dyn_add(&table, &e[8], key_hash(e[8].key));
+ fail_mallocs = 0;
+ if (!TEST_size_t_eq(ossl_htable_dyn_num_buckets(&table),
+ (size_t)1 << DYN_MIN_BITS)
+ || !TEST_size_t_eq(ossl_htable_num(&table), 9)
+ || !TEST_ulong_eq(ERR_peek_error(), 0))
+ goto end;
+
+ /* The next add grows by one doubling, not to fit every entry */
+ ossl_htable_dyn_add(&table, &e[9], key_hash(e[9].key));
+ if (!TEST_size_t_eq(ossl_htable_dyn_num_buckets(&table),
+ (size_t)2 << DYN_MIN_BITS))
+ goto end;
+ for (i = 10; i < OSSL_NELEM(e); i++)
+ ossl_htable_dyn_add(&table, &e[i], key_hash(e[i].key));
+ if (!TEST_size_t_eq(ossl_htable_dyn_num_buckets(&table), 16))
+ goto end;
+ for (i = 0; i < OSSL_NELEM(e); i++) {
+ OSSL_HTABLE_FIND(p, dyn, &table, key_hash(e[i].key), p->key == e[i].key);
+ if (!TEST_ptr_eq(p, &e[i]))
+ goto end;
+ }
+ ret = 1;
+end:
+ fail_mallocs = 0;
+ if (wrapped
+ && !TEST_true(CRYPTO_set_mem_functions(saved_malloc, saved_realloc,
+ saved_free)))
+ ret = 0;
+ ossl_htable_dyn_cleanup(&table);
+ return ret;
+}
+
+/*
+ * Cleanup neither visits nor unlinks the elements. They may be gone by the
+ * time it runs, as the objects of an X509_STORE are. One that is kept still
+ * has the link it had in the table, into buckets that were freed, which
+ * init_elem clears before the element is added again.
+ */
+static int test_dyn_cleanup(void)
+{
+ OSSL_HTABLE(dyn) table;
+ ENTRY *e[64], keep[8], *p;
+ size_t i;
+ int ret = 0;
+
+ memset(e, 0, sizeof(e));
+ ossl_htable_dyn_init(&table);
+ for (i = 0; i < OSSL_NELEM(e); i++) {
+ /* Zeroed, so the links need no init_elem */
+ if (!TEST_ptr(e[i] = OPENSSL_zalloc(sizeof(*e[i]))))
+ goto end;
+ e[i]->key = i;
+ ossl_htable_dyn_add(&table, e[i], key_hash(i));
+ }
+ if (!TEST_ptr_ne(table.dyn_buckets, table.inline_buckets))
+ goto end;
+
+ /* Freed while in the table: cleanup has no business with them */
+ for (i = 0; i < OSSL_NELEM(e); i++) {
+ OPENSSL_free(e[i]);
+ e[i] = NULL;
+ }
+ ossl_htable_dyn_cleanup(&table);
+ /* A second cleanup finds nothing left to free */
+ ossl_htable_dyn_cleanup(&table);
+
+ /* Kept across a cleanup of grown buckets: their links are stale */
+ ossl_htable_dyn_init(&table);
+ init_entries(keep, OSSL_NELEM(keep), 1);
+ for (i = 0; i < OSSL_NELEM(keep); i++)
+ ossl_htable_dyn_add(&table, &keep[i], key_hash(keep[i].key));
+ if (!TEST_ptr_ne(table.dyn_buckets, table.inline_buckets))
+ goto end;
+ ossl_htable_dyn_cleanup(&table);
+
+ /* Cleared, they go into the table again once it is initialised again */
+ ossl_htable_dyn_init(&table);
+ for (i = 0; i < OSSL_NELEM(keep); i++) {
+ ossl_queue_dyn_init_elem(&keep[i]);
+ ossl_htable_dyn_add(&table, &keep[i], key_hash(keep[i].key));
+ }
+ if (!TEST_size_t_eq(ossl_htable_num(&table), OSSL_NELEM(keep)))
+ goto end;
+ for (i = 0; i < OSSL_NELEM(keep); i++) {
+ OSSL_HTABLE_FIND(p, dyn, &table, key_hash(keep[i].key),
+ p->key == keep[i].key);
+ if (!TEST_ptr_eq(p, &keep[i]))
+ goto end;
+ }
+ ret = 1;
+end:
+ for (i = 0; i < OSSL_NELEM(e); i++)
+ OPENSSL_free(e[i]);
+ ossl_htable_dyn_cleanup(&table);
+ return ret;
+}
+
+static void dyn_del_visited(ENTRY *el, void *arg)
+{
+ el->visits++;
+ ossl_htable_dyn_del(arg, el);
+}
+
+/* doall visits every entry once, across grown buckets, and may delete it. */
+static int test_dyn_doall_del(void)
+{
+ OSSL_HTABLE(dyn) table;
+ ENTRY e[100];
+ size_t i;
+ int ret = 0;
+
+ ossl_htable_dyn_init(&table);
+ init_entries(e, OSSL_NELEM(e), 3);
+ for (i = 0; i < OSSL_NELEM(e); i++)
+ ossl_htable_dyn_add(&table, &e[i], key_hash(e[i].key));
+ ossl_htable_dyn_doall_arg(&table, dyn_del_visited, &table);
+ if (!TEST_true(ossl_htable_is_empty(&table)))
+ goto end;
+ for (i = 0; i < OSSL_NELEM(e); i++)
+ if (!TEST_int_eq(e[i].visits, 1)
+ || !TEST_false(ossl_queue_dyn_hashed(&e[i])))
+ goto end;
+ ret = 1;
+end:
+ ossl_htable_dyn_cleanup(&table);
+ return ret;
+}
+
+/* The reader macros see what _add_rcu() published, newest first. */
+static int test_rcu_add_find(void)
+{
+ OSSL_HTABLE(pub) table;
+ ENTRY e[64], *p;
+ size_t i, n;
+
+ ossl_htable_pub_init(&table);
+ memset(e, 0, sizeof(e));
+
+ for (i = 0; i < OSSL_NELEM(e); i++) {
+ e[i].key = i;
+ /* Not there until it is published */
+ OSSL_HTABLE_FIND_RCU(p, pub, &table, key_hash(i), p->key == i);
+ if (!TEST_ptr_null(p))
+ return 0;
+ ossl_htable_pub_add_rcu(&table, &e[i], key_hash(i));
+ OSSL_HTABLE_FIND_RCU(p, pub, &table, key_hash(i), p->key == i);
+ if (!TEST_ptr_eq(p, &e[i]))
+ return 0;
+ }
+ if (!TEST_size_t_eq(ossl_htable_num(&table), OSSL_NELEM(e)))
+ return 0;
+
+ /* The locked and the lock-free views of a chain agree */
+ for (i = 0; i < OSSL_NELEM(e); i++) {
+ OSSL_HTABLE_FIND(p, pub, &table, key_hash(i), p->key == i);
+ if (!TEST_ptr_eq(p, &e[i]))
+ return 0;
+ }
+ n = 0;
+ for (i = 0; i < ossl_htable_num_buckets(&table); i++)
+ OSSL_HTABLE_FOREACH_RCU (p, pub, &table, i)
+ n++;
+ if (!TEST_size_t_eq(n, OSSL_NELEM(e)))
+ return 0;
+
+ /* A published element is an ordinary one to the writer side */
+ ossl_htable_pub_del(&table, &e[0]);
+ OSSL_HTABLE_FIND_RCU(p, pub, &table, key_hash(0), p->key == 0);
+ return TEST_ptr_null(p)
+ && TEST_size_t_eq(ossl_htable_num(&table), OSSL_NELEM(e) - 1);
+}
+
+#ifdef HTABLE_TEST_THREADS
+/*
+ * One writer publishes elements while readers look them up without a lock.
+ * A reader must find every key below the count the writer has announced,
+ * and whatever it finds must be completely initialised.
+ */
+#define RCU_ELEMS 20000
+#define RCU_READERS 4
+
+static OSSL_HTABLE(pub) rcu_table;
+static ENTRY *rcu_elems;
+static CRYPTO_RWLOCK *rcu_count_lock;
+static int rcu_published;
+static int rcu_reader_errors;
+
+static void rcu_reader_fn(void)
+{
+ ENTRY *p;
+ int n = 0, i, errs = 0;
+
+ while (n < RCU_ELEMS) {
+ if (!CRYPTO_atomic_load_int(&rcu_published, &n, rcu_count_lock)) {
+ errs++;
+ break;
+ }
+ /* Announced keys: the newest, the oldest and a few in between */
+ for (i = n - 1; i >= 0; i -= 1 + n / 8) {
+ OSSL_HTABLE_FIND_RCU(p, pub, &rcu_table, key_hash(i),
+ p->key == (uint64_t)i);
+ if (p == NULL || p->visits != i + 1)
+ errs++;
+ }
+ /* Keys being added right now: found or not, but never half done */
+ for (i = n; i < n + 8 && i < RCU_ELEMS; i++) {
+ OSSL_HTABLE_FIND_RCU(p, pub, &rcu_table, key_hash(i),
+ p->key == (uint64_t)i);
+ if (p != NULL && p->visits != i + 1)
+ errs++;
+ }
+ }
+ if (errs != 0) {
+ int dummy;
+
+ (void)CRYPTO_atomic_add(&rcu_reader_errors, errs, &dummy,
+ rcu_count_lock);
+ }
+}
+
+static int test_rcu_threads(void)
+{
+ thread_t readers[RCU_READERS];
+ int i, started = 0, ret = 0, errs = -1;
+
+ rcu_published = 0;
+ rcu_reader_errors = 0;
+ ossl_htable_pub_init(&rcu_table);
+ rcu_elems = OPENSSL_calloc(RCU_ELEMS, sizeof(*rcu_elems));
+ rcu_count_lock = CRYPTO_THREAD_lock_new();
+ if (!TEST_ptr(rcu_elems) || !TEST_ptr(rcu_count_lock))
+ goto end;
+
+ for (; started < RCU_READERS; started++)
+ if (!TEST_true(run_thread(&readers[started], rcu_reader_fn)))
+ break;
+
+ for (i = 0; i < RCU_ELEMS; i++) {
+ /* Complete the element, then publish it */
+ rcu_elems[i].visits = i + 1;
+ rcu_elems[i].key = (uint64_t)i;
+ ossl_htable_pub_add_rcu(&rcu_table, &rcu_elems[i], key_hash(i));
+ if (!CRYPTO_atomic_store_int(&rcu_published, i + 1, rcu_count_lock))
+ break;
+ }
+ /* Let the readers finish even if the writer gave up */
+ (void)CRYPTO_atomic_store_int(&rcu_published, RCU_ELEMS, rcu_count_lock);
+
+ ret = TEST_int_eq(i, RCU_ELEMS) && TEST_int_eq(started, RCU_READERS);
+ for (i = 0; i < started; i++)
+ if (!TEST_true(wait_for_thread(readers[i])))
+ ret = 0;
+ if (!TEST_true(CRYPTO_atomic_load_int(&rcu_reader_errors, &errs,
+ rcu_count_lock))
+ || !TEST_int_eq(errs, 0))
+ ret = 0;
+end:
+ CRYPTO_THREAD_lock_free(rcu_count_lock);
+ OPENSSL_free(rcu_elems);
+ return ret;
+}
+#endif /* HTABLE_TEST_THREADS */
+
+int setup_tests(void)
+{
+ ADD_TEST(test_init);
+ ADD_TEST(test_add_find_del);
+ ADD_TEST(test_single_bucket);
+ ADD_TEST(test_ruc);
+ ADD_TEST(test_hash_mixing);
+ ADD_TEST(test_dyn_grow);
+ ADD_TEST(test_dyn_max_bits);
+ ADD_TEST(test_dyn_hash_compare);
+ ADD_TEST(test_dyn_reserve);
+ ADD_TEST(test_dyn_grow_failure);
+ ADD_TEST(test_dyn_cleanup);
+ ADD_TEST(test_dyn_doall_del);
+ ADD_TEST(test_rcu_add_find);
+#ifdef HTABLE_TEST_THREADS
+ ADD_TEST(test_rcu_threads);
+#endif
+ ADD_TEST(test_keyed_hash);
+ ADD_TEST(test_scan_typical);
+ ADD_TEST(test_scan_duplicate_known);
+ ADD_ALL_TESTS(test_scan_unknown, OSSL_NELEM(unknown_counts));
+ ADD_TEST(test_scan_duplicate_unknown);
+ ADD_ALL_TESTS(test_scan_no_rand, 2);
+ ADD_TEST(test_scan_prefix_oids);
+ ADD_TEST(test_scan_critical);
+ ADD_TEST(test_scan_dynamic_nid);
+ ADD_TEST(test_scan_zero_length_oid);
+ ADD_TEST(test_scan_flood);
+ return 1;
+}
diff --git a/test/lhash_test.c b/test/lhash_test.c
index 11b0ea7fb8..538bbd7588 100644
--- a/test/lhash_test.c
+++ b/test/lhash_test.c
@@ -16,10 +16,8 @@
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/crypto.h>
-#include <internal/hashtable.h>
#include "internal/nelem.h"
-#include "threadstest.h"
#include "testutil.h"
/*
@@ -32,8 +30,6 @@
DEFINE_LHASH_OF_EX(int);
-static void hashtable_intfree(HT_VALUE *v);
-
static int int_tests[] = { 65537, 13, 1, 3, -5, 6, 7, 4, -10, -12, -14, 22, 9,
-17, 16, 17, -23, 35, 37, 173, 11 };
static const size_t n_int_tests = OSSL_NELEM(int_tests);
@@ -262,255 +258,6 @@ end:
return testresult;
}
-static int int_filter_all(HT_VALUE *v, void *arg)
-{
- return 1;
-}
-
-HT_START_KEY_DEFN(intkey)
-HT_DEF_KEY_FIELD(mykey, int)
-HT_END_KEY_DEFN(INTKEY)
-
-IMPLEMENT_HT_VALUE_TYPE_FNS(int, test, static)
-
-static int int_foreach(HT_VALUE *v, void *arg)
-{
- int *vd = ossl_ht_test_int_from_value(v);
- const int n = int_find(*vd);
-
- if (n < 0)
- int_not_found++;
- else
- int_found[n]++;
- return 1;
-}
-
-static uint64_t hashtable_hash(HT_KEY *key)
-{
- return (uint64_t)(*(uint32_t *)key->keybuf);
-}
-
-static uint64_t hashtable_collision_hash(HT_KEY *key)
-{
- return 42;
-}
-
-static int test_hashtable_collisions(int idx)
-{
- static unsigned char keys[][5] = { "aaa", "bbb", "bbbb", "" };
- HT_CONFIG hash_conf = {
- .ht_hash_fn = hashtable_collision_hash,
- .collision_check = 1,
- .no_rcu = idx,
- };
- struct {
- HT_KEY key_header;
- } key;
- HT *ht = NULL;
- HT_VALUE value = { 0 }, *found;
- size_t i;
- int ret = 0;
-
- if (!TEST_ptr(ht = ossl_ht_new(&hash_conf)))
- goto end;
-
- /* Distinct keys must survive a collision even when their lengths differ. */
- for (i = 0; i < OSSL_NELEM(keys); i++) {
- HT_INIT_KEY(&key);
- key.key_header.keybuf = keys[i];
- key.key_header.keysize = strlen((char *)keys[i]);
- value.value = keys[i];
- if (!TEST_int_eq(ossl_ht_insert(ht, TO_HT_KEY(&key), &value, NULL), 1))
- goto end;
- }
-
- for (i = 0; i < OSSL_NELEM(keys); i++) {
- HT_INIT_KEY(&key);
- key.key_header.keybuf = keys[i];
- key.key_header.keysize = strlen((char *)keys[i]);
- if (!TEST_ptr(found = ossl_ht_get(ht, TO_HT_KEY(&key)))
- || !TEST_ptr_eq(found->value, keys[i]))
- goto end;
- }
-
- ret = 1;
-
-end:
- ossl_ht_free(ht);
- return ret;
-}
-
-static int test_int_hashtable(int idx)
-{
- static struct {
- int data;
- int should_del;
- } dels[] = {
- { 65537, 1 },
- { 173, 1 },
- { 999, 0 },
- { 37, 1 },
- { 1, 1 },
- { 34, 0 }
- };
- const size_t n_dels = OSSL_NELEM(dels);
- HT_CONFIG hash_conf = {
- .collision_check = 1,
- .no_rcu = idx,
- };
- INTKEY key;
- int rc = 0;
- size_t i;
- HT *ht = NULL;
- int todel;
- HT_VALUE_LIST *list = NULL;
-
- ht = ossl_ht_new(&hash_conf);
-
- if (ht == NULL)
- return 0;
-
- /* insert */
- HT_INIT_KEY(&key);
- for (i = 0; i < n_int_tests; i++) {
- HT_KEY_RESET(&key);
- HT_SET_KEY_FIELD(&key, mykey, int_tests[i]);
- if (!TEST_int_eq(ossl_ht_test_int_insert(ht, TO_HT_KEY(&key),
- &int_tests[i], NULL),
- 1)) {
- TEST_info("int insert %zu", i);
- goto end;
- }
- }
-
- /* num_items */
- if (!TEST_size_t_eq(ossl_ht_count(ht), n_int_tests))
- goto end;
-
- /* foreach, no arg */
- memset(int_found, 0, sizeof(int_found));
- int_not_found = 0;
- ossl_ht_foreach_until(ht, int_foreach, NULL);
- if (!TEST_int_eq(int_not_found, 0)) {
- TEST_info("hashtable int foreach encountered a not found condition");
- goto end;
- }
-
- for (i = 0; i < n_int_tests; i++)
- if (!TEST_int_eq(int_found[i], 1)) {
- TEST_info("hashtable int foreach %zu", i);
- goto end;
- }
-
- /* filter */
- list = ossl_ht_filter(ht, 64, int_filter_all, NULL);
- if (!TEST_size_t_eq(list->list_len, n_int_tests))
- goto end;
- ossl_ht_value_list_free(list);
-
- /* delete */
- for (i = 0; i < n_dels; i++) {
- HT_KEY_RESET(&key);
- HT_SET_KEY_FIELD(&key, mykey, dels[i].data);
- todel = ossl_ht_delete(ht, TO_HT_KEY(&key));
- if (dels[i].should_del) {
- if (!TEST_int_eq(todel, 1)) {
- TEST_info("hashtable couldn't find entry %d to delete\n",
- dels[i].data);
- goto end;
- }
- } else {
- if (!TEST_int_eq(todel, 0)) {
- TEST_info("%d found an entry that shouldn't be there\n", dels[i].data);
- goto end;
- }
- }
- }
-
- rc = 1;
-end:
- ossl_ht_free(ht);
- return rc;
-}
-
-/*
- * MFAIL coverage for the RCU replacement branch of ossl_ht_insert_locked.
- */
-static int test_hashtable_insert_replace_mfail(void)
-{
- HT_CONFIG hash_conf = {
- .collision_check = 1,
- .no_rcu = 0, /* RCU enabled - exercises cbi pre-alloc on replace */
- };
- INTKEY key;
- HT *ht = NULL;
- int *old = NULL;
- int ret = 0;
- static int v1 = 100;
- static int v2 = 200;
-
- if (!TEST_ptr(ht = ossl_ht_new(&hash_conf)))
- goto end;
-
- /* Seed the table outside MFAIL for later replacement */
- HT_INIT_KEY(&key);
- HT_KEY_RESET(&key);
- HT_SET_KEY_FIELD(&key, mykey, int_tests[0]);
- if (!TEST_int_eq(ossl_ht_test_int_insert(ht, TO_HT_KEY(&key), &v1, NULL),
- 1))
- goto end;
-
- /* Replacement under MFAIL. */
- MFAIL_start();
- ret = ossl_ht_test_int_insert(ht, TO_HT_KEY(&key), &v2, &old);
- MFAIL_end();
-
-end:
- ossl_ht_free(ht);
- return ret > 0 ? 1 : 0;
-}
-
-static int test_hashtable_free_mfail(void)
-{
- HT_CONFIG hash_conf = {
- .ht_free_fn = hashtable_intfree,
- .collision_check = 1,
- .no_rcu = 0,
- };
- INTKEY key;
- HT *ht = NULL;
- int *p;
- size_t i;
-
- if (!TEST_ptr(ht = ossl_ht_new(&hash_conf)))
- return 0;
-
- /* Seed values. */
- HT_INIT_KEY(&key);
- for (i = 0; i < n_int_tests; i++) {
- if (!TEST_ptr(p = OPENSSL_malloc(sizeof(*p))))
- goto end;
- *p = int_tests[i];
- HT_KEY_RESET(&key);
- HT_SET_KEY_FIELD(&key, mykey, *p);
- if (!TEST_int_eq(ossl_ht_test_int_insert(ht, TO_HT_KEY(&key),
- p, NULL),
- 1)) {
- OPENSSL_free(p);
- goto end;
- }
- }
- MFAIL_start();
- ossl_ht_free(ht);
- MFAIL_end();
- ht = NULL;
-
- return 1;
-end:
- ossl_ht_free(ht);
- return 0;
-}
-
static unsigned long int stress_hash(const int *p)
{
return *p;
@@ -600,458 +347,10 @@ end:
return testresult;
}
-static void hashtable_intfree(HT_VALUE *v)
-{
- OPENSSL_free(v->value);
-}
-
-static int test_hashtable_stress(int idx)
-{
- const unsigned int n = 2500000;
- unsigned int i;
- int testresult = 0, *p;
- HT_CONFIG hash_conf = {
- .ht_free_fn = hashtable_intfree,
- .ht_hash_fn = hashtable_hash,
- .init_neighborhoods = 625000,
- .collision_check = 1,
- .lockless_reads = idx % 2,
- .no_rcu = idx / 2,
- };
-
- HT *h;
- INTKEY key;
- HT_VALUE *v;
-#ifdef MEASURE_HASH_PERFORMANCE
- struct timeval start, end, delta;
-#endif
-
- h = ossl_ht_new(&hash_conf);
- if (h == NULL
- && hash_conf.no_rcu
- && hash_conf.lockless_reads)
- return 1;
-
- if (!TEST_ptr(h))
- goto end;
-#ifdef MEASURE_HASH_PERFORMANCE
- gettimeofday(&start, NULL);
-#endif
-
- HT_INIT_KEY(&key);
-
- /* insert */
- for (i = 0; i < n; i++) {
- p = OPENSSL_malloc(sizeof(i));
- if (!TEST_ptr(p)) {
- TEST_info("hashtable stress out of memory %d", i);
- goto end;
- }
- *p = 3 * i + 1;
- HT_KEY_RESET(&key);
- HT_SET_KEY_FIELD(&key, mykey, *p);
- if (!TEST_int_eq(ossl_ht_test_int_insert(h, TO_HT_KEY(&key),
- p, NULL),
- 1)) {
- TEST_info("hashtable unable to insert element %d\n", *p);
- goto end;
- }
- }
-
- /* make sure we stored everything */
- if (!TEST_size_t_eq(ossl_ht_count(h), n))
- goto end;
-
- /* delete or get in a different order */
- for (i = 0; i < n; i++) {
- const int j = (7 * i + 4) % n * 3 + 1;
- HT_KEY_RESET(&key);
- HT_SET_KEY_FIELD(&key, mykey, j);
-
- switch (idx % 2) {
- case 0:
- if (!TEST_int_eq((ossl_ht_delete(h, TO_HT_KEY(&key))), 1)) {
- TEST_info("hashtable didn't delete key %d\n", j);
- goto end;
- }
- break;
- case 1:
- if (!TEST_ptr(p = ossl_ht_test_int_get(h, TO_HT_KEY(&key), &v))
- || !TEST_int_eq(*p, j)) {
- TEST_info("hashtable didn't get key %d\n", j);
- goto end;
- }
- break;
- }
- }
-
- testresult = 1;
-end:
-#ifdef MEASURE_HASH_PERFORMANCE
- gettimeofday(&end, NULL);
- timeval_subtract(&delta, &end, &start);
- TEST_info("hashtable stress runs in %ld.%ld seconds", delta.tv_sec, delta.tv_usec);
-#endif
- ossl_ht_free(h);
- return testresult;
-}
-
-typedef struct test_mt_entry {
- int in_table;
- int pending_delete;
-} TEST_MT_ENTRY;
-
-static HT *m_ht = NULL;
-#define TEST_MT_POOL_SZ 256
-/*-
- * TEST_THREAD_ITERATIONS is chosen so that collisions between workers
- * on the same key are exercised, not to make the test run for any
- * particular length of time.
- *
- * Choosing too large a number consumes a multithreaded machine with the
- * kernel madly exercising lock contention, for no real gain in coverage
- * for our code, making the tests run excessively long. A million
- * iterations is really painful.
- *
- * A race needs two workers on one key at once, so what must be covered is
- * each ordered pair of behaviours -- NUM_BEHAVIORS squared, or 16 --
- * arriving together on a key. With W workers an operation collides with
- * probability P = 1 - ((TEST_MT_POOL_SZ - 1) / TEST_MT_POOL_SZ) ^ (W - 1),
- * and a collision is equally likely to be any of the 16, so each is seen
- * an expected E = W * TEST_THREAD_ITERATIONS * P / 16 times per
- * configuration. The chance of never seeing one is about 16 * exp(-E):
- *
- * workers E P(some combination never exercised)
- * 2 73 1e-31
- * 4 438 1e-189
- * 8 2027 1e-879
- * 16 8553 1e-3713
- *
- * Coverage rises with the square of the worker count but run time only
- * linearly, so the value is sized for the fewest workers worth supporting.
- * At two workers 10000 iterations would miss a combination one run in
- * nine, and 20000 one run in a thousand; the value below is far enough
- * past that to leave each combination met at many different points in the
- * interleaving. More buys only further chances of landing in a narrow
- * timing window, not more of the state space.
- */
-#define TEST_THREAD_ITERATIONS 150000
-/*-
- * Four workers is enough to interleave more than a pair of threads on a
- * key, which two cannot do, without tying up a whole machine.
- */
-#define MAX_NUM_WORKERS 4
-
-static struct test_mt_entry test_mt_entries[TEST_MT_POOL_SZ];
-static char **worker_exits;
-static thread_t *workers;
-static int num_workers = MAX_NUM_WORKERS;
-
-static int setup_num_workers(void)
-{
- char *harness_jobs = getenv("HARNESS_JOBS");
- char *lhash_workers = getenv("LHASH_WORKERS");
- /* If we have HARNESS_JOBS set, don't use more workers than that */
- if (harness_jobs != NULL) {
- int jobs;
-
- if (test_strtoint(harness_jobs, &jobs) && jobs > 0
- && jobs < num_workers)
- num_workers = jobs;
- }
- /* But if we have explicitly set LHASH_WORKERS use that */
- if (lhash_workers != NULL) {
- int jobs;
-
- if (test_strtoint(lhash_workers, &jobs) && jobs > 0)
- num_workers = jobs;
- }
-
- TEST_info("using %d workers\n", num_workers);
-
- free(worker_exits);
- free(workers);
- worker_exits = calloc(num_workers, sizeof(*worker_exits));
- workers = calloc(num_workers, sizeof(*workers));
- return worker_exits != NULL && workers != NULL;
-}
-
-HT_START_KEY_DEFN(mtkey)
-HT_DEF_KEY_FIELD(index, uint32_t)
-HT_END_KEY_DEFN(MTKEY)
-
-IMPLEMENT_HT_VALUE_TYPE_FNS(TEST_MT_ENTRY, mt, static)
-
-struct ht_internal_st {
- HT_CONFIG config;
-};
-
-static int worker_num = 0;
-static CRYPTO_RWLOCK *worker_lock;
-static CRYPTO_RWLOCK *testrand_lock;
-static CRYPTO_RWLOCK *no_rcu_lock;
-static int free_failure = 0;
-static int shutting_down = 0;
-static int global_iteration = 0;
-
-static void hashtable_mt_free(HT_VALUE *v)
-{
- TEST_MT_ENTRY *m = ossl_ht_mt_TEST_MT_ENTRY_from_value(v);
- int pending_delete;
- int ret;
-
- if (!TEST_true(CRYPTO_atomic_load_int(&m->pending_delete, &pending_delete,
- worker_lock))) {
- free_failure = 1;
- return;
- }
-
- if (shutting_down == 1)
- return;
-
- if (pending_delete == 0) {
- TEST_info("Freeing element which was not scheduled for free");
- free_failure = 1;
- } else {
- CRYPTO_atomic_add(&m->pending_delete, -1,
- &ret, worker_lock);
- }
-}
-
-#define DO_LOOKUP 0
-#define DO_INSERT 1
-#define DO_REPLACE 2
-#define DO_DELETE 3
-#define NUM_BEHAVIORS (DO_DELETE + 1)
-
-static void do_mt_hash_work(void)
-{
- MTKEY key;
- uint32_t index;
- int num;
- TEST_MT_ENTRY *m;
- TEST_MT_ENTRY *expected_m = NULL;
- HT_VALUE *v = NULL;
- TEST_MT_ENTRY **r = NULL;
- int expected_rc;
- int ret;
- char behavior;
- size_t iter = 0;
- int giter;
-
- CRYPTO_atomic_add(&worker_num, 1, &num, worker_lock);
- num--; /* atomic_add is an add/fetch operation */
-
- HT_INIT_KEY(&key);
-
- for (iter = 0; iter < TEST_THREAD_ITERATIONS; iter++) {
- if (!TEST_true(CRYPTO_THREAD_write_lock(testrand_lock)))
- return;
- index = test_random() % TEST_MT_POOL_SZ;
- behavior = (char)(test_random() % NUM_BEHAVIORS);
- CRYPTO_THREAD_unlock(testrand_lock);
-
- expected_m = &test_mt_entries[index];
- HT_KEY_RESET(&key);
- HT_SET_KEY_FIELD(&key, index, index);
-
- if (!CRYPTO_atomic_add(&global_iteration, 1, &giter, worker_lock)) {
- worker_exits[num] = "Unable to increment global iterator";
- return;
- }
- switch (behavior) {
- case DO_LOOKUP:
- if (!m_ht->config.no_rcu) {
- if (!ossl_ht_read_lock(m_ht))
- break;
- } else {
- if (!TEST_true(CRYPTO_THREAD_read_lock(no_rcu_lock)))
- break;
- }
- m = ossl_ht_mt_TEST_MT_ENTRY_get(m_ht, TO_HT_KEY(&key), &v);
- if (m != NULL && m != expected_m) {
- worker_exits[num] = "Read unexpected value from hashtable";
- TEST_info("Iteration %d Read unexpected value %p when %p expected",
- giter, (void *)m, (void *)expected_m);
- }
- if (!m_ht->config.no_rcu) {
- ossl_ht_read_unlock(m_ht);
- } else {
- if (!TEST_true(CRYPTO_THREAD_unlock(no_rcu_lock)))
- break;
- }
- if (worker_exits[num] != NULL)
- return;
- break;
- case DO_INSERT:
- case DO_REPLACE:
- if (!m_ht->config.no_rcu) {
- ossl_ht_write_lock(m_ht);
- } else {
- if (!TEST_true(CRYPTO_THREAD_write_lock(no_rcu_lock)))
- break;
- }
- if (behavior == DO_REPLACE) {
- expected_rc = 1;
- r = &m;
- } else {
- expected_rc = !expected_m->in_table;
- r = NULL;
- }
-
- if (expected_rc != ossl_ht_mt_TEST_MT_ENTRY_insert(m_ht, TO_HT_KEY(&key), expected_m, r)) {
- TEST_info("Iteration %d Expected rc %d on %s of element %u which is %s\n",
- giter, expected_rc, behavior == DO_REPLACE ? "replace" : "insert",
- (unsigned int)index,
- expected_m->in_table ? "in table" : "not in table");
- worker_exits[num] = "Failure on insert";
- }
- if (expected_rc == 1)
- expected_m->in_table = 1;
- if (!m_ht->config.no_rcu) {
- ossl_ht_write_unlock(m_ht);
- } else {
- if (!TEST_true(CRYPTO_THREAD_unlock(no_rcu_lock)))
- break;
- }
- if (worker_exits[num] != NULL)
- return;
- break;
- case DO_DELETE:
- if (!m_ht->config.no_rcu) {
- ossl_ht_write_lock(m_ht);
- } else {
- if (!TEST_true(CRYPTO_THREAD_write_lock(no_rcu_lock)))
- break;
- }
- expected_rc = expected_m->in_table;
- if (expected_rc == 1) {
- /*
- * We must set pending_delete before the actual deletion
- * as another inserting or deleting thread can pick up
- * the delete callback before the ossl_ht_write_unlock() call.
- * This can happen only if no read locks are pending and
- * only on Windows where we do not use the write mutex
- * to get the callback list.
- */
- expected_m->in_table = 0;
- CRYPTO_atomic_add(&expected_m->pending_delete, 1, &ret, worker_lock);
- }
- if (expected_rc != ossl_ht_delete(m_ht, TO_HT_KEY(&key))) {
- TEST_info("Iteration %d Expected rc %d on delete of element %u which is %s\n",
- giter, expected_rc, (unsigned int)index,
- expected_m->in_table ? "in table" : "not in table");
- worker_exits[num] = "Failure on delete";
- }
- if (!m_ht->config.no_rcu) {
- ossl_ht_write_unlock(m_ht);
- } else {
- if (!TEST_true(CRYPTO_THREAD_unlock(no_rcu_lock)))
- break;
- }
- if (worker_exits[num] != NULL)
- return;
- break;
- default:
- worker_exits[num] = "Undefined behavior specified";
- return;
- }
- }
-}
-
-static int test_hashtable_multithread(int idx)
-{
- HT_CONFIG hash_conf = {
- .ht_free_fn = hashtable_mt_free,
- .init_neighborhoods = 0,
- .collision_check = 1,
- .no_rcu = idx,
- };
- int ret = 0;
- int i;
-#ifdef MEASURE_HASH_PERFORMANCE
- struct timeval start, end, delta;
-#endif
-
- if (!TEST_true(setup_num_workers()))
- goto end;
-
- memset(test_mt_entries, 0, sizeof(TEST_MT_ENTRY) * TEST_MT_POOL_SZ);
-
- m_ht = ossl_ht_new(&hash_conf);
-
- if (!TEST_ptr(m_ht))
- goto end;
-
- if (!TEST_ptr(worker_lock = CRYPTO_THREAD_lock_new()))
- goto end_free;
- if (!TEST_ptr(testrand_lock = CRYPTO_THREAD_lock_new()))
- goto end_free;
- if (!TEST_ptr(no_rcu_lock = CRYPTO_THREAD_lock_new()))
- goto end_free;
-#ifdef MEASURE_HASH_PERFORMANCE
- gettimeofday(&start, NULL);
-#endif
-
- for (i = 0; i < num_workers; i++) {
- if (!run_thread(&workers[i], do_mt_hash_work))
- goto shutdown;
- }
-
-shutdown:
- for (i = 0; i < num_workers; i++) {
- wait_for_thread(workers[i]);
- }
-
- /*
- * Now that the workers are done, check for any error
- * conditions
- */
- ret = 1;
- for (i = 0; i < num_workers; i++) {
- if (worker_exits[i] != NULL) {
- TEST_info("Worker %d failed: %s\n", i, worker_exits[i]);
- ret = 0;
- }
- }
- if (free_failure == 1) {
- TEST_info("Encountered a free failure");
- ret = 0;
- }
-
-#ifdef MEASURE_HASH_PERFORMANCE
- gettimeofday(&end, NULL);
- timeval_subtract(&delta, &end, &start);
- TEST_info("multithread stress runs 40000 ops in %ld.%ld seconds", delta.tv_sec, delta.tv_usec);
-#endif
-
- worker_num = 0;
- free_failure = 0;
- global_iteration = 0;
-end_free:
- shutting_down = 1;
- ossl_ht_free(m_ht);
- CRYPTO_THREAD_lock_free(worker_lock);
- CRYPTO_THREAD_lock_free(testrand_lock);
- CRYPTO_THREAD_lock_free(no_rcu_lock);
- free(workers);
- workers = NULL;
- free(worker_exits);
- worker_exits = NULL;
-end:
- return ret;
-}
-
int setup_tests(void)
{
ADD_TEST(test_int_lhash);
ADD_TEST(test_raw_lhash_doall);
ADD_TEST(test_stress);
- ADD_ALL_TESTS(test_int_hashtable, 2);
- ADD_ALL_TESTS(test_hashtable_collisions, 2);
- ADD_ALL_TESTS(test_hashtable_stress, 4);
- ADD_ALL_TESTS(test_hashtable_multithread, 2);
- ADD_MFAIL_TEST(test_hashtable_insert_replace_mfail);
- ADD_MFAIL_NO_CHECK_TEST(test_hashtable_free_mfail);
return 1;
}
diff --git a/test/namemap_internal_test.c b/test/namemap_internal_test.c
index ec5d23d714..988b6928d5 100644
--- a/test/namemap_internal_test.c
+++ b/test/namemap_internal_test.c
@@ -7,6 +7,9 @@
* https://www.openssl.org/source/license.html
*/
+#include <ctype.h>
+#include <stdio.h>
+#include <string.h>
#include <openssl/evp.h>
#include "internal/namemap.h"
#include "testutil.h"
@@ -53,6 +56,134 @@ static int test_namemap(OSSL_NAMEMAP *nm)
&& TEST_int_eq(false1, 0);
}
+/*
+ * The number of names has no limit, whatever the size of the name->number
+ * table, and every one of them stays findable under any letter case.
+ */
+static int test_namemap_many(void)
+{
+ OSSL_NAMEMAP *nm = ossl_namemap_new(NULL);
+ char name[32], alias[32];
+ int i, num, ok = 0;
+ const int count = 5000;
+
+ if (!TEST_ptr(nm))
+ return 0;
+ for (i = 0; i < count; i++) {
+ snprintf(name, sizeof(name), "name-%d", i);
+ snprintf(alias, sizeof(alias), "Alias.%d", i);
+ if (!TEST_int_eq(num = ossl_namemap_add_name(nm, 0, name), i + 1)
+ || !TEST_int_eq(ossl_namemap_add_name(nm, num, alias), num))
+ goto end;
+ }
+ for (i = 0; i < count; i++) {
+ snprintf(name, sizeof(name), "NAME-%d", i);
+ snprintf(alias, sizeof(alias), "alias.%d", i);
+ if (!TEST_int_eq(ossl_namemap_name2num(nm, name), i + 1)
+ || !TEST_int_eq(ossl_namemap_name2num(nm, alias), i + 1)
+ || !TEST_int_eq(ossl_namemap_name2num_n(nm, name, 4), 0))
+ goto end;
+ snprintf(name, sizeof(name), "name-%d", i);
+ if (!TEST_str_eq(ossl_namemap_num2name(nm, i + 1, 0), name))
+ goto end;
+ }
+ ok = TEST_int_eq(ossl_namemap_name2num(nm, "name-5000"), 0);
+end:
+ ossl_namemap_free(nm);
+ return ok;
+}
+
+/* Names are told apart by their first 64 characters only. */
+static int test_namemap_long(void)
+{
+ OSSL_NAMEMAP *nm = ossl_namemap_new(NULL);
+ char n63[64], n64[65], n70a[71], n70b[71];
+ int num63, num64, ok;
+
+ memset(n63, 'a', 63);
+ n63[63] = '\0';
+ memset(n64, 'a', 64);
+ n64[64] = '\0';
+ memset(n70a, 'a', 70);
+ n70a[70] = '\0';
+ memset(n70b, 'A', 64);
+ memcpy(n70b + 64, "bcdefg", 7);
+
+ ok = TEST_ptr(nm)
+ && TEST_int_ne(num63 = ossl_namemap_add_name(nm, 0, n63), 0)
+ && TEST_int_ne(num64 = ossl_namemap_add_name(nm, 0, n70a), 0)
+ && TEST_int_ne(num63, num64)
+ /* The same first 64 characters: the same name */
+ && TEST_int_eq(ossl_namemap_add_name(nm, 0, n64), num64)
+ && TEST_int_eq(ossl_namemap_name2num(nm, n64), num64)
+ && TEST_int_eq(ossl_namemap_name2num(nm, n70b), num64)
+ && TEST_int_eq(ossl_namemap_name2num_n(nm, n70b, 64), num64)
+ && TEST_int_eq(ossl_namemap_name2num_n(nm, n70b, 63), num63)
+ && TEST_int_eq(ossl_namemap_name2num(nm, n63), num63)
+ /* The name is kept whole all the same */
+ && TEST_str_eq(ossl_namemap_num2name(nm, num64, 0), n70a)
+ && TEST_ptr_null(ossl_namemap_num2name(nm, num64, 1));
+ ossl_namemap_free(nm);
+ return ok;
+}
+
+/*
+ * A space is a character like any other, wherever it is: a name with a
+ * space before or after it is another name.
+ */
+static int test_namemap_spaces(void)
+{
+ OSSL_NAMEMAP *nm = ossl_namemap_new(NULL);
+ int num = 0, after = 0, before = 0, ok;
+
+ ok = TEST_ptr(nm)
+ && TEST_int_ne(num = ossl_namemap_add_name(nm, 0, "name"), 0)
+ && TEST_int_eq(ossl_namemap_name2num(nm, "name "), 0)
+ && TEST_int_eq(ossl_namemap_name2num(nm, " name"), 0)
+ && TEST_int_eq(ossl_namemap_name2num(nm, "na me"), 0)
+ && TEST_int_eq(ossl_namemap_name2num_n(nm, "name ", 4), num)
+ && TEST_int_ne(after = ossl_namemap_add_name(nm, 0, "name "), 0)
+ && TEST_int_ne(before = ossl_namemap_add_name(nm, 0, " name"), 0)
+ && TEST_int_ne(after, num)
+ && TEST_int_ne(before, num)
+ && TEST_int_ne(before, after)
+ && TEST_int_eq(ossl_namemap_name2num(nm, "NAME"), num)
+ && TEST_int_eq(ossl_namemap_name2num(nm, "NAME "), after)
+ && TEST_int_eq(ossl_namemap_name2num(nm, " NAME"), before)
+ && TEST_int_eq(ossl_namemap_name2num(nm, "name "), 0)
+ /* As a second name of the same number, too */
+ && TEST_int_eq(ossl_namemap_add_names(nm, 0, "other:other ", ':'),
+ before + 1)
+ && TEST_str_eq(ossl_namemap_num2name(nm, before + 1, 1), "other ");
+ ossl_namemap_free(nm);
+ return ok;
+}
+
+/*
+ * A lookup with a length does not read a name beyond its NUL, whatever the
+ * length, and what follows the NUL is not part of the name.
+ */
+static int test_namemap_past_nul(void)
+{
+ OSSL_NAMEMAP *nm = ossl_namemap_new(NULL);
+ char exact[5] = "name";
+ int num = 0, ok;
+
+ ok = TEST_ptr(nm)
+ && TEST_int_ne(num = ossl_namemap_add_name(nm, 0, "name"), 0)
+ && TEST_int_ne(ossl_namemap_add_name(nm, 0, "name junk"), num)
+ && TEST_int_eq(ossl_namemap_name2num_n(nm, "name\0junk", 4), num)
+ && TEST_int_eq(ossl_namemap_name2num_n(nm, "name\0junk", 9), 0)
+ && TEST_int_eq(ossl_namemap_name2num_n(nm, exact, 5), 0)
+ && TEST_int_eq(ossl_namemap_name2num_n(nm, exact, 64), 0)
+ && TEST_int_eq(ossl_namemap_name2num_n(nm, exact, 1000), 0)
+ && TEST_int_eq(ossl_namemap_name2num_n(nm, "", 4), 0)
+ && TEST_int_eq(ossl_namemap_name2num_n(nm, NULL, 4), 0)
+ && TEST_int_eq(ossl_namemap_name2num_n(nm, NULL, 0), 0);
+ ossl_namemap_free(nm);
+ return ok;
+}
+
static int test_namemap_independent(void)
{
OSSL_NAMEMAP *nm = ossl_namemap_new(NULL);
@@ -191,10 +322,69 @@ err:
return ret;
}
+/*
+ * Keys are hashed and compared a word at a time, the last word overlapping
+ * the one before it. Names of every length around the word size are found
+ * under either letter case of any character, and are told apart from a name
+ * that differs in any one character or in length.
+ */
+static int test_namemap_lengths(void)
+{
+ static const char letters[] = "abcdefghijklmnopqrstuvwxyz";
+ OSSL_NAMEMAP *nm = ossl_namemap_new(NULL);
+ char name[26], other[sizeof(name) + 1];
+ size_t len, i;
+ int ok = 0;
+
+ if (!TEST_ptr(nm))
+ return 0;
+ /* The name of length |len| gets the number |len| */
+ for (len = 1; len < sizeof(name); len++) {
+ for (i = 0; i < len; i++)
+ name[i] = letters[(i * 7 + len) % 26];
+ name[len] = '\0';
+ if (!TEST_int_eq(ossl_namemap_add_name(nm, 0, name), (int)len))
+ goto end;
+ }
+ for (len = 1; len < sizeof(name); len++) {
+ for (i = 0; i < len; i++)
+ name[i] = letters[(i * 7 + len) % 26];
+ name[len] = '\0';
+ if (!TEST_int_eq(ossl_namemap_name2num(nm, name), (int)len)
+ || !TEST_int_eq(ossl_namemap_name2num_n(nm, name, len - 1), 0))
+ goto end;
+ /* One character more */
+ memcpy(other, name, len);
+ other[len] = name[0];
+ other[len + 1] = '\0';
+ if (!TEST_int_eq(ossl_namemap_name2num(nm, other), 0)
+ || !TEST_int_eq(ossl_namemap_name2num_n(nm, other, len), (int)len))
+ goto end;
+ for (i = 0; i < len; i++) {
+ memcpy(other, name, len + 1);
+ other[i] = (char)toupper((unsigned char)name[i]);
+ if (!TEST_int_eq(ossl_namemap_name2num(nm, other), (int)len))
+ goto end;
+ other[i] = letters[(i * 7 + len + 1) % 26];
+ if (!TEST_int_eq(ossl_namemap_name2num(nm, other), 0))
+ goto end;
+ }
+ }
+ ok = 1;
+end:
+ ossl_namemap_free(nm);
+ return ok;
+}
+
int setup_tests(void)
{
ADD_TEST(test_namemap_empty);
ADD_TEST(test_namemap_independent);
+ ADD_TEST(test_namemap_many);
+ ADD_TEST(test_namemap_long);
+ ADD_TEST(test_namemap_lengths);
+ ADD_TEST(test_namemap_spaces);
+ ADD_TEST(test_namemap_past_nul);
ADD_TEST(test_namemap_stored);
ADD_TEST(test_digestbyname);
ADD_TEST(test_cipherbyname);
diff --git a/test/queue_test.c b/test/queue_test.c
new file mode 100644
index 0000000000..9d3de51fa0
--- /dev/null
+++ b/test/queue_test.c
@@ -0,0 +1,306 @@
+/*
+ * Copyright 2026 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <string.h>
+
+#include <openssl/crypto.h>
+
+#include "internal/queue.h"
+#include "internal/nelem.h"
+#include "testutil.h"
+
+typedef struct qitem_st {
+ int n;
+ OSSL_QUEUE_MEMBER(fizz);
+ OSSL_QUEUE_MEMBER(buzz);
+} QITEM;
+
+DEFINE_QUEUE_OF(fizz, QITEM);
+DEFINE_QUEUE_OF(buzz, QITEM);
+
+/*
+ * Walk |q| and check that it holds exactly the nodes in |exp|, in that order,
+ * and that every back-link points at the slot which points at the node.
+ */
+static int check_node_order(const OSSL_QUEUE *q, OSSL_QNODE *const *exp,
+ size_t n)
+{
+ const OSSL_QNODE *it;
+ size_t i = 0;
+
+ OSSL_QUEUE_WALK (it, q) {
+ if (!TEST_size_t_lt(i, n)
+ || !TEST_ptr_eq(it, exp[i])
+ || !TEST_ptr_eq(*it->prev, it))
+ return 0;
+ i++;
+ }
+ return TEST_size_t_eq(i, n);
+}
+
+static int check_fizz_order(const OSSL_QUEUE *q, const int *exp, size_t n)
+{
+ const QITEM *p;
+ size_t i = 0;
+
+ OSSL_QUEUE_FOREACH (p, fizz, q) {
+ if (!TEST_size_t_lt(i, n)
+ || !TEST_int_eq(p->n, exp[i])
+ || !TEST_ptr_eq(*p->ossl_queue_fizz.prev, &p->ossl_queue_fizz))
+ return 0;
+ i++;
+ }
+ return TEST_size_t_eq(i, n);
+}
+
+static int check_buzz_order(const OSSL_QUEUE *q, const int *exp, size_t n)
+{
+ const QITEM *p;
+ size_t i = 0;
+
+ OSSL_QUEUE_FOREACH (p, buzz, q) {
+ if (!TEST_size_t_lt(i, n)
+ || !TEST_int_eq(p->n, exp[i])
+ || !TEST_ptr_eq(*p->ossl_queue_buzz.prev, &p->ossl_queue_buzz))
+ return 0;
+ i++;
+ }
+ return TEST_size_t_eq(i, n);
+}
+
+/* The node-level operations on bare OSSL_QNODEs. */
+static int test_node_ops(void)
+{
+ OSSL_QUEUE q = OSSL_QUEUE_INIT, q2;
+ OSSL_QNODE n[5], *it, *tmp;
+ OSSL_QNODE *exp1[] = { &n[2], &n[1], &n[0] };
+ OSSL_QNODE *exp2[] = { &n[2], &n[3], &n[1], &n[4], &n[0] };
+ OSSL_QNODE *exp3[] = { &n[3], &n[4] };
+ OSSL_QNODE *exp4[] = { &n[4] };
+ size_t i, count = 0;
+
+ ossl_queue_init(&q2);
+ for (i = 0; i < OSSL_NELEM(n); i++)
+ ossl_qnode_init(&n[i]);
+
+ if (!TEST_true(ossl_queue_empty(&q))
+ || !TEST_true(ossl_queue_empty(&q2))
+ || !TEST_ptr_null(ossl_queue_head(&q))
+ || !TEST_true(ossl_qnode_unhashed(&n[0]))
+ || !TEST_false(ossl_qnode_hashed(&n[0])))
+ return 0;
+
+ /* Insertion is at the head, so the order is reversed */
+ ossl_queue_add_head(&q, &n[0]);
+ ossl_queue_add_head(&q, &n[1]);
+ ossl_queue_add(&q, &n[2]);
+ if (!TEST_false(ossl_queue_empty(&q))
+ || !TEST_true(ossl_qnode_hashed(&n[0]))
+ || !TEST_false(ossl_qnode_unhashed(&n[2]))
+ || !TEST_ptr_eq(ossl_queue_head(&q), &n[2])
+ || !TEST_ptr_eq(ossl_qnode_next(&n[2]), &n[1])
+ || !TEST_ptr_null(ossl_qnode_next(&n[0]))
+ || !check_node_order(&q, exp1, OSSL_NELEM(exp1)))
+ return 0;
+
+ /* Relative insertion before and behind a node in the middle */
+ ossl_qnode_add_before(&n[3], &n[1]);
+ ossl_qnode_add_behind(&n[4], &n[1]);
+ if (!check_node_order(&q, exp2, OSSL_NELEM(exp2)))
+ return 0;
+
+ /* prev() walks back through the back-links, to NULL at the head */
+ if (!TEST_ptr_null(ossl_qnode_prev(&q, &n[2]))
+ || !TEST_ptr_eq(ossl_qnode_prev(&q, &n[3]), &n[2])
+ || !TEST_ptr_eq(ossl_qnode_prev(&q, &n[1]), &n[3])
+ || !TEST_ptr_eq(ossl_qnode_prev(&q, &n[0]), &n[4]))
+ return 0;
+
+ /* Delete the head, the tail and a node in the middle */
+ ossl_qnode_del(&n[2]);
+ ossl_qnode_del(&n[0]);
+ ossl_qnode_del(&n[1]);
+ if (!TEST_true(ossl_qnode_unhashed(&n[2]))
+ || !TEST_ptr_null(n[2].next)
+ || !TEST_ptr_eq(ossl_queue_head(&q), &n[3])
+ || !check_node_order(&q, exp3, OSSL_NELEM(exp3)))
+ return 0;
+
+ /* del_init removes a queued node and ignores one that is not queued */
+ ossl_qnode_del_init(&n[2]);
+ ossl_qnode_del_init(&n[3]);
+ if (!TEST_true(ossl_qnode_unhashed(&n[3]))
+ || !check_node_order(&q, exp4, OSSL_NELEM(exp4)))
+ return 0;
+
+ /* A move re-points the head's back-link, so deletion still works */
+ ossl_queue_move(&q2, &q);
+ if (!TEST_true(ossl_queue_empty(&q))
+ || !check_node_order(&q2, exp4, OSSL_NELEM(exp4)))
+ return 0;
+ ossl_qnode_del(&n[4]);
+ if (!TEST_true(ossl_queue_empty(&q2)))
+ return 0;
+
+ /* A deletion-safe walk may remove every node it visits */
+ for (i = 0; i < OSSL_NELEM(n); i++)
+ ossl_queue_add_head(&q, &n[i]);
+ OSSL_QUEUE_WALK_DELSAFE (it, tmp, &q) {
+ ossl_qnode_del(it);
+ count++;
+ }
+ if (!TEST_size_t_eq(count, OSSL_NELEM(n))
+ || !TEST_true(ossl_queue_empty(&q)))
+ return 0;
+ for (i = 0; i < OSSL_NELEM(n); i++)
+ if (!TEST_true(ossl_qnode_unhashed(&n[i])))
+ return 0;
+ return 1;
+}
+
+/* The typed operations of DEFINE_QUEUE_OF, with elements in two queues. */
+static int test_typed_queue(void)
+{
+ OSSL_QUEUE a = OSSL_QUEUE_INIT, b = OSSL_QUEUE_INIT;
+ QITEM elem[16], *p, *pn;
+ const int fizz1[] = { 15, 12, 9, 6, 3 };
+ const int fizz2[] = { 15, 12, 9, 6, 1, 3, 2 };
+ const int buzz1[] = { 15, 10, 5 };
+ int i, na = 0, nb = 0;
+ size_t count = 0;
+
+ for (i = 0; i < (int)OSSL_NELEM(elem); i++) {
+ elem[i].n = i;
+ ossl_queue_fizz_init_elem(&elem[i]);
+ ossl_queue_buzz_init_elem(&elem[i]);
+ }
+
+ /* entry() maps a node back to its element, and NULL to NULL */
+ if (!TEST_ptr_eq(ossl_queue_fizz_entry(&elem[3].ossl_queue_fizz), &elem[3])
+ || !TEST_ptr_eq(ossl_queue_buzz_entry(&elem[3].ossl_queue_buzz),
+ &elem[3])
+ || !TEST_ptr_null(ossl_queue_fizz_entry(NULL))
+ || !TEST_ptr_null(ossl_queue_fizz_head(&a))
+ || !TEST_ptr_null(ossl_queue_buzz_head(&b)))
+ return 0;
+
+ for (i = 1; i < (int)OSSL_NELEM(elem); i++) {
+ if (i % 3 == 0) {
+ ossl_queue_fizz_add(&a, &elem[i]);
+ na++;
+ }
+ if (i % 5 == 0) {
+ ossl_queue_buzz_add(&b, &elem[i]);
+ nb++;
+ }
+ }
+
+ /* An element sits in two queues at once through its two members */
+ if (!TEST_true(ossl_queue_fizz_hashed(&elem[15]))
+ || !TEST_true(ossl_queue_buzz_hashed(&elem[15]))
+ || !TEST_true(ossl_queue_fizz_hashed(&elem[3]))
+ || !TEST_false(ossl_queue_buzz_hashed(&elem[3]))
+ || !TEST_false(ossl_queue_fizz_hashed(&elem[5]))
+ || !TEST_true(ossl_queue_buzz_hashed(&elem[5]))
+ || !TEST_ptr_eq(ossl_queue_fizz_head(&a), &elem[15])
+ || !TEST_ptr_eq(ossl_queue_fizz_next(&elem[15]), &elem[12])
+ || !TEST_ptr_null(ossl_queue_fizz_next(&elem[3]))
+ || !check_fizz_order(&a, fizz1, OSSL_NELEM(fizz1))
+ || !check_buzz_order(&b, buzz1, OSSL_NELEM(buzz1)))
+ return 0;
+
+ /* Relative insertion around the tail */
+ ossl_queue_fizz_add_before(&elem[1], &elem[3]);
+ ossl_queue_fizz_add_behind(&elem[2], &elem[3]);
+ if (!check_fizz_order(&a, fizz2, OSSL_NELEM(fizz2))
+ || !TEST_ptr_null(ossl_queue_fizz_prev(&a, &elem[15]))
+ || !TEST_ptr_eq(ossl_queue_fizz_prev(&a, &elem[1]), &elem[6])
+ || !TEST_ptr_eq(ossl_queue_fizz_prev(&a, &elem[2]), &elem[3]))
+ return 0;
+
+ ossl_queue_fizz_del(&elem[1]);
+ ossl_queue_fizz_del_init(&elem[2]);
+ ossl_queue_fizz_del_init(&elem[2]); /* a no-op once removed */
+ if (!TEST_false(ossl_queue_fizz_hashed(&elem[1]))
+ || !TEST_false(ossl_queue_fizz_hashed(&elem[2]))
+ || !check_fizz_order(&a, fizz1, OSSL_NELEM(fizz1)))
+ return 0;
+
+ /* Emptying one queue while walking it leaves the other untouched */
+ OSSL_QUEUE_FOREACH_DELSAFE (p, pn, fizz, &a) {
+ ossl_queue_fizz_del(p);
+ count++;
+ }
+ if (!TEST_size_t_eq(count, (size_t)na)
+ || !TEST_ptr_null(ossl_queue_fizz_head(&a))
+ || !TEST_false(ossl_queue_fizz_hashed(&elem[15]))
+ || !TEST_true(ossl_queue_buzz_hashed(&elem[15]))
+ || !check_buzz_order(&b, buzz1, OSSL_NELEM(buzz1)))
+ return 0;
+ count = 0;
+ OSSL_QUEUE_FOREACH (p, buzz, &b)
+ count++;
+ return TEST_size_t_eq(count, (size_t)nb);
+}
+
+/* _add_tail() and _del_keep_tail() keep a tail pointer the caller holds. */
+static int test_tail(void)
+{
+ OSSL_QUEUE q = OSSL_QUEUE_INIT;
+ QITEM elem[4], *tail = NULL;
+ const int all[] = { 0, 1, 2, 3 };
+ const int mid[] = { 1, 2 };
+ const int back[] = { 1, 2, 3 };
+ int i;
+
+ for (i = 0; i < (int)OSSL_NELEM(elem); i++) {
+ elem[i].n = i;
+ ossl_queue_fizz_init_elem(&elem[i]);
+ }
+
+ /* Appending keeps the order of insertion and moves the tail along */
+ for (i = 0; i < (int)OSSL_NELEM(elem); i++) {
+ ossl_queue_fizz_add_tail(&q, &tail, &elem[i]);
+ if (!TEST_ptr_eq(tail, &elem[i]))
+ return 0;
+ }
+ if (!check_fizz_order(&q, all, OSSL_NELEM(all)))
+ return 0;
+
+ /* Removing the tail moves it back; removing the head leaves it */
+ ossl_queue_fizz_del_keep_tail(&q, &tail, &elem[3]);
+ if (!TEST_ptr_eq(tail, &elem[2]))
+ return 0;
+ ossl_queue_fizz_del_keep_tail(&q, &tail, &elem[0]);
+ if (!TEST_ptr_eq(tail, &elem[2])
+ || !check_fizz_order(&q, mid, OSSL_NELEM(mid)))
+ return 0;
+
+ /* An append after removals still goes behind the tail */
+ ossl_queue_fizz_add_tail(&q, &tail, &elem[3]);
+ if (!TEST_ptr_eq(tail, &elem[3])
+ || !check_fizz_order(&q, back, OSSL_NELEM(back)))
+ return 0;
+
+ /* Emptied from the tail, the queue ends with no tail */
+ for (i = 3; i >= 1; i--) {
+ ossl_queue_fizz_del_keep_tail(&q, &tail, &elem[i]);
+ if (!TEST_ptr_eq(tail, i > 1 ? &elem[i - 1] : NULL))
+ return 0;
+ }
+ return TEST_true(ossl_queue_empty(&q));
+}
+
+int setup_tests(void)
+{
+ ADD_TEST(test_node_ops);
+ ADD_TEST(test_typed_queue);
+ ADD_TEST(test_tail);
+ return 1;
+}
diff --git a/test/recipes/02-test_htable.t b/test/recipes/02-test_htable.t
new file mode 100644
index 0000000000..2f07d920cd
--- /dev/null
+++ b/test/recipes/02-test_htable.t
@@ -0,0 +1,16 @@
+#! /usr/bin/env perl
+# Copyright 2026 The OpenSSL Project Authors. All Rights Reserved.
+#
+# Licensed under the Apache License 2.0 (the "License"). You may not use
+# this file except in compliance with the License. You can obtain a copy
+# in the file LICENSE in the source distribution or at
+# https://www.openssl.org/source/license.html
+
+use OpenSSL::Test;
+use OpenSSL::Test::Utils;
+
+setup("test_htable");
+
+plan tests => 1;
+
+ok(run(test(["htable_test"])));
diff --git a/test/recipes/02-test_queue.t b/test/recipes/02-test_queue.t
new file mode 100644
index 0000000000..f0e7bad834
--- /dev/null
+++ b/test/recipes/02-test_queue.t
@@ -0,0 +1,16 @@
+#! /usr/bin/env perl
+# Copyright 2026 The OpenSSL Project Authors. All Rights Reserved.
+#
+# Licensed under the Apache License 2.0 (the "License"). You may not use
+# this file except in compliance with the License. You can obtain a copy
+# in the file LICENSE in the source distribution or at
+# https://www.openssl.org/source/license.html
+
+use OpenSSL::Test;
+use OpenSSL::Test::Utils;
+
+setup("test_queue");
+
+plan tests => 1;
+
+ok(run(test(["queue_test"])));
diff --git a/test/recipes/99-test_fuzz_hashtable.t b/test/recipes/99-test_fuzz_hashtable.t
index d36aa44423..79106fb72c 100644
--- a/test/recipes/99-test_fuzz_hashtable.t
+++ b/test/recipes/99-test_fuzz_hashtable.t
@@ -9,7 +9,8 @@
use strict;
use warnings;
-use OpenSSL::Test qw/:DEFAULT srctop_file/;
+use File::Spec::Functions qw/catdir catfile/;
+use OpenSSL::Test qw/:DEFAULT srctop_dir srctop_file result_dir/;
use OpenSSL::Test::Utils;
my $fuzzer = "hashtable";
@@ -19,4 +20,53 @@ plan tests => 2; # one more due to below require_ok(...)
require_ok(srctop_file('test','recipes','fuzz.pl'));
-fuzz_ok($fuzzer);
+# The size of a record of fuzz/hashtable.c
+my $record = 11;
+
+sub read_input {
+ my ($path) = @_;
+ open(my $fh, '<', $path) or die "$path: $!";
+ binmode $fh;
+ local $/;
+ my $input = <$fh>;
+ close $fh;
+ return $input;
+}
+
+sub write_input {
+ my ($path, $input) = @_;
+ open(my $fh, '>', $path) or die "$path: $!";
+ binmode $fh;
+ print $fh $input;
+ close $fh or die "$path: $!";
+}
+
+# The corpus is that of the ossl_ht fuzzer, which took one record per input
+# and kept its table from one input to the next. This fuzzer starts every
+# input with empty tables, so such an input is one operation on tables that
+# hold nothing. Run the corpus together with one more input: the records of
+# all the others in a row, which meet what the earlier ones left in the tables.
+sub chained_corpus {
+ my ($src) = @_;
+ my $dst = catdir(result_dir(), 'corpus');
+ my $chain = '';
+
+ opendir(my $dh, $src) or return;
+ my @names = sort grep { -f catfile($src, $_) } readdir($dh);
+ closedir($dh);
+
+ mkdir $dst or die "$dst: $!";
+ foreach my $name (@names) {
+ my $input = read_input(catfile($src, $name));
+ write_input(catfile($dst, $name), $input);
+ # whole records only, so that the next input starts at a record
+ $chain .= substr($input, 0, length($input) - length($input) % $record);
+ }
+ write_input(catfile($dst, 'all-records'), $chain) if $chain ne '';
+ return $dst;
+}
+
+my $corpus = chained_corpus(srctop_dir('fuzz', 'corpora', $fuzzer));
+
+# without a corpus, as when its submodule is not checked out, this skips
+fuzz_ok($fuzzer, defined $corpus ? (corpus => $corpus) : ());
diff --git a/test/recipes/fuzz.pl b/test/recipes/fuzz.pl
index d3a7e2399e..29535e347a 100644
--- a/test/recipes/fuzz.pl
+++ b/test/recipes/fuzz.pl
@@ -249,7 +249,8 @@ sub fuzz_check_max_time {
sub fuzz_ok {
my ($f, %opts) = @_;
- my $d = srctop_dir('fuzz', 'corpora', $f);
+ # the corpus of the fuzzer, unless the caller has prepared another
+ my $d = $opts{corpus} // srctop_dir('fuzz', 'corpora', $f);
SKIP: {
skip "No directory $d", 1 unless -d $d;
diff --git a/test/timing_namemap_x509store.c b/test/timing_namemap_x509store.c
new file mode 100644
index 0000000000..f5645b7642
--- /dev/null
+++ b/test/timing_namemap_x509store.c
@@ -0,0 +1,682 @@
+/*
+ * Copyright 2026 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * Times the two users of the library's internal hash table: the namemap
+ * (name -> number, read without a lock on every fetch by name) and the
+ * X509_STORE (name -> objects, under the store's lock). It only uses
+ * interfaces that do not depend on how either is implemented, so the same
+ * source measures any two versions of the library against each other.
+ *
+ * Not run by "make test". Each line of output is "<case> <value> <unit>",
+ * the best of a few repetitions.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <openssl/crypto.h>
+#include <openssl/evp.h>
+#include <openssl/kdf.h>
+#include <openssl/x509.h>
+#include <openssl/x509_vfy.h>
+
+#include "internal/namemap.h"
+#include "internal/nelem.h"
+#include "internal/time.h"
+
+/*
+ * Without threads, threadstest.h runs a "thread" to completion inside
+ * run_thread(), which the readers here cannot do: they wait for the start
+ * signal that is given once all of them have been started. The cases with
+ * several readers are left out of such a build.
+ */
+#if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG)
+#define TIMING_THREADS
+#include "threadstest.h"
+#endif
+
+#define REPEATS 7
+
+static uint64_t now_ns(void)
+{
+ return ossl_time2ticks(ossl_time_now()) / (OSSL_TIME_SECOND / 1000000000);
+}
+
+static void report(const char *name, double value, const char *unit)
+{
+ printf("%-34s %12.2f %s\n", name, value, unit);
+ fflush(stdout);
+}
+
+static void die(const char *what)
+{
+ fprintf(stderr, "FAILED: %s\n", what);
+ exit(1);
+}
+
+/* A cheap deterministic sequence, so every run visits keys the same way. */
+static uint32_t next_rand(uint32_t *state)
+{
+ *state = *state * 1664525u + 1013904223u;
+ return *state >> 8;
+}
+
+/*-
+ * Namemap
+ * =======
+ */
+
+static char **nm_names;
+static size_t nm_num_names, nm_cap_names;
+static OSSL_NAMEMAP *nm_shared;
+/* The sum of every number looked up, which runs into the billions */
+static uint64_t nm_sink;
+
+static void nm_collect(const char *name, void *arg)
+{
+ if (nm_num_names == nm_cap_names) {
+ nm_cap_names = nm_cap_names == 0 ? 1024 : nm_cap_names * 2;
+ nm_names = realloc(nm_names, nm_cap_names * sizeof(*nm_names));
+ if (nm_names == NULL)
+ die("realloc");
+ }
+ if ((nm_names[nm_num_names++] = strdup(name)) == NULL)
+ die("strdup");
+}
+
+static void md_cb(EVP_MD *m, void *arg)
+{
+}
+
+static void cipher_cb(EVP_CIPHER *c, void *arg)
+{
+}
+
+static void mac_cb(EVP_MAC *m, void *arg)
+{
+}
+
+static void kdf_cb(EVP_KDF *k, void *arg)
+{
+}
+
+static void keymgmt_cb(EVP_KEYMGMT *k, void *arg)
+{
+}
+
+static void sig_cb(EVP_SIGNATURE *s, void *arg)
+{
+}
+
+static void kem_cb(EVP_KEM *k, void *arg)
+{
+}
+
+static void kex_cb(EVP_KEYEXCH *k, void *arg)
+{
+}
+
+static void rand_cb(EVP_RAND *r, void *arg)
+{
+}
+
+/* Every name the default library context knows once it is fully loaded. */
+static void nm_load_real_names(void)
+{
+ int number;
+
+ EVP_MD_do_all_provided(NULL, md_cb, NULL);
+ EVP_CIPHER_do_all_provided(NULL, cipher_cb, NULL);
+ EVP_MAC_do_all_provided(NULL, mac_cb, NULL);
+ EVP_KDF_do_all_provided(NULL, kdf_cb, NULL);
+ EVP_KEYMGMT_do_all_provided(NULL, keymgmt_cb, NULL);
+ EVP_SIGNATURE_do_all_provided(NULL, sig_cb, NULL);
+ EVP_KEM_do_all_provided(NULL, kem_cb, NULL);
+ EVP_KEYEXCH_do_all_provided(NULL, kex_cb, NULL);
+ EVP_RAND_do_all_provided(NULL, rand_cb, NULL);
+
+ nm_shared = ossl_namemap_stored(NULL);
+ if (nm_shared == NULL)
+ die("ossl_namemap_stored");
+ for (number = 1; ossl_namemap_doall_names(nm_shared, number, nm_collect,
+ NULL);
+ number++)
+ continue;
+ if (nm_num_names == 0)
+ die("no names");
+}
+
+#define NM_LOOKUPS 2000000
+
+/* ns per lookup of names that exist, visited in a scattered order */
+static double nm_time_hits(void)
+{
+ uint32_t seed = 12345;
+ uint64_t start, sum = 0;
+ int i;
+
+ start = now_ns();
+ for (i = 0; i < NM_LOOKUPS; i++)
+ sum += ossl_namemap_name2num(nm_shared,
+ nm_names[next_rand(&seed) % nm_num_names]);
+ start = now_ns() - start;
+ if (sum == 0)
+ die("namemap hits");
+ nm_sink += sum;
+ return (double)start / NM_LOOKUPS;
+}
+
+static double nm_time_one_hot(void)
+{
+ uint64_t start, sum = 0;
+ int i;
+
+ start = now_ns();
+ for (i = 0; i < NM_LOOKUPS; i++)
+ sum += ossl_namemap_name2num(nm_shared, "SHA2-256");
+ start = now_ns() - start;
+ if (sum == 0)
+ die("namemap SHA2-256");
+ nm_sink += sum;
+ return (double)start / NM_LOOKUPS;
+}
+
+static double nm_time_misses(void)
+{
+ static const char *const absent[] = {
+ "no-such-algorithm", "SHA2-257", "AES-512-GCM", "x", "RSA-PSS-PSS",
+ "ML-KEM-2048", "id-absent-name-with-a-rather-long-tail-0123456789",
+ "CHACHA21"
+ };
+ uint64_t start, sum = 0;
+ int i;
+
+ start = now_ns();
+ for (i = 0; i < NM_LOOKUPS; i++)
+ sum += ossl_namemap_name2num(nm_shared, absent[i & 7]);
+ start = now_ns() - start;
+ if (sum != 0)
+ die("namemap misses");
+ return (double)start / NM_LOOKUPS;
+}
+
+static double nm_time_fetch(void)
+{
+ uint64_t start;
+ int i;
+ const int n = 500000;
+
+ start = now_ns();
+ for (i = 0; i < n; i++) {
+ EVP_MD *md = EVP_MD_fetch(NULL, "SHA2-256", NULL);
+
+ if (md == NULL)
+ die("EVP_MD_fetch");
+ EVP_MD_free(md);
+ }
+ return (double)(now_ns() - start) / n;
+}
+
+#ifdef TIMING_THREADS
+/* Readers on all threads at once: total lookups per second, in millions. */
+#define MAX_THREADS 8
+static CRYPTO_RWLOCK *mt_lock;
+static int mt_go, mt_ready;
+
+static void mt_wait_for_start(void)
+{
+ int go = 0, dummy;
+
+ (void)CRYPTO_atomic_add(&mt_ready, 1, &dummy, mt_lock);
+ while (!go)
+ if (!CRYPTO_atomic_load_int(&mt_go, &go, mt_lock))
+ die("atomic load");
+}
+
+static uint64_t mt_run(int nthreads, void (*fn)(void))
+{
+ thread_t t[MAX_THREADS];
+ int i, ready = 0;
+ uint64_t start;
+
+ mt_go = 0;
+ mt_ready = 0;
+ for (i = 0; i < nthreads; i++)
+ if (!run_thread(&t[i], fn))
+ die("run_thread");
+ while (ready < nthreads)
+ if (!CRYPTO_atomic_load_int(&mt_ready, &ready, mt_lock))
+ die("atomic load");
+ start = now_ns();
+ if (!CRYPTO_atomic_store_int(&mt_go, 1, mt_lock))
+ die("atomic store");
+ for (i = 0; i < nthreads; i++)
+ if (!wait_for_thread(t[i]))
+ die("wait_for_thread");
+ return now_ns() - start;
+}
+
+/*
+ * Report "<prefix>.threads=<n>" for |fn|, a reader doing |lookups| of them,
+ * on every |step|'th of 1, 2, 4 and 8 threads: the best of |repeats| runs.
+ */
+static void mt_report(const char *prefix, void (*fn)(void), int lookups,
+ int repeats, size_t step)
+{
+ static const int threads[] = { 1, 2, 4, MAX_THREADS };
+ char label[96]; /* a 63 character prefix, ".threads=" and an int */
+ double v, b;
+ size_t i;
+ int r;
+
+ if ((mt_lock = CRYPTO_THREAD_lock_new()) == NULL)
+ die("lock");
+ for (i = 0; i < OSSL_NELEM(threads); i += step) {
+ b = 0;
+ for (r = 0; r < repeats; r++) {
+ v = (double)threads[i] * lookups * 1000.0
+ / (double)mt_run(threads[i], fn);
+ if (v > b)
+ b = v;
+ }
+ snprintf(label, sizeof(label), "%s.threads=%d", prefix, threads[i]);
+ report(label, b, "Mlookups/s");
+ }
+ CRYPTO_THREAD_lock_free(mt_lock);
+ mt_lock = NULL;
+}
+
+static void nm_reader(void)
+{
+ uint32_t seed = (uint32_t)(uintptr_t)&seed;
+ uint64_t sum = 0;
+ int i;
+
+ mt_wait_for_start();
+ for (i = 0; i < NM_LOOKUPS; i++)
+ sum += ossl_namemap_name2num(nm_shared,
+ nm_names[next_rand(&seed) % nm_num_names]);
+ if (sum == 0)
+ die("namemap mt hits");
+}
+#endif /* TIMING_THREADS */
+
+/* us to register |count| new names (and as many aliases) in a new namemap */
+static double nm_time_add(int count, int *failed)
+{
+ OSSL_NAMEMAP *nm = ossl_namemap_new(NULL);
+ char name[48];
+ uint64_t start;
+ int i, num;
+
+ if (nm == NULL)
+ die("ossl_namemap_new");
+ *failed = 0;
+ start = now_ns();
+ for (i = 0; i < count; i++) {
+ snprintf(name, sizeof(name), "Algorithm-Name-%d", i);
+ if ((num = ossl_namemap_add_name(nm, 0, name)) == 0) {
+ *failed = i + 1;
+ break;
+ }
+ snprintf(name, sizeof(name), "1.3.6.1.4.1.99999.%d", i);
+ if (ossl_namemap_add_name(nm, num, name) != num) {
+ *failed = i + 1;
+ break;
+ }
+ }
+ start = now_ns() - start;
+ ossl_namemap_free(nm);
+ return (double)start / 1000;
+}
+
+/* ns per lookup in a namemap holding |count| names and as many aliases */
+static double nm_time_sized_hits(int count)
+{
+ OSSL_NAMEMAP *nm = ossl_namemap_new(NULL);
+ char (*names)[48] = malloc((size_t)count * sizeof(*names));
+ uint32_t seed = 777;
+ uint64_t start, sum = 0;
+ int i, num;
+
+ if (nm == NULL || names == NULL)
+ die("sized namemap");
+ for (i = 0; i < count; i++) {
+ snprintf(names[i], sizeof(names[i]), "Algorithm-Name-%d", i);
+ if ((num = ossl_namemap_add_name(nm, 0, names[i])) == 0)
+ die("sized namemap add");
+ snprintf(names[i], sizeof(names[i]), "1.3.6.1.4.1.99999.%d", i);
+ if (ossl_namemap_add_name(nm, num, names[i]) != num)
+ die("sized namemap alias");
+ }
+ start = now_ns();
+ for (i = 0; i < NM_LOOKUPS; i++)
+ sum += ossl_namemap_name2num(nm, names[next_rand(&seed) % count]);
+ start = now_ns() - start;
+ if (sum == 0)
+ die("sized namemap hits");
+ nm_sink += sum;
+ free(names);
+ ossl_namemap_free(nm);
+ return (double)start / NM_LOOKUPS;
+}
+
+/*-
+ * X509_STORE
+ * ==========
+ */
+
+static X509 **xs_certs;
+static X509_NAME **xs_absent;
+static int xs_num_certs;
+#define XS_ABSENT 64
+#define XS_SAME_NAME 4
+
+static X509_NAME *xs_make_name(const char *cn_prefix, int i)
+{
+ X509_NAME *nm = X509_NAME_new();
+ char cn[64];
+
+ snprintf(cn, sizeof(cn), "%s %d", cn_prefix, i);
+ if (nm == NULL
+ || !X509_NAME_add_entry_by_txt(nm, "C", MBSTRING_ASC,
+ (const unsigned char *)"CZ", -1, -1, 0)
+ || !X509_NAME_add_entry_by_txt(nm, "O", MBSTRING_ASC,
+ (const unsigned char *)"Timing Trust Services", -1, -1, 0)
+ || !X509_NAME_add_entry_by_txt(nm, "CN", MBSTRING_ASC,
+ (const unsigned char *)cn, -1, -1, 0))
+ die("X509_NAME");
+ return nm;
+}
+
+/*
+ * |n| unsigned certificates. Every XS_SAME_NAME'th one shares its subject
+ * with its predecessor, as cross-signed and re-issued CA certificates do.
+ */
+static void xs_make_certs(int n)
+{
+ int i;
+
+ xs_certs = calloc(n, sizeof(*xs_certs));
+ xs_absent = calloc(XS_ABSENT, sizeof(*xs_absent));
+ if (xs_certs == NULL || xs_absent == NULL)
+ die("calloc");
+ for (i = 0; i < n; i++) {
+ X509 *x = X509_new();
+ X509_NAME *nm = xs_make_name("Timing Root CA",
+ i % XS_SAME_NAME == XS_SAME_NAME - 1 ? i - 1 : i);
+
+ if (x == NULL
+ || !X509_set_subject_name(x, nm)
+ || !X509_set_issuer_name(x, nm)
+ || !ASN1_INTEGER_set(X509_get_serialNumber(x), i + 1))
+ die("X509");
+ X509_NAME_free(nm);
+ xs_certs[i] = x;
+ }
+ for (i = 0; i < XS_ABSENT; i++)
+ xs_absent[i] = xs_make_name("Unknown Issuing CA", i);
+ xs_num_certs = n;
+}
+
+static void xs_free_certs(void)
+{
+ int i;
+
+ for (i = 0; i < xs_num_certs; i++)
+ X509_free(xs_certs[i]);
+ for (i = 0; i < XS_ABSENT; i++)
+ X509_NAME_free(xs_absent[i]);
+ free(xs_certs);
+ free(xs_absent);
+}
+
+static X509_STORE *xs_fill(int n)
+{
+ X509_STORE *store = X509_STORE_new();
+ int i;
+
+ if (store == NULL)
+ die("X509_STORE_new");
+ for (i = 0; i < n; i++)
+ if (!X509_STORE_add_cert(store, xs_certs[i]))
+ die("X509_STORE_add_cert");
+ return store;
+}
+
+/* ns per certificate added to a new store, including freeing the store */
+static double xs_time_add(int n)
+{
+ uint64_t start = now_ns();
+ X509_STORE *store = xs_fill(n);
+
+ X509_STORE_free(store);
+ return (double)(now_ns() - start) / n;
+}
+
+static double xs_time_new_free(void)
+{
+ uint64_t start = now_ns();
+ int i;
+ const int n = 200000;
+
+ for (i = 0; i < n; i++) {
+ X509_STORE *store = X509_STORE_new();
+
+ if (store == NULL)
+ die("X509_STORE_new");
+ X509_STORE_free(store);
+ }
+ return (double)(now_ns() - start) / n;
+}
+
+static X509_STORE *xs_shared;
+static int xs_shared_n;
+#define XS_LOOKUPS 1000000
+
+static void xs_lookups(int hits, uint32_t seed)
+{
+ X509_STORE_CTX *ctx = X509_STORE_CTX_new();
+ X509_OBJECT *obj = X509_OBJECT_new();
+ int i, found = 0;
+
+ if (ctx == NULL || obj == NULL
+ || !X509_STORE_CTX_init(ctx, xs_shared, NULL, NULL))
+ die("X509_STORE_CTX");
+ for (i = 0; i < XS_LOOKUPS; i++) {
+ const X509_NAME *nm = hits
+ ? X509_get_subject_name(xs_certs[next_rand(&seed) % xs_shared_n])
+ : xs_absent[next_rand(&seed) % XS_ABSENT];
+
+ if (X509_STORE_CTX_get_by_subject(ctx, X509_LU_X509, nm, obj)) {
+ found++;
+ /* |obj| is reused: drop the reference the lookup took */
+ X509_free(X509_OBJECT_get0_X509(obj));
+ }
+ }
+ if (found != (hits ? XS_LOOKUPS : 0))
+ die("X509_STORE lookups");
+ /* The references are gone already; free the shell only */
+ OPENSSL_free(obj);
+ X509_STORE_CTX_free(ctx);
+}
+
+static double xs_time_lookups(int hits)
+{
+ uint64_t start = now_ns();
+
+ xs_lookups(hits, 4242);
+ return (double)(now_ns() - start) / XS_LOOKUPS;
+}
+
+#ifdef TIMING_THREADS
+static void xs_reader(void)
+{
+ uint32_t seed = (uint32_t)(uintptr_t)&seed;
+
+ mt_wait_for_start();
+ xs_lookups(1, seed);
+}
+#endif
+
+/* ns per name for collecting all the certificates of one subject */
+static double xs_time_get1_certs(void)
+{
+ X509_STORE_CTX *ctx = X509_STORE_CTX_new();
+ uint32_t seed = 99;
+ uint64_t start;
+ int i;
+ const int n = 300000;
+
+ if (ctx == NULL || !X509_STORE_CTX_init(ctx, xs_shared, NULL, NULL))
+ die("X509_STORE_CTX");
+ start = now_ns();
+ for (i = 0; i < n; i++) {
+ STACK_OF(X509) *sk = X509_STORE_CTX_get1_certs(ctx,
+ X509_get_subject_name(xs_certs[next_rand(&seed) % xs_shared_n]));
+
+ if (sk_X509_num(sk) < 1)
+ die("X509_STORE_CTX_get1_certs");
+ OSSL_STACK_OF_X509_free(sk);
+ }
+ start = now_ns() - start;
+ X509_STORE_CTX_free(ctx);
+ return (double)start / n;
+}
+
+/* ns per certificate for listing the whole store */
+static double xs_time_all_certs(void)
+{
+ uint64_t start = now_ns();
+ int i, reps = 1 + 200000 / xs_shared_n;
+
+ for (i = 0; i < reps; i++) {
+ STACK_OF(X509) *sk = X509_STORE_get1_all_certs(xs_shared);
+
+ if (sk_X509_num(sk) != xs_shared_n)
+ die("X509_STORE_get1_all_certs");
+ OSSL_STACK_OF_X509_free(sk);
+ }
+ return (double)(now_ns() - start) / ((double)reps * xs_shared_n);
+}
+
+/*-
+ * Driver
+ * ======
+ */
+
+static double best(double (*fn)(void))
+{
+ double v, b = fn();
+ int i;
+
+ for (i = 1; i < REPEATS; i++)
+ if ((v = fn()) < b)
+ b = v;
+ return b;
+}
+
+static int cur_arg;
+static double call_xs_add(void)
+{
+ return xs_time_add(cur_arg);
+}
+
+static double call_xs_hits(void)
+{
+ return xs_time_lookups(1);
+}
+
+static double call_xs_misses(void)
+{
+ return xs_time_lookups(0);
+}
+
+static double call_nm_sized(void)
+{
+ return nm_time_sized_hits(cur_arg);
+}
+
+int main(void)
+{
+ static const int nm_sizes[] = { 250, 900 };
+ static const int nm_add_sizes[] = { 250, 900, 5000 };
+ static const int xs_sizes[] = { 150, 2000, 50000 };
+ char label[64];
+ size_t i, j;
+ double v, b;
+ int failed;
+
+ nm_load_real_names();
+ report("namemap.names", (double)nm_num_names, "names");
+ report("namemap.hit", best(nm_time_hits), "ns/lookup");
+ report("namemap.hit.sha2-256", best(nm_time_one_hot), "ns/lookup");
+ report("namemap.miss", best(nm_time_misses), "ns/lookup");
+ report("evp_md_fetch.sha2-256", best(nm_time_fetch), "ns/fetch");
+#ifdef TIMING_THREADS
+ mt_report("namemap.hit", nm_reader, NM_LOOKUPS, REPEATS, 1);
+#endif
+ for (i = 0; i < OSSL_NELEM(nm_sizes); i++) {
+ cur_arg = nm_sizes[i];
+ snprintf(label, sizeof(label), "namemap.hit.names=%d", 2 * cur_arg);
+ report(label, best(call_nm_sized), "ns/lookup");
+ }
+ for (i = 0; i < OSSL_NELEM(nm_add_sizes); i++) {
+ b = -1;
+ for (failed = 0, j = 0; j < REPEATS; j++) {
+ v = nm_time_add(nm_add_sizes[i], &failed);
+ if (failed)
+ break;
+ if (b < 0 || v < b)
+ b = v;
+ }
+ snprintf(label, sizeof(label), "namemap.add.names=%d",
+ 2 * nm_add_sizes[i]);
+ if (failed)
+ printf("%-34s %12s (failed at name pair %d)\n", label, "n/a",
+ failed);
+ else
+ report(label, b * 1000 / (2 * nm_add_sizes[i]), "ns/name");
+ }
+
+ report("x509_store.new+free", best(xs_time_new_free), "ns");
+ xs_make_certs(xs_sizes[OSSL_NELEM(xs_sizes) - 1]);
+ for (i = 0; i < OSSL_NELEM(xs_sizes); i++) {
+ cur_arg = xs_shared_n = xs_sizes[i];
+ snprintf(label, sizeof(label), "x509_store.add.certs=%d", cur_arg);
+ report(label, best(call_xs_add), "ns/cert");
+
+ xs_shared = xs_fill(xs_shared_n);
+ snprintf(label, sizeof(label), "x509_store.hit.certs=%d", cur_arg);
+ report(label, best(call_xs_hits), "ns/lookup");
+ snprintf(label, sizeof(label), "x509_store.miss.certs=%d", cur_arg);
+ report(label, best(call_xs_misses), "ns/lookup");
+ snprintf(label, sizeof(label), "x509_store.get1_certs.certs=%d",
+ cur_arg);
+ report(label, best(xs_time_get1_certs), "ns/name");
+ snprintf(label, sizeof(label), "x509_store.all_certs.certs=%d",
+ cur_arg);
+ report(label, best(xs_time_all_certs), "ns/cert");
+#ifdef TIMING_THREADS
+ if (i == 1) {
+ snprintf(label, sizeof(label), "x509_store.hit.certs=%d", cur_arg);
+ mt_report(label, xs_reader, XS_LOOKUPS, 3, 2);
+ }
+#endif
+ X509_STORE_free(xs_shared);
+ }
+ xs_free_certs();
+
+ for (i = 0; i < nm_num_names; i++)
+ free(nm_names[i]);
+ free(nm_names);
+ return nm_sink == 0;
+}
diff --git a/test/x509_load_cert_file_test.c b/test/x509_load_cert_file_test.c
index 1d3eb4bd75..3d234306d0 100644
--- a/test/x509_load_cert_file_test.c
+++ b/test/x509_load_cert_file_test.c
@@ -283,6 +283,166 @@ err:
return ret;
}
+/*
+ * Objects that share a name are kept in the order they were added, whatever
+ * the type of the first of them, and the store's getters list each once.
+ */
+static int test_store_same_name_order(void)
+{
+ X509_NAME *name = NULL, *other = NULL;
+ X509 *certs[4] = { NULL, NULL, NULL, NULL }, *lone = NULL;
+ X509_CRL *new_crl = NULL;
+ X509_STORE *store = NULL;
+ X509_STORE_CTX *ctx = NULL;
+ X509_OBJECT *obj = NULL;
+ STACK_OF(X509) *got = NULL, *all = NULL;
+ STACK_OF(X509_CRL) *crls = NULL;
+ STACK_OF(X509_OBJECT) *objs = NULL;
+ size_t i;
+ int ret = 0;
+
+ if (!TEST_ptr(name = X509_NAME_new())
+ || !TEST_true(X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
+ (unsigned char *)"same.test", -1, -1, 0))
+ || !TEST_ptr(other = X509_NAME_new())
+ || !TEST_true(X509_NAME_add_entry_by_txt(other, "CN", MBSTRING_ASC,
+ (unsigned char *)"other.test", -1, -1, 0))
+ || !TEST_ptr(new_crl = X509_CRL_new())
+ || !TEST_true(X509_CRL_set_issuer_name(new_crl, name))
+ || !TEST_ptr(lone = X509_new())
+ || !TEST_true(X509_set_subject_name(lone, other))
+ || !TEST_ptr(ctx = X509_STORE_CTX_new())
+ || !TEST_ptr(store = X509_STORE_new())
+ || !TEST_true(X509_STORE_CTX_init(ctx, store, NULL, NULL)))
+ goto err;
+ for (i = 0; i < OSSL_NELEM(certs); i++)
+ if (!TEST_ptr(certs[i] = X509_new())
+ || !TEST_true(X509_set_subject_name(certs[i], name))
+ || !TEST_true(ASN1_INTEGER_set(X509_get_serialNumber(certs[i]),
+ (long)i + 1)))
+ goto err;
+
+ /* The CRL is the first object of its name; no certificate is there yet */
+ if (!TEST_true(X509_STORE_add_crl(store, new_crl))
+ || !TEST_ptr_null(obj = X509_STORE_CTX_get_obj_by_subject(ctx,
+ X509_LU_X509, name))
+ || !TEST_true(X509_STORE_add_cert(store, lone)))
+ goto err;
+ for (i = 0; i < OSSL_NELEM(certs); i++)
+ if (!TEST_true(X509_STORE_add_cert(store, certs[i])))
+ goto err;
+ /* Adding what is there, wherever it is among its name, adds nothing */
+ if (!TEST_true(X509_STORE_add_crl(store, new_crl))
+ || !TEST_true(X509_STORE_add_cert(store, certs[0]))
+ || !TEST_true(X509_STORE_add_cert(store, certs[2]))
+ || !TEST_true(X509_STORE_add_cert(store, certs[3]))
+ || !TEST_true(X509_STORE_add_cert(store, lone)))
+ goto err;
+
+ if (!TEST_ptr(got = X509_STORE_CTX_get1_certs(ctx, name))
+ || !TEST_int_eq(sk_X509_num(got), (int)OSSL_NELEM(certs)))
+ goto err;
+ for (i = 0; i < OSSL_NELEM(certs); i++)
+ if (!TEST_ptr_eq(sk_X509_value(got, (int)i), certs[i]))
+ goto err;
+
+ /* A lookup by subject finds the first certificate, past the CRL */
+ if (!TEST_ptr(obj = X509_STORE_CTX_get_obj_by_subject(ctx, X509_LU_X509,
+ name))
+ || !TEST_ptr_eq(X509_OBJECT_get0_X509(obj), certs[0])
+ || !TEST_ptr(crls = X509_STORE_CTX_get1_crls(ctx, name))
+ || !TEST_int_eq(sk_X509_CRL_num(crls), 1)
+ || !TEST_ptr_eq(sk_X509_CRL_value(crls, 0), new_crl)
+ || !TEST_ptr(all = X509_STORE_get1_all_certs(store))
+ || !TEST_int_eq(sk_X509_num(all), (int)OSSL_NELEM(certs) + 1)
+ || !TEST_ptr(objs = X509_STORE_get1_objects(store))
+ || !TEST_int_eq(sk_X509_OBJECT_num(objs), (int)OSSL_NELEM(certs) + 2))
+ goto err;
+
+ ret = 1;
+
+err:
+ X509_OBJECT_free(obj);
+ OSSL_STACK_OF_X509_free(got);
+ OSSL_STACK_OF_X509_free(all);
+ sk_X509_CRL_pop_free(crls, X509_CRL_free);
+ sk_X509_OBJECT_pop_free(objs, X509_OBJECT_free);
+ X509_STORE_CTX_free(ctx);
+ X509_STORE_free(store);
+ for (i = 0; i < OSSL_NELEM(certs); i++)
+ X509_free(certs[i]);
+ X509_free(lone);
+ X509_CRL_free(new_crl);
+ X509_NAME_free(name);
+ X509_NAME_free(other);
+ return ret;
+}
+
+/* A lookup method that reports every name found and adds none to the store */
+static int found_not_cached(X509_LOOKUP *lu, X509_LOOKUP_TYPE type,
+ const X509_NAME *name, X509_OBJECT *ret)
+{
+ return 1;
+}
+
+static int check_get1_empty(X509_STORE_CTX *ctx, const X509_NAME *name)
+{
+ STACK_OF(X509) *certs = NULL;
+ STACK_OF(X509_CRL) *crls = NULL;
+ int ret;
+
+ ret = TEST_ptr(certs = X509_STORE_CTX_get1_certs(ctx, name))
+ && TEST_int_eq(sk_X509_num(certs), 0)
+ && TEST_ptr(crls = X509_STORE_CTX_get1_crls(ctx, name))
+ && TEST_int_eq(sk_X509_CRL_num(crls), 0);
+ OSSL_STACK_OF_X509_free(certs);
+ sk_X509_CRL_pop_free(crls, X509_CRL_free);
+ return ret;
+}
+
+/*
+ * A name that a lookup method reports found, but that the store holds nothing
+ * under, gets an empty stack and not the NULL of a failure, in both
+ * representations of the store.
+ */
+static int test_store_get1_not_cached(void)
+{
+ X509_LOOKUP_METHOD *meth = NULL;
+ X509_NAME *name = NULL;
+ X509_STORE *store = NULL;
+ X509_STORE_CTX *ctx = NULL;
+ int ret = 0;
+
+ if (!TEST_ptr(meth = X509_LOOKUP_meth_new("found, not cached"))
+ || !TEST_true(X509_LOOKUP_meth_set_get_by_subject(meth,
+ found_not_cached))
+ || !TEST_ptr(name = X509_NAME_new())
+ || !TEST_true(X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
+ (unsigned char *)"absent.test", -1, -1, 0))
+ || !TEST_ptr(store = X509_STORE_new())
+ || !TEST_ptr(X509_STORE_add_lookup(store, meth))
+ || !TEST_ptr(ctx = X509_STORE_CTX_new())
+ || !TEST_true(X509_STORE_CTX_init(ctx, store, NULL, NULL))
+ || !check_get1_empty(ctx, name))
+ goto err;
+
+#ifndef OPENSSL_NO_DEPRECATED_4_0
+ /* The same of a store converted to a stack of objects */
+ if (!TEST_ptr(X509_STORE_get0_objects(store))
+ || !check_get1_empty(ctx, name))
+ goto err;
+#endif
+
+ ret = 1;
+
+err:
+ X509_STORE_CTX_free(ctx);
+ X509_STORE_free(store);
+ X509_LOOKUP_meth_free(meth);
+ X509_NAME_free(name);
+ return ret;
+}
+
/*
* Test to trigger memory failures in X509_STORE_add_cert.
*/
@@ -376,6 +536,8 @@ int setup_tests(void)
ADD_TEST(test_load_cert_file);
ADD_TEST(test_load_same_cn_certs);
+ ADD_TEST(test_store_same_name_order);
+ ADD_TEST(test_store_get1_not_cached);
ADD_MFAIL_NO_CHECK_TEST(test_x509_pem_read_mfail);
ADD_MFAIL_TEST(test_x509_store_add_mfail);
ADD_MFAIL_TEST(test_x509_get1_objects_mfail);
diff --git a/test/x509_test.c b/test/x509_test.c
index 5f720bcf2b..1664f00031 100644
--- a/test/x509_test.c
+++ b/test/x509_test.c
@@ -852,6 +852,144 @@ end:
return ret;
}
+static X509_NAME *canon_hash_name(const char *org, const char *cn)
+{
+ X509_NAME *nm = X509_NAME_new();
+
+ if (nm == NULL
+ || !X509_NAME_add_entry_by_txt(nm, "O", MBSTRING_ASC,
+ (const unsigned char *)org, -1, -1, 0)
+ || !X509_NAME_add_entry_by_txt(nm, "CN", MBSTRING_ASC,
+ (const unsigned char *)cn, -1, -1, 0)) {
+ X509_NAME_free(nm);
+ return NULL;
+ }
+ return nm;
+}
+
+/* Whether |store| holds a certificate with the subject |nm|. */
+static int canon_hash_lookup(X509_STORE *store, const X509_NAME *nm)
+{
+ X509_STORE_CTX *ctx = X509_STORE_CTX_new();
+ X509_OBJECT *obj = X509_OBJECT_new();
+ int found = -1;
+
+ if (ctx != NULL && obj != NULL
+ && X509_STORE_CTX_init(ctx, store, NULL, NULL))
+ found = X509_STORE_CTX_get_by_subject(ctx, X509_LU_X509, nm, obj);
+ X509_OBJECT_free(obj);
+ X509_STORE_CTX_free(ctx);
+ return found;
+}
+
+/*
+ * The hash kept with a name's canonical encoding follows that encoding: equal
+ * for names that compare equal, renewed when the name changes, and it is
+ * what an X509_STORE finds the name by.
+ */
+static int test_x509_name_canon_hash(void)
+{
+ X509_NAME *a = NULL, *b = NULL, *c = NULL, *dup = NULL;
+ X509_NAME *empty1 = NULL, *empty2 = NULL;
+ X509_NAME_ENTRY *ne = NULL;
+ X509 *cert = NULL, *anon = NULL;
+ X509_STORE *store = NULL;
+ uint64_t hash_a;
+ int ret = 0;
+
+ /* |a| and |b| differ in case and white space only */
+ if (!TEST_ptr(a = canon_hash_name("Example Org", "Test Name"))
+ || !TEST_ptr(b = canon_hash_name("example ORG", " test name "))
+ || !TEST_ptr(c = canon_hash_name("Example Org", "Test Name 2"))
+ || !TEST_ptr(empty1 = X509_NAME_new())
+ || !TEST_ptr(empty2 = X509_NAME_new())
+ || !TEST_int_gt(i2d_X509_NAME(a, NULL), 0)
+ || !TEST_int_gt(i2d_X509_NAME(b, NULL), 0)
+ || !TEST_int_gt(i2d_X509_NAME(c, NULL), 0)
+ || !TEST_int_gt(i2d_X509_NAME(empty1, NULL), 0)
+ || !TEST_int_gt(i2d_X509_NAME(empty2, NULL), 0)
+ || !TEST_ptr(dup = X509_NAME_dup(a)))
+ goto end;
+
+ hash_a = a->canon_hash;
+ if (!TEST_int_eq(X509_NAME_cmp(a, b), 0)
+ || !TEST_uint64_t_eq(b->canon_hash, hash_a)
+ || !TEST_uint64_t_eq(dup->canon_hash, hash_a)
+ || !TEST_uint64_t_ne(c->canon_hash, hash_a)
+ || !TEST_ptr_null(empty1->canon_enc)
+ || !TEST_uint64_t_eq(empty1->canon_hash, empty2->canon_hash)
+ || !TEST_uint64_t_ne(empty1->canon_hash, hash_a))
+ goto end;
+
+ /* A changed name gets a new hash, and the old one back when restored */
+ if (!TEST_true(X509_NAME_add_entry_by_txt(b, "OU", MBSTRING_ASC,
+ (const unsigned char *)"Unit", -1, -1, 0))
+ || !TEST_int_gt(i2d_X509_NAME(b, NULL), 0)
+ || !TEST_uint64_t_ne(b->canon_hash, hash_a)
+ || !TEST_ptr(ne = X509_NAME_delete_entry(b, 2))
+ || !TEST_int_gt(i2d_X509_NAME(b, NULL), 0)
+ || !TEST_uint64_t_eq(b->canon_hash, hash_a))
+ goto end;
+ X509_NAME_ENTRY_free(ne);
+ ne = NULL;
+
+ /* An emptied name hashes as an empty one */
+ while (X509_NAME_entry_count(dup) > 0)
+ X509_NAME_ENTRY_free(X509_NAME_delete_entry(dup, 0));
+ if (!TEST_int_gt(i2d_X509_NAME(dup, NULL), 0)
+ || !TEST_uint64_t_eq(dup->canon_hash, empty1->canon_hash))
+ goto end;
+
+ /* The store finds certificates by any name equal to their subject */
+ if (!TEST_ptr(cert = X509_new())
+ || !TEST_ptr(anon = X509_new())
+ || !TEST_ptr(store = X509_STORE_new())
+ || !TEST_true(X509_set_subject_name(cert, a))
+ || !TEST_true(ASN1_INTEGER_set(X509_get_serialNumber(anon), 2))
+ || !TEST_int_eq(canon_hash_lookup(store, a), 0)
+ || !TEST_true(X509_STORE_add_cert(store, cert))
+ || !TEST_int_eq(canon_hash_lookup(store, a), 1)
+ || !TEST_int_eq(canon_hash_lookup(store, b), 1)
+ || !TEST_int_eq(canon_hash_lookup(store, c), 0)
+ || !TEST_int_eq(canon_hash_lookup(store, empty1), 0)
+ || !TEST_true(X509_STORE_add_cert(store, anon))
+ || !TEST_int_eq(canon_hash_lookup(store, empty1), 1)
+ || !TEST_int_eq(canon_hash_lookup(store, dup), 1))
+ goto end;
+
+ /*
+ * A name changed since it was last encoded carries a stale hash until
+ * the store re-encodes it for the lookup.
+ */
+ if (!TEST_true(X509_NAME_add_entry_by_txt(b, "OU", MBSTRING_ASC,
+ (const unsigned char *)"Unit", -1, -1, 0))
+ || !TEST_uint64_t_eq(b->canon_hash, hash_a)
+ || !TEST_int_eq(canon_hash_lookup(store, b), 0)
+ || !TEST_uint64_t_ne(b->canon_hash, hash_a)
+ || !TEST_ptr(ne = X509_NAME_delete_entry(b, 2))
+ || !TEST_int_eq(canon_hash_lookup(store, b), 1))
+ goto end;
+
+ /* The hash only narrows the search: a name found by it is compared */
+ c->canon_hash = hash_a;
+ if (!TEST_int_eq(canon_hash_lookup(store, c), 0))
+ goto end;
+
+ ret = 1;
+end:
+ X509_NAME_ENTRY_free(ne);
+ X509_STORE_free(store);
+ X509_free(cert);
+ X509_free(anon);
+ X509_NAME_free(a);
+ X509_NAME_free(b);
+ X509_NAME_free(c);
+ X509_NAME_free(dup);
+ X509_NAME_free(empty1);
+ X509_NAME_free(empty2);
+ return ret;
+}
+
static int test_x509_name_multivalued_rdn_mfail(void)
{
X509_NAME *name = NULL;
@@ -1057,6 +1195,7 @@ int setup_tests(void)
ADD_TEST(test_nc_empty_dirname_excluded);
ADD_TEST(test_nc_empty_dirname_permitted);
ADD_TEST(test_x509_name_canon_failure_cache);
+ ADD_TEST(test_x509_name_canon_hash);
ADD_MFAIL_TEST(test_x509_name_multivalued_rdn_mfail);
ADD_MFAIL_TEST(test_x509_attribute_i2d_mfail);
ADD_MFAIL_TEST(test_pkcs7_digest_set_i2d_mfail);