Skip to content

Commit f48a870

Browse files
committed
Loop on Win32 to satisfy large random byte requests (as is done on Linux)
1 parent d553d04 commit f48a870

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

stdlib/public/stubs/Random.cpp

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -65,16 +65,18 @@ void swift_stdlib_random(void *buf, __swift_size_t nbytes) {
6565

6666
SWIFT_RUNTIME_STDLIB_API
6767
void swift_stdlib_random(void *buf, __swift_size_t nbytes) {
68-
if (nbytes > ULONG_MAX) {
69-
fatalError(0, "Fatal error: %zd exceeds ULONG_MAX\n", nbytes);
70-
}
68+
while (nbytes > 0) {
69+
auto actual_nbytes = std::min(nbytes, (__swift_size_t)ULONG_MAX);
70+
NTSTATUS status = BCryptGenRandom(nullptr,
71+
static_cast<PUCHAR>(buf),
72+
static_cast<ULONG>(actual_nbytes),
73+
BCRYPT_USE_SYSTEM_PREFERRED_RNG);
74+
if (!BCRYPT_SUCCESS(status)) {
75+
fatalError(0, "Fatal error: 0x%lX in '%s'\n", status, __func__);
76+
}
7177

72-
NTSTATUS status = BCryptGenRandom(nullptr,
73-
static_cast<PUCHAR>(buf),
74-
static_cast<ULONG>(nbytes),
75-
BCRYPT_USE_SYSTEM_PREFERRED_RNG);
76-
if (!BCRYPT_SUCCESS(status)) {
77-
fatalError(0, "Fatal error: 0x%lX in '%s'\n", status, __func__);
78+
buf = static_cast<uint8_t *>(buf) + actual_nbytes;
79+
nbytes -= actual_nbytes;
7880
}
7981
}
8082

0 commit comments

Comments
 (0)