[CRT]
authorPierre Schweitzer <pierre@reactos.org>
Fri, 4 Sep 2015 16:41:51 +0000 (16:41 +0000)
committerPierre Schweitzer <pierre@reactos.org>
Fri, 4 Sep 2015 16:41:51 +0000 (16:41 +0000)
Fix rand_s implementation so that it doesn't leak resources, so that it doesn't dereference null pointer, so that it matches MSDN documentation (https://msdn.microsoft.com/fr-fr/library/sxtz2fa8.aspx)

CID 716561
CID 716668

svn path=/trunk/; revision=69005

reactos/lib/sdk/crt/math/rand.c

index 10cc95e..b83be76 100644 (file)
@@ -33,17 +33,41 @@ srand(unsigned int seed)
 int CDECL rand_s(unsigned int *pval)
 {
     BOOLEAN (WINAPI *pSystemFunction036)(PVOID, ULONG); // RtlGenRandom
-    HINSTANCE hadvapi32 = LoadLibraryA("advapi32.dll");    
-    int ret = 0;
+    HINSTANCE hadvapi32;
+
+    if (!pval)
+    {
+        _invalid_parameter(NULL,_CRT_WIDE("rand_s"),_CRT_WIDE(__FILE__),__LINE__, 0);
+        *_errno() = EINVAL;
+        return EINVAL;
+    }
+
+    *pval = 0;
+    hadvapi32 = LoadLibraryA("advapi32.dll");
+    if (!hadvapi32)
+    {
+        _invalid_parameter(NULL,_CRT_WIDE("rand_s"),_CRT_WIDE(__FILE__),__LINE__, 0);
+        *_errno() = EINVAL;
+        return EINVAL;
+    }
+
     pSystemFunction036 = (void*)GetProcAddress(hadvapi32, "SystemFunction036");
-#if 1
-    if (!pval || (pSystemFunction036 && !pSystemFunction036(pval, sizeof(*pval))))
+    if (!pSystemFunction036)
+    {
+        _invalid_parameter(NULL,_CRT_WIDE("rand_s"),_CRT_WIDE(__FILE__),__LINE__, 0);
+        *_errno() = EINVAL;
+        FreeLibrary(hadvapi32);
+        return EINVAL;
+    }
+
+    if (!pSystemFunction036(pval, sizeof(*pval)))
     {
         _invalid_parameter(NULL,_CRT_WIDE("rand_s"),_CRT_WIDE(__FILE__),__LINE__, 0);
         *_errno() = EINVAL;
-        ret = EINVAL;
+        FreeLibrary(hadvapi32);
+        return EINVAL;
     }
-#endif
-    if(hadvapi32) FreeLibrary(hadvapi32);
-    return ret;
+
+    FreeLibrary(hadvapi32);
+    return 0;
 }