pal_random.cpp 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #include "il2cpp-config.h"
  2. #include "pal_platform.h"
  3. #if IL2CPP_USES_POSIX_CLASS_LIBRARY_PAL
  4. #define IL2CPP_HAVE_O_CLOEXEC 1
  5. #include <stdlib.h>
  6. #include <fcntl.h>
  7. #include <errno.h>
  8. #include <stdio.h>
  9. #include <time.h>
  10. #include <unistd.h>
  11. extern "C"
  12. {
  13. // Items needed by mscorlib
  14. IL2CPP_EXPORT void SystemNative_GetNonCryptographicallySecureRandomBytes(uint8_t* buffer, int32_t bufferLength);
  15. }
  16. void SystemNative_GetNonCryptographicallySecureRandomBytes(uint8_t* buffer, int32_t bufferLength)
  17. {
  18. IL2CPP_ASSERT(buffer != NULL);
  19. #if IL2CPP_HAVE_ARC4RANDOM_BUF
  20. arc4random_buf(buffer, (size_t)bufferLength);
  21. #else
  22. static volatile int rand_des = -1;
  23. long num = 0;
  24. static bool sMissingDevURandom;
  25. static bool sInitializedMRand;
  26. #if !IL2CPP_HAVE_NO_UDEV_RANDOM
  27. if (!sMissingDevURandom)
  28. {
  29. if (rand_des == -1)
  30. {
  31. int fd;
  32. do
  33. {
  34. #if IL2CPP_HAVE_O_CLOEXEC
  35. fd = open("/dev/urandom", O_RDONLY, O_CLOEXEC);
  36. #else
  37. fd = open("/dev/urandom", O_RDONLY);
  38. fcntl(fd, F_SETFD, FD_CLOEXEC);
  39. #endif
  40. }
  41. while ((fd == -1) && (errno == EINTR));
  42. if (fd != -1)
  43. {
  44. if (!__sync_bool_compare_and_swap(&rand_des, -1, fd))
  45. {
  46. // Another thread has already set the rand_des
  47. close(fd);
  48. }
  49. }
  50. else if (errno == ENOENT)
  51. {
  52. sMissingDevURandom = true;
  53. }
  54. }
  55. if (rand_des != -1)
  56. {
  57. int32_t offset = 0;
  58. do
  59. {
  60. ssize_t n = read(rand_des, buffer + offset , (size_t)(bufferLength - offset));
  61. if (n == -1)
  62. {
  63. if (errno == EINTR)
  64. {
  65. continue;
  66. }
  67. IL2CPP_ASSERT(false && "read from /dev/urandom has failed");
  68. break;
  69. }
  70. offset += n;
  71. }
  72. while (offset != bufferLength);
  73. }
  74. }
  75. #endif // !IL2CPP_HAVE_NO_UDEV_RANDOM
  76. if (!sInitializedMRand)
  77. {
  78. srand48(time(NULL));
  79. sInitializedMRand = true;
  80. }
  81. // always xor srand48 over the whole buffer to get some randomness
  82. // in case /dev/urandom is not really random
  83. for (int i = 0; i < bufferLength; i++)
  84. {
  85. if (i % 4 == 0)
  86. {
  87. num = lrand48();
  88. }
  89. *(buffer + i) ^= num;
  90. num >>= 8;
  91. }
  92. #endif // IL2CPP_HAVE_ARC4RANDOM_BUF
  93. }
  94. #endif