/ src / common / sysinternals / dll.c
dll.c
 1  //=========================================================================-==
 2  //
 3  // dll.c
 4  //
 5  // DLL support functions
 6  //
 7  //============================================================================
 8  
 9  #include <windows.h>
10  #include <assert.h>
11  #include <tchar.h>
12  #include <stdlib.h>
13  #include "dll.h"
14  
15  #ifndef LOAD_LIBRARY_SEARCH_SYSTEM32
16      #define LOAD_LIBRARY_SEARCH_SYSTEM32 0x800
17  #endif
18  
19  
20  //=========================================================================-==
21  //
22  // ExtendedFlagsSupported
23  //
24  // Returns TRUE if running on Windows 7 or later and FALSE otherwise
25  //
26  //============================================================================
27  static BOOLEAN ExtendedFlagsSupported()
28  {
29      OSVERSIONINFO osInfo;
30      BOOLEAN rc = FALSE;
31  
32      ZeroMemory(&osInfo, sizeof(OSVERSIONINFO));
33      osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
34  
35  #pragma warning ( disable : 4996 )  // deprecated in favour of version helper functions which we can't use 
36  
37      if (GetVersionEx(&osInfo) && (osInfo.dwMajorVersion > 6 || (osInfo.dwMajorVersion == 6 && osInfo.dwMinorVersion > 0)))
38          rc = TRUE;
39  
40  #pragma warning ( default : 4996 ) 
41  
42      return rc;
43  }
44  
45  //=========================================================================-==
46  //
47  // LoadLibrarySafe
48  //
49  // Loads a DLL from the system folder in a way that mitigates DLL spoofing /
50  // side-loading attacks
51  //
52  //============================================================================
53  HMODULE LoadLibrarySafe(LPCTSTR libraryName, DLL_LOAD_LOCATION location)
54  {
55      HMODULE hMod = NULL;
56  
57      if (NULL == libraryName || location <= DLL_LOAD_LOCATION_MIN || location >= DLL_LOAD_LOCATION_MAX) {
58  
59          SetLastError(ERROR_INVALID_PARAMETER);
60          return NULL;
61      }
62  
63      // LOAD_LIBRARY_SEARCH_SYSTEM32 is only supported on Window 7 or later. On earlier SKUs we could use a fully
64      // qualified path to the system folder but specifying a path causes Ldr to skip SxS file redirection. This can 
65      // cause the wrong library to be loaded if the application is using a manifest that defines a specific version 
66      // of Microsoft.Windows.Common-Controls when loading comctl32.dll
67      if (DLL_LOAD_LOCATION_SYSTEM == location) {
68  
69          DWORD flags = ExtendedFlagsSupported() ? LOAD_LIBRARY_SEARCH_SYSTEM32 : 0;
70          hMod = LoadLibraryEx(libraryName, NULL, flags);
71      }
72  
73      return hMod;
74  }