From: David Loffredo Date: Wed, 7 Aug 2019 03:19:48 +0000 (-0400) Subject: Make win32 stdlib.h define rand_s(), add writeRandomBytes_rand_s(). X-Git-Tag: R_2_2_8~51^2~3 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=c5a2867de1b8f4661e24437374a85cf62b9f17e0;p=libexpat Make win32 stdlib.h define rand_s(), add writeRandomBytes_rand_s(). Signed-off-by: David Loffredo --- diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c index e89a2afd..50c61a87 100644 --- a/expat/lib/xmlparse.c +++ b/expat/lib/xmlparse.c @@ -34,6 +34,11 @@ # define _GNU_SOURCE 1 /* syscall prototype */ #endif +#ifdef _WIN32 +/* force stdlib to define rand_s() */ +# define _CRT_RAND_S +#endif + #include #include /* memset(), memcpy() */ #include @@ -729,6 +734,31 @@ writeRandomBytes_arc4random(void *target, size_t count) { #ifdef _WIN32 +/* Obtain entropy on Windows using the rand_s() function which + * generates cryptographically secure random numbers. Internally it + * uses RtlGenRandom API which is present in Windows XP and later. + */ +static int +writeRandomBytes_rand_s(void *target, size_t count) { + size_t bytesWrittenTotal = 0; + + while (bytesWrittenTotal < count) { + unsigned int random32 = 0; + size_t i = 0; + + if (rand_s(&random32)) + return 0; /* failure */ + + for (; (i < sizeof(random32)) && (bytesWrittenTotal < count); + i++, bytesWrittenTotal++) { + const uint8_t random8 = (uint8_t)(random32 >> (i * 8)); + ((uint8_t *)target)[bytesWrittenTotal] = random8; + } + } + return 1; /* success */ +} + + typedef BOOLEAN(APIENTRY *RTLGENRANDOM_FUNC)(PVOID, ULONG); HMODULE _Expat_LoadLibrary(LPCTSTR filename); /* see loadlibrary.c */