getentropy.c 901 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. #include <sys/syscall.h>
  15. #ifdef __NR_getrandom
  16. int
  17. getentropy(void *__buf, size_t __len)
  18. {
  19. ssize_t n;
  20. if (__len > 256U) {
  21. errno = EIO;
  22. return (-1);
  23. }
  24. again:
  25. if ((n = getrandom(__buf, __len, 0)) == -1)
  26. switch (errno) {
  27. case EAGAIN: /* should not happen but better safe than sorry */
  28. case EINTR:
  29. goto again;
  30. default:
  31. errno = EIO;
  32. /* FALLTHROUGH */
  33. case EFAULT:
  34. case ENOSYS:
  35. return (-1);
  36. }
  37. if ((size_t)n != __len)
  38. /* also shouldn’t happen (safety net) */
  39. goto again;
  40. return (0);
  41. }
  42. #endif