Remove libuuid usage (#16643)
authorJan Vorlicek <janvorli@microsoft.com>
Tue, 6 Mar 2018 01:21:09 +0000 (02:21 +0100)
committerGitHub <noreply@github.com>
Tue, 6 Mar 2018 01:21:09 +0000 (02:21 +0100)
* Remove libuuid usage

This change removes dependency on the libuuid library that is used for GUID creation only.
It implements it using a random generator instead.

It also modifies return type of PAL_Random to VOID since it was always
returning TRUE and none of the existing callers were checking it.

1. Port the GUID creation to managed code.
2. Modify the PAL_Random to have 6 times better perf so that the perf of the
   CoCreateGuid that is used in the native runtime doesn't degrade that much
   w.r.t the previous state when the libuuid was used.
3. Use Interop.GetRandomBytes on Unix and fix Windows

20 files changed:
src/ToolBox/superpmi/superpmi-shim-collector/superpmi-shim-collector.cpp
src/ToolBox/superpmi/superpmi-shim-counter/methodcallsummarizer.cpp
src/ToolBox/superpmi/superpmi/parallelsuperpmi.cpp
src/dlls/mscordac/mscordac_unixexports.src
src/dlls/mscoree/mscorwks_unixexports.src
src/mscorlib/System.Private.CoreLib.csproj
src/mscorlib/shared/Interop/Windows/Ole32/Interop.CoCreateGuid.cs [new file with mode: 0644]
src/mscorlib/shared/System.Private.CoreLib.Shared.projitems
src/mscorlib/shared/System/Guid.Unix.cs [new file with mode: 0644]
src/mscorlib/shared/System/Guid.Windows.cs [new file with mode: 0644]
src/mscorlib/src/Microsoft/Win32/Win32Native.cs
src/mscorlib/src/System/Guid.CoreCLR.cs [deleted file]
src/pal/inc/pal.h
src/pal/inc/rt/palrt.h
src/pal/src/CMakeLists.txt
src/pal/src/config.h.in
src/pal/src/configure.cmake
src/pal/src/misc/miscpalapi.cpp
src/palrt/guid.cpp
src/vm/comutilnative.cpp

index c8af7a0..26f6563 100644 (file)
@@ -107,7 +107,7 @@ void SetLogPathName()
     unsigned __int64 randNumber       = 0;
     const size_t     RandNumberLength = sizeof(randNumber) * 2 + 1; // 16 hex digits + null
     WCHAR            RandNumberString[RandNumberLength];
-    PAL_Random(/* bStrong */ FALSE, &randNumber, sizeof(randNumber));
+    PAL_Random(&randNumber, sizeof(randNumber));
     swprintf_s(RandNumberString, RandNumberLength, W("%016llX"), randNumber);
 #else  // !FEATURE_PAL
     unsigned int randNumber       = 0;
index 423007a..eb4a56d 100644 (file)
@@ -49,7 +49,7 @@ MethodCallSummarizer::MethodCallSummarizer(WCHAR* logPath)
         dataFileNameLength = MaxAcceptablePathLength;
 
 #ifdef FEATURE_PAL
-        PAL_Random(/* bStrong */ FALSE, &randNumber, sizeof(randNumber));
+        PAL_Random(&randNumber, sizeof(randNumber));
 #else  // !FEATURE_PAL
         rand_s(&randNumber);
 #endif // !FEATURE_PAL
index 596f1b6..a773344 100644 (file)
@@ -471,7 +471,7 @@ int doParallelSuperPMI(CommandLine::Options& o)
     // Add a random number to the temporary file names to allow multiple parallel SuperPMI to happen at once.
     unsigned int randNumber = 0;
 #ifdef FEATURE_PAL
-    PAL_Random(/* bStrong */ FALSE, &randNumber, sizeof(randNumber));
+    PAL_Random(&randNumber, sizeof(randNumber));
 #else  // !FEATURE_PAL
     rand_s(&randNumber);
 #endif // !FEATURE_PAL
index 99ed375..77a53d7 100644 (file)
@@ -29,6 +29,7 @@ PAL_InitializeDLL
 PAL_TerminateEx
 PAL_IsDebuggerPresent
 PAL_ProbeMemory
+PAL_Random
 PAL_iswspace
 PAL_memcpy
 PAL_malloc
@@ -65,7 +66,6 @@ _i64tow_s
 memcpy_s
 sscanf_s
 
-CoCreateGuid
 CopyFileW
 CreateDirectoryW
 CreateFileMappingA
index 0eae53f..a3b00d0 100644 (file)
@@ -22,7 +22,6 @@ GetCLRRuntimeHost
 
 ; Win32 API and other PAL functions used by the mscorlib
 CloseHandle
-CoCreateGuid
 CoTaskMemAlloc
 CoTaskMemRealloc
 CoTaskMemFree
index 1da5ccb..effac53 100644 (file)
     <Compile Include="$(BclSourcesRoot)\System\Enum.cs" />
     <Compile Include="$(BclSourcesRoot)\System\Environment.cs" />
     <Compile Include="$(BclSourcesRoot)\System\GC.cs" />
-    <Compile Include="$(BclSourcesRoot)\System\Guid.CoreCLR.cs" />
     <Compile Include="$(BclSourcesRoot)\System\InsufficientMemoryException.cs" />
     <Compile Include="$(BclSourcesRoot)\System\Internal.cs" />
     <Compile Include="$(BclSourcesRoot)\System\Math.CoreCLR.cs" />
diff --git a/src/mscorlib/shared/Interop/Windows/Ole32/Interop.CoCreateGuid.cs b/src/mscorlib/shared/Interop/Windows/Ole32/Interop.CoCreateGuid.cs
new file mode 100644 (file)
index 0000000..60cfb23
--- /dev/null
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+    internal static partial class Ole32
+    {
+        [DllImport(Interop.Libraries.Ole32)]
+        internal extern static int CoCreateGuid(out Guid guid);
+    }
+}
index 46a161e..a0c6c0c 100644 (file)
     <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Normaliz\Interop.Idna.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'" />
     <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Normaliz\Interop.Normalization.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'" />
     <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.TimeZone.cs" />
