fix: ha_seed_jitter loop-until-full partial read; byteorder.h musl portability

This commit is contained in:
Rongsong Shen 2026-05-13 14:18:43 +00:00
parent 2c375cf476
commit 8a9fce1be4
2 changed files with 31 additions and 2 deletions

View file

@ -22,6 +22,7 @@
#include <pthread.h>
#include <stdatomic.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
@ -45,11 +46,22 @@ static inline uint64_t xorshift64_next(uint64_t *state)
static inline void ha_seed_jitter(uint64_t *seed, int my_priority)
{
uint8_t buf[8] = {0};
int fd = open("/dev/urandom", O_RDONLY);
if (fd >= 0) {
if (read(fd, seed, 8) == 8 && *seed != 0) { close(fd); return; }
ssize_t n = 0;
while (n < 8) {
ssize_t r = read(fd, buf + n, (size_t)(8 - n));
if (r <= 0) break;
n += r;
}
close(fd);
if (n == 8) {
memcpy(seed, buf, 8);
if (*seed != 0) return;
}
}
/* Fallback: monotonic clock + priority + pid mixing */
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
*seed = (uint64_t)ts.tv_nsec