xref: /reactos/sdk/lib/crt/stdlib/rand_s.c (revision 1331e2fb)
1 /*
2  * PROJECT:     ReactOS CRT library
3  * LICENSE:     GPL-2.0+ (https://spdx.org/licenses/GPL-2.0+)
4  * PURPOSE:     rand_s implementation
5  * COPYRIGHT:   Copyright 2010 Sylvain Petreolle <spetreolle@yahoo.fr>
6  *              Copyright 2015 Christoph von Wittich <christoph_vw@reactos.org>
7  *              Copyright 2015 Pierre Schweitzer <pierre@reactos.org>
8  */
9 
10 #include <precomp.h>
11 
12 typedef BOOLEAN (WINAPI *PFN_SystemFunction036)(PVOID, ULONG); // RtlGenRandom
13 PFN_SystemFunction036 g_pfnSystemFunction036 = NULL;
14 
15 /*********************************************************************
16  *              rand_s (MSVCRT.@)
17  */
18 int CDECL rand_s(unsigned int *pval)
19 {
20     HINSTANCE hadvapi32;
21 
22     if (!pval)
23     {
24         _invalid_parameter(NULL,_CRT_WIDE("rand_s"),_CRT_WIDE(__FILE__),__LINE__, 0);
25         *_errno() = EINVAL;
26         return EINVAL;
27     }
28 
29     *pval = 0;
30 
31     if (g_pfnSystemFunction036 == NULL)
32     {
33         PFN_SystemFunction036 pSystemFunction036;
34 
35         hadvapi32 = LoadLibraryA("advapi32.dll");
36         if (!hadvapi32)
37         {
38             _invalid_parameter(NULL,_CRT_WIDE("rand_s"),_CRT_WIDE(__FILE__),__LINE__, 0);
39             *_errno() = EINVAL;
40             return EINVAL;
41         }
42 
43         pSystemFunction036 = (void*)GetProcAddress(hadvapi32, "SystemFunction036");
44         if (!pSystemFunction036)
45         {
46             _invalid_parameter(NULL,_CRT_WIDE("rand_s"),_CRT_WIDE(__FILE__),__LINE__, 0);
47             *_errno() = EINVAL;
48             FreeLibrary(hadvapi32);
49             return EINVAL;
50         }
51 
52         g_pfnSystemFunction036 = pSystemFunction036;
53     }
54 
55     if (!g_pfnSystemFunction036(pval, sizeof(*pval)))
56     {
57         _invalid_parameter(NULL,_CRT_WIDE("rand_s"),_CRT_WIDE(__FILE__),__LINE__, 0);
58         *_errno() = EINVAL;
59         return EINVAL;
60     }
61 
62     return 0;
63 }
64 
65 // Small hack: import stub to allow GCC's stdc++ to link
66 #if defined(__GNUC__) && (DLL_EXPORT_VERSION < 0x600)
67 #ifdef WIN64
68 const void* __imp_rand_s = rand_s;
69 #else
70 const void* _imp_rand_s = rand_s;
71 #endif
72 #endif
73