diff --git a/Include/object.h b/Include/object.h index c69becec51a..71d9dc8f762 100644 --- a/Include/object.h +++ b/Include/object.h @@ -560,6 +560,10 @@ typedef struct { } _Py_HashSecret_t; PyAPI_DATA(_Py_HashSecret_t) _Py_HashSecret; +#ifdef Py_DEBUG +PyAPI_DATA(int) _Py_HashSecret_Initialized; +#endif + /* Helper for passing objects to printf and the like */ #define PyObject_REPR(obj) _PyUnicode_AsString(PyObject_Repr(obj)) diff --git a/Objects/object.c b/Objects/object.c index bb18d471912..2665d2135fc 100644 --- a/Objects/object.c +++ b/Objects/object.c @@ -763,6 +763,7 @@ _Py_HashBytes(unsigned char *p, Py_ssize_t len) We make the hash of the empty string be 0, rather than using (prefix ^ suffix), since this slightly obfuscates the hash secret */ + assert(_Py_HashSecret_Initialized); if (len == 0) { return 0; } diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index 75e9923f0d7..a42aad9ade2 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -11214,6 +11214,7 @@ unicode_hash(PyObject *self) Py_ssize_t len; Py_uhash_t x; + assert(_Py_HashSecret_Initialized); if (_PyUnicode_HASH(self) != -1) return _PyUnicode_HASH(self); if (PyUnicode_READY(self) == -1) diff --git a/Python/random.c b/Python/random.c index 01cd83aa564..a2ae002261a 100644 --- a/Python/random.c +++ b/Python/random.c @@ -5,7 +5,11 @@ #include #endif -static int random_initialized = 0; +#ifdef Py_DEBUG +int _Py_HashSecret_Initialized = 0; +#else +static int _Py_HashSecret_Initialized = 0; +#endif #ifdef MS_WINDOWS typedef BOOL (WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv,\ @@ -246,11 +250,11 @@ _PyRandom_Init(void) { char *env; void *secret = &_Py_HashSecret; - Py_ssize_t secret_size = sizeof(_Py_HashSecret); + Py_ssize_t secret_size = sizeof(_Py_HashSecret_t); - if (random_initialized) + if (_Py_HashSecret_Initialized) return; - random_initialized = 1; + _Py_HashSecret_Initialized = 1; /* By default, hash randomization is disabled, and only