+    <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Ole32\Interop.CoCreateGuid.cs" />
     <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\OleAut32\Interop.SysAllocStringLen.cs" />
     <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\OleAut32\Interop.SysFreeString.cs" />
     <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\OleAut32\Interop.SysStringLen.cs" />
     <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\JapaneseCalendar.WinRT.cs" Condition="'$(EnableWinRT)' == 'true'" />
     <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\Normalization.Windows.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'" />
     <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\TextInfo.Windows.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'" />
+    <Compile Include="$(MSBuildThisFileDirectory)System\Guid.Windows.cs" />
     <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Windows.cs" />
     <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStreamCompletionSource.Win32.cs" />
     <Compile Include="$(MSBuildThisFileDirectory)System\IO\Path.Windows.cs" />
     <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\LocaleData.Unix.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'" />
     <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\Normalization.Unix.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'" />
     <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\TextInfo.Unix.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'" />
+    <Compile Include="$(MSBuildThisFileDirectory)System\Guid.Unix.cs" />
     <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.OSX.cs" Condition="'$(TargetsOSX)' == 'true'" />
     <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Linux.cs" Condition="'$(TargetsOSX)' != 'true'" />
     <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Unix.cs" />
diff --git a/src/mscorlib/shared/System/Guid.Unix.cs b/src/mscorlib/shared/System/Guid.Unix.cs
new file mode 100644 (file)
index 0000000..442e7f8
--- /dev/null
@@ -0,0 +1,38 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
+namespace System
+{
+    partial struct Guid
+    {
+        // This will create a new random guid based on the https://www.ietf.org/rfc/rfc4122.txt 
+        public static unsafe Guid NewGuid()
+        {
+            Guid g;
+            Interop.GetRandomBytes((byte*)&g, sizeof(Guid));
+            
+            const ushort VersionMask = 0xF000;
+            const ushort RandomGuidVersion = 0x4000;
+
+            const byte ClockSeqHiAndReservedMask = 0xC0;
+            const byte ClockSeqHiAndReservedValue = 0x80;
+
+            // Modify bits indicating the type of the GUID
+
+            unchecked
+            {
+                // time_hi_and_version
+                g._c = (short)((g._c & ~VersionMask) | RandomGuidVersion);
+                // clock_seq_hi_and_reserved
+                g._d = (byte)((g._d & ~ClockSeqHiAndReservedMask) | ClockSeqHiAndReservedValue);
+            }
+
+            return g;
+        }
+    }
+}
+
diff --git a/src/mscorlib/shared/System/Guid.Windows.cs b/src/mscorlib/shared/System/Guid.Windows.cs
new file mode 100644 (file)
index 0000000..f00fbe4
--- /dev/null
@@ -0,0 +1,29 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System
+{
+    partial struct Guid
+    {
+        public static Guid NewGuid()
+        {
+            // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some
+            // uniqueness guarantees.
+
+            Guid g;
+            int hr = Interop.Ole32.CoCreateGuid(out g);
+            // We don't expect that this will ever throw an error, none are even documented, and so we don't want to pull 
+            // in the HR to ComException mappings into the core library just for this so we will try a generic exception if 
+            // we ever hit this condition.
+            if (hr != 0)
+            {
+                Exception ex = new Exception();
+                ex.SetErrorCode(hr);
+                throw ex;
+            }
+            return g;
+        }
+    }
+}
+
index fbb1b35..eef34ad 100644 (file)
@@ -380,9 +380,6 @@ namespace Microsoft.Win32
         internal static extern uint GetCurrentProcessId();
 
         [DllImport(Interop.Libraries.Ole32)]
