fix: ha_seed_jitter loop-until-full partial read; byteorder.h musl portability
This commit is contained in:
parent
2c375cf476
commit
8a9fce1be4
2 changed files with 31 additions and 2 deletions
|
|
@ -22,6 +22,7 @@
|
||||||
#include <pthread.h>
|
#include <pthread.h>
|
||||||
#include <stdatomic.h>
|
#include <stdatomic.h>
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
|
#include <string.h>
|
||||||
#include <time.h>
|
#include <time.h>
|
||||||
#include <unistd.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)
|
static inline void ha_seed_jitter(uint64_t *seed, int my_priority)
|
||||||
{
|
{
|
||||||
|
uint8_t buf[8] = {0};
|
||||||
int fd = open("/dev/urandom", O_RDONLY);
|
int fd = open("/dev/urandom", O_RDONLY);
|
||||||
if (fd >= 0) {
|
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);
|
close(fd);
|
||||||
|
if (n == 8) {
|
||||||
|
memcpy(seed, buf, 8);
|
||||||
|
if (*seed != 0) return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
/* Fallback: monotonic clock + priority + pid mixing */
|
||||||
struct timespec ts;
|
struct timespec ts;
|
||||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||||
*seed = (uint64_t)ts.tv_nsec
|
*seed = (uint64_t)ts.tv_nsec
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,24 @@
|
||||||
#pragma once
|
#pragma once
|
||||||
/* Portable be64toh() for non-glibc or pre-2.25 targets. */
|
/* Portable be64toh() — big-endian to host byte order conversion. */
|
||||||
#if defined(__linux__)
|
#if defined(__linux__)
|
||||||
|
# ifndef _DEFAULT_SOURCE
|
||||||
|
# define _DEFAULT_SOURCE 1
|
||||||
|
# endif
|
||||||
|
# ifndef _BSD_SOURCE
|
||||||
|
# define _BSD_SOURCE 1
|
||||||
|
# endif
|
||||||
# include <endian.h>
|
# include <endian.h>
|
||||||
|
# ifndef be64toh
|
||||||
|
/* musl and some older glibc: fall back to builtin */
|
||||||
|
# include <stdint.h>
|
||||||
|
static inline uint64_t be64toh(uint64_t x) {
|
||||||
|
# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
|
||||||
|
return __builtin_bswap64(x);
|
||||||
|
# else
|
||||||
|
return x;
|
||||||
|
# endif
|
||||||
|
}
|
||||||
|
# endif /* be64toh */
|
||||||
#elif defined(__APPLE__)
|
#elif defined(__APPLE__)
|
||||||
# include <machine/endian.h>
|
# include <machine/endian.h>
|
||||||
# include <libkern/OSByteOrder.h>
|
# include <libkern/OSByteOrder.h>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue