getentropy.c 876 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * getentropy() by wrapping getrandom(), for µClibc-ng
  3. *
  4. * © 2025 mirabilos Ⓕ CC0 or MirBSD or GNU LGPLv2
  5. *
  6. * Note: may be a thread cancellation point, unlike the
  7. * implementations in glibc and musl libc. Should this
  8. * ever become a concern, it will need patching.
  9. */
  10. #define _DEFAULT_SOURCE
  11. #include <errno.h>
  12. #include <unistd.h>
  13. #include <sys/random.h>
  14. #ifdef __NR_getrandom
  15. int
  16. getentropy(void *__buf, size_t __len)
  17. {
  18. ssize_t n;
  19. if (__len > 256U) {
  20. errno = EIO;
  21. return (-1);
  22. }
  23. again:
  24. if ((n = getrandom(__buf, __len, 0)) == -1)
  25. switch (errno) {
  26. case EAGAIN: /* should not happen but better safe than sorry */
  27. case EINTR:
  28. goto again;
  29. default:
  30. errno = EIO;
  31. /* FALLTHROUGH */
  32. case EFAULT:
  33. case ENOSYS:
  34. return (-1);
  35. }
  36. if ((size_t)n != __len)
  37. /* also shouldn’t happen (safety net) */
  38. goto again;
  39. return (0);
  40. }
  41. #endif