-        internal extern static int CoCreateGuid(out Guid guid);
-
-        [DllImport(Interop.Libraries.Ole32)]
         internal static extern IntPtr CoTaskMemAlloc(UIntPtr cb);
 
         [DllImport(Interop.Libraries.Ole32)]
diff --git a/src/mscorlib/src/System/Guid.CoreCLR.cs b/src/mscorlib/src/System/Guid.CoreCLR.cs
deleted file mode 100644 (file)
index e3722b8..0000000
+++ /dev/null
@@ -1,19 +0,0 @@
-// Licensed to the .NET Foundation under one or more agreements.
-// The .NET Foundation licenses this file to you under the MIT license.
-// See the LICENSE file in the project root for more information.
-
-using Microsoft.Win32;
-using System.Runtime.InteropServices;
-
-namespace System
-{
-    partial struct Guid
-    {
-        public static Guid NewGuid()
-        {
-            Guid guid;
-            Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1));
-            return guid;
-        }
-    }
-}
index 18fbdab..462accd 100644 (file)
@@ -526,10 +526,9 @@ PAL_GetPALDirectoryW(
 #endif
 
 PALIMPORT
-BOOL
+VOID
 PALAPI
 PAL_Random(
-    IN BOOL bStrong,
     IN OUT LPVOID lpBuffer,
     IN DWORD dwLength);
 
@@ -4876,11 +4875,6 @@ SetThreadIdealProcessorEx(
 #define EVENTLOG_AUDIT_SUCCESS          0x0008
 #define EVENTLOG_AUDIT_FAILURE          0x0010
 
-PALIMPORT
-HRESULT
-PALAPI
-CoCreateGuid(OUT GUID * pguid);
-
 #if defined FEATURE_PAL_ANSI
 #include "palprivate.h"
 #endif //FEATURE_PAL_ANSI
index af76e04..1360a81 100644 (file)
@@ -1577,6 +1577,9 @@ EXTERN_C HRESULT PALAPI PAL_CoCreateInstance(REFCLSID   rclsid,
 // instead of spreading around of if'def FEATURE_PALs for PAL_CoCreateInstance.
 #define CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, ppv) PAL_CoCreateInstance(rclsid, riid, ppv)
 
+STDAPI
+CoCreateGuid(OUT GUID * pguid);
+
 /************** verrsrc.h ************************************/
 
 /* ----- VS_VERSION.dwFileFlags ----- */
index 3ef0dd1..0285d88 100644 (file)
@@ -345,7 +345,6 @@ if(CMAKE_SYSTEM_NAME STREQUAL Linux)
 
   target_link_libraries(coreclrpal
     dl
-    uuid
   )
 
   if(NOT UNWIND_GENERIC STREQUAL UNWIND_GENERIC-NOTFOUND)
index 5643c1b..584b28a 100644 (file)
@@ -15,8 +15,6 @@
 #cmakedefine01 HAVE_SYS_LWP_H
 #cmakedefine01 HAVE_LWP_H
 #cmakedefine01 HAVE_LIBUNWIND_H
-#cmakedefine01 HAVE_LIBUUID_H
-#cmakedefine01 HAVE_BSD_UUID_H
 #cmakedefine01 HAVE_RUNETYPE_H
 #cmakedefine01 HAVE_SYS_SYSCTL_H
 #cmakedefine01 HAVE_GNU_LIBNAMES_H
index 0f105ee..a6dd6f4 100644 (file)
@@ -48,7 +48,6 @@ if(NOT CMAKE_SYSTEM_NAME STREQUAL FreeBSD AND NOT CMAKE_SYSTEM_NAME STREQUAL Net
   unset(CMAKE_REQUIRED_FLAGS)
 endif()
 
-check_include_files(uuid/uuid.h HAVE_LIBUUID_H)
 check_include_files(sys/sysctl.h HAVE_SYS_SYSCTL_H)
 check_include_files(gnu/lib-names.h HAVE_GNU_LIBNAMES_H)
 
@@ -170,16 +169,6 @@ check_cxx_symbol_exists(_SC_PHYS_PAGES unistd.h HAVE__SC_PHYS_PAGES)
 check_cxx_symbol_exists(_SC_AVPHYS_PAGES unistd.h HAVE__SC_AVPHYS_PAGES)
 
 check_cxx_source_runs("
-#include <uuid.h>
-
-int main(void) {
-  uuid_t uuid;
-  uint32_t status;
-  uuid_create(&uuid, &status);
-  return 0;
-}" HAVE_BSD_UUID_H)
-
-check_cxx_source_runs("
 #include <sys/param.h>
 #include <stdlib.h>
 
@@ -1271,10 +1260,6 @@ if(NOT CLR_CMAKE_PLATFORM_ARCH_ARM AND NOT CLR_CMAKE_PLATFORM_ARCH_ARM64)
 endif()
 
 if(CMAKE_SYSTEM_NAME STREQUAL Darwin)
-  if(NOT HAVE_LIBUUID_H)
-    unset(HAVE_LIBUUID_H CACHE)
-    message(FATAL_ERROR "Cannot find libuuid. Try installing uuid-dev or the appropriate packages for your platform")
-  endif()
   set(HAVE_COREFOUNDATION 1)
   set(HAVE__NSGETENVIRON 1)
   set(DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX 1)
@@ -1291,10 +1276,6 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL FreeBSD)
     unset(HAVE_LIBUNWIND_H CACHE)
     message(FATAL_ERROR "Cannot find libunwind. Try installing libunwind8 and libunwind8-dev (or the appropriate packages for your platform)")
   endif()
-  if(NOT HAVE_BSD_UUID_H)
-    unset(HAVE_BSD_UUID_H CACHE)
-    message(FATAL_ERROR "Cannot find uuid.h")
-  endif()
   set(DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX 0)
   set(PAL_PTRACE "ptrace((cmd), (pid), (caddr_t)(addr), (data))")
   set(PAL_PT_ATTACH PT_ATTACH)
@@ -1309,10 +1290,6 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL NetBSD)
     unset(HAVE_LIBUNWIND_H CACHE)
     message(FATAL_ERROR "Cannot find libunwind. Try installing libunwind8 and libunwind8-dev (or the appropriate packages for your platform)")
   endif()
-  if(NOT HAVE_BSD_UUID_H)
-    unset(HAVE_BSD_UUID_H CACHE)
-    message(FATAL_ERROR "Cannot find uuid.h")
-  endif()
   set(DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX 0)
   set(PAL_PTRACE "ptrace((cmd), (pid), (void*)(addr), (data))")
   set(PAL_PT_ATTACH PT_ATTACH)
@@ -1328,10 +1305,6 @@ elseif(CMAKE_SYSTEM_NAME STREQUAL SunOS)
     unset(HAVE_LIBUNWIND_H CACHE)
     message(FATAL_ERROR "Cannot find libunwind. Try installing libunwind8 and libunwind8-dev (or the appropriate packages for your platform)")
   endif()
-  if(NOT HAVE_LIBUUID_H)
-    unset(HAVE_LIBUUID_H CACHE)
-    message(FATAL_ERROR "Cannot find libuuid. Try installing uuid-dev or the appropriate packages for your platform")
-  endif()
   set(DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX 0)
   set(PAL_PTRACE "ptrace((cmd), (pid), (caddr_t)(addr), (data))")
   set(PAL_PT_ATTACH PT_ATTACH)
@@ -1348,10 +1321,6 @@ else() # Anything else is Linux
     unset(HAVE_LTTNG_TRACEPOINT_H CACHE)
     message(FATAL_ERROR "Cannot find liblttng-ust-dev. Try installing liblttng-ust-dev  (or the appropriate packages for your platform)")
   endif()
-  if(NOT HAVE_LIBUUID_H)
-    unset(HAVE_LIBUUID_H CACHE)
-    message(FATAL_ERROR "Cannot find libuuid. Try installing uuid-dev or the appropriate packages for your platform")
-  endif()
   set(DEADLOCK_WHEN_THREAD_IS_SUSPENDED_WHILE_BLOCKED_ON_MUTEX 0)
   set(PAL_PTRACE "ptrace((cmd), (pid), (void*)(addr), (data))")
   set(PAL_PT_ATTACH PTRACE_ATTACH)
index 0e12344..27ff136 100644 (file)
@@ -34,12 +34,6 @@ Revision History:
 #include <pthread.h>
 #include <dlfcn.h>
 
-#if HAVE_BSD_UUID_H
-#include <uuid.h>
-#elif HAVE_LIBUUID_H
-#include <uuid/uuid.h>
-#endif
-
 #include <pal_endian.h>
 
 #ifdef __APPLE__
@@ -48,7 +42,6 @@ Revision History:
 
 SET_DEFAULT_DEBUG_CHANNEL(MISC);
 
-static const char RANDOM_DEVICE_NAME[] ="/dev/random";
 static const char URANDOM_DEVICE_NAME[]="/dev/urandom";
 
 /*++
@@ -235,90 +228,64 @@ PAL_GetPALDirectoryA(
     return bRet;
 }
 
-BOOL
+VOID
 PALAPI
 PAL_Random(
-        IN BOOL bStrong,
         IN OUT LPVOID lpBuffer,
         IN DWORD dwLength)
 {
     int rand_des = -1;
-    BOOL bRet = FALSE;
     DWORD i;
-    char buf;
     long num = 0;
-    static BOOL sMissingDevRandom;
     static BOOL sMissingDevURandom;
     static BOOL sInitializedMRand;
 
     PERF_ENTRY(PAL_Random);
-    ENTRY("PAL_Random(bStrong=%d, lpBuffer=%p, dwLength=%d)\n", 
-          bStrong, lpBuffer, dwLength);
+    ENTRY("PAL_Random(lpBuffer=%p, dwLength=%d)\n", lpBuffer, dwLength);
 
-    i = 0;
-
-    if (bStrong == TRUE && i < dwLength && !sMissingDevRandom)
+    if (!sMissingDevURandom)
     {
-        // request non-blocking access to avoid hangs if the /dev/random is exhausted
-        // or just simply broken
-        if ((rand_des = PAL__open(RANDOM_DEVICE_NAME, O_RDONLY | O_NONBLOCK)) == -1)
+        do
         {
-            if (errno == ENOENT)
-            {
-                sMissingDevRandom = TRUE;
-            }
-            else
-            {
-                ASSERT("PAL__open() failed, errno:%d (%s)\n", errno, strerror(errno));
-            }
-
-            // Back off and try /dev/urandom.
+            rand_des = open("/dev/urandom", O_RDONLY, O_CLOEXEC);
         }
-        else
-        {
-            for( ; i < dwLength; i++)
-            {
-                if (read(rand_des, &buf, 1) < 1)
-                {
-                    // the /dev/random pool has been exhausted.  Fall back
-                    // to /dev/urandom for the remainder of the buffer.
-                    break;
-                }
+        while ((rand_des == -1) && (errno == EINTR));
 
-                *(((BYTE*)lpBuffer) + i) ^= buf;
-            }
-
-            close(rand_des);
-        }
-    }
-    if (i < dwLength && !sMissingDevURandom)
-    {
-        if ((rand_des = PAL__open(URANDOM_DEVICE_NAME, O_RDONLY)) == -1)
+        if (rand_des == -1)
         {
             if (errno == ENOENT)
             {                
-                sMissingDevURandom = TRUE;                
+                sMissingDevURandom = TRUE;
             }
             else
             {
-                ASSERT("PAL__open() failed, errno:%d (%s)\n", errno, strerror(errno));               
+                ASSERT("PAL__open() failed, errno:%d (%s)\n", errno, strerror(errno));
             }
 
-            // Back off and try mrand48.           
+            // Back off and try mrand48.
         }
         else
         {
-            for( ; i < dwLength; i++)
+            DWORD offset = 0;
+            do
             {
-                if (read(rand_des, &buf, 1) < 1)
+                DWORD n = read(rand_des, (BYTE*)lpBuffer + offset , dwLength - offset);
+                if (n == -1)
                 {
-                    // Fall back to srand48 for the remainder of the buffer.
+                    if (errno == EINTR)
+                    {
+                        continue;
+                    }
+                    ASSERT("read() failed, errno:%d (%s)\n", errno, strerror(errno));
+
                     break;
                 }
 
-                *(((BYTE*)lpBuffer) + i) ^= buf;
+                offset += n;
             }
+            while (offset != dwLength);
+
+            _ASSERTE(offset == dwLength);
 
             close(rand_des);
         }
@@ -331,9 +298,9 @@ PAL_Random(
     }
 
     // always xor srand48 over the whole buffer to get some randomness
-    // in case /dev/random is not really random
+    // in case /dev/urandom is not really random
 
-    for(i = 0; i < dwLength; i++)
+    for (i = 0; i < dwLength; i++)
     {
         if (i % sizeof(long) == 0) {
             num = mrand48();
@@ -343,39 +310,6 @@ PAL_Random(
         num >>= 8;
     }
 
-    bRet = TRUE;
-
-    LOGEXIT("PAL_Random returns %d\n", bRet);
+    LOGEXIT("PAL_Random\n");
     PERF_EXIT(PAL_Random);
-    return bRet;
-}
-
-HRESULT
-PALAPI
-CoCreateGuid(OUT GUID * pguid)
-{
-#if HAVE_BSD_UUID_H
-    uuid_t uuid;
-    uint32_t status;
-    uuid_create(&uuid, &status);
-    if (status != uuid_s_ok)
-    {
-        ASSERT("Unexpected uuid_create failure (status=%u)\n", status);
-        PROCAbort();
-    }
-
-    // Encode the uuid with little endian.
-    uuid_enc_le(pguid, &uuid);
-#elif HAVE_LIBUUID_H
-    uuid_generate_random(*(uuid_t*)pguid);
-
-    // Change the byte order of the Data1, 2 and 3, since the uuid_generate_random
-    // generates them with big endian while GUIDS need to have them in little endian.
-    pguid->Data1 = SWAP32(pguid->Data1);
-    pguid->Data2 = SWAP16(pguid->Data2);
-    pguid->Data3 = SWAP16(pguid->Data3);
-#else
-    #error Don't know how to generate UUID on this platform
-#endif
-    return 0;
 }
index bd782c8..14cd3bb 100644 (file)
@@ -24,3 +24,25 @@ DEFINE_GUID(IID_IClassFactory, 0x00000001, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x0
 // objidl.idl
 DEFINE_GUID(IID_ISequentialStream, 0x0c733a30, 0x2a1c, 0x11ce, 0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d);
 DEFINE_GUID(IID_IStream, 0x0000000c, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46);
+
+// Create a random guid based on the https://www.ietf.org/rfc/rfc4122.txt
+STDAPI
+CoCreateGuid(OUT GUID * pguid)
+{
+    PAL_Random(pguid, sizeof(GUID));
+
+    static const USHORT VersionMask = 0xF000;
+    static const USHORT RandomGuidVersion = 0x4000;
+
+    static const BYTE ClockSeqHiAndReservedMask = 0xC0;
+    static const BYTE ClockSeqHiAndReservedValue = 0x80;
+
+    // Modify bits indicating the type of the GUID
+
+    // time_hi_and_version
+    pguid->Data3 = (pguid->Data3 & ~VersionMask) | RandomGuidVersion;
+    // clock_seq_hi_and_reserved
+    pguid->Data4[0] = (pguid->Data4[0] & ~ClockSeqHiAndReservedMask) | ClockSeqHiAndReservedValue;
+
+    return S_OK;
+}
index 3b30d4c..8fc326e 100644 (file)
@@ -2337,7 +2337,7 @@ PCBYTE COMNlsHashProvider::GetEntropy()
         AllocMemHolder<BYTE> pNewEntropy(GetAppDomain()->GetLowFrequencyHeap()->AllocMem(S_SIZE_T(sizeof(SYMCRYPT_MARVIN32_SEED_SIZE))));
 
 #ifdef FEATURE_PAL
-        PAL_Random(TRUE, pNewEntropy, SYMCRYPT_MARVIN32_SEED_SIZE);
+        PAL_Random(pNewEntropy, SYMCRYPT_MARVIN32_SEED_SIZE);
 #else
         HCRYPTPROV hCryptProv;
         WszCryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);