From 066531df73264fa1436a3f2ad6dff1746baffc26 Mon Sep 17 00:00:00 2001 From: Adam Cozzette Date: Fri, 31 Jan 2025 16:52:16 -0800 Subject: [PATCH] Randomize upb's map ordering We use the address of a variable as the seed for upb's hash function, and this allows us to get some randomness from ASLR. The randomness is not perfect, especially since it won't necessarily help when ASLR is not enabled. However, it seems to be enough to prevent unit tests from relying on a deterministic map ordering. PiperOrigin-RevId: 721950394 --- upb/hash/common.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/upb/hash/common.c b/upb/hash/common.c index ef90baafa5685..99e370318d517 100644 --- a/upb/hash/common.c +++ b/upb/hash/common.c @@ -402,9 +402,14 @@ uint32_t _upb_Hash(const void* p, size_t n, uint64_t seed) { return Wyhash(p, n, seed, kWyhashSalt); } -// Returns a seed for upb's hash function. For now this is just a hard-coded -// constant, but we are going to randomize it soon. -static uint64_t _upb_Seed(void) { return 0x69835f69597ec1cc; } +static const void* const _upb_seed; + +// Returns a random seed for upb's hash function. This does not provide +// high-quality randomness, but it should be enough to prevent unit tests from +// relying on a deterministic map ordering. By returning the address of a +// variable, we are able to get some randomness for free provided that ASLR is +// enabled. +static uint64_t _upb_Seed(void) { return (uint64_t)&_upb_seed; } static uint32_t _upb_Hash_NoSeed(const char* p, size_t n) { return _upb_Hash(p, n, _upb_Seed());