• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- Windows implementation of getentropy ------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/unistd/getentropy.h"
10 #include "hdr/errno_macros.h"
11 #include "src/__support/common.h"
12 #include "src/errno/libc_errno.h"
13 
14 #define WIN32_LEAN_AND_MEAN
15 #include <Windows.h>
16 #include <bcrypt.h>
17 #include <ntstatus.h>
18 #pragma comment(lib, "bcrypt.lib")
19 
20 namespace LIBC_NAMESPACE_DECL {
21 
22 LLVM_LIBC_FUNCTION(int, getentropy, (void *buffer, size_t length)) {
23   __try {
24     // check the length limit
25     if (length > 256)
26       __leave;
27 
28     NTSTATUS result = ::BCryptGenRandom(nullptr, static_cast<PUCHAR>(buffer),
29                                         static_cast<ULONG>(length),
30                                         BCRYPT_USE_SYSTEM_PREFERRED_RNG);
31 
32     if (result == STATUS_SUCCESS)
33       return 0;
34 
35   } __except (EXCEPTION_EXECUTE_HANDLER) {
36     // no need to handle exceptions specially
37   }
38 
39   libc_errno = EIO;
40   return -1;
41 }
42 } // namespace LIBC_NAMESPACE_DECL
43