Skip to content

Commit 0368538

Browse files
authored
Loop on Win32 to satisfy large random byte requests (as is done on Linux) (#62364)
1 parent 79b9c55 commit 0368538

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

stdlib/public/stubs/Random.cpp

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
#if defined(_WIN32) && !defined(__CYGWIN__)
2121
#define WIN32_LEAN_AND_MEAN
22+
#define NOMINMAX
2223
#include <Windows.h>
2324
#include <Bcrypt.h>
2425
#pragma comment(lib, "bcrypt.lib")
@@ -65,16 +66,18 @@ void swift_stdlib_random(void *buf, __swift_size_t nbytes) {
6566

6667
SWIFT_RUNTIME_STDLIB_API
6768
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-
}
69+
while (nbytes > 0) {
70+
auto actual_nbytes = std::min(nbytes, (__swift_size_t)ULONG_MAX);
71+
NTSTATUS status = BCryptGenRandom(nullptr,
72+
static_cast<PUCHAR>(buf),
73+
static_cast<ULONG>(actual_nbytes),
74+
BCRYPT_USE_SYSTEM_PREFERRED_RNG);
75+
if (!BCRYPT_SUCCESS(status)) {
76+
fatalError(0, "Fatal error: 0x%lX in '%s'\n", status, __func__);
77+
}
7178

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__);
79+
buf = static_cast<uint8_t *>(buf) + actual_nbytes;
80+
nbytes -= actual_nbytes;
7881
}
7982
}
8083

0 commit comments

Comments
 (0)