xref: /aosp_15_r20/external/lzma/C/DllSecur.c (revision f6dc9357d832569d4d1f5d24eacdb3935a1ae8e6)
1 /* DllSecur.c -- DLL loading security
2 2023-12-03 : Igor Pavlov : Public domain */
3 
4 #include "Precomp.h"
5 
6 #ifdef _WIN32
7 
8 #include "7zWindows.h"
9 
10 #include "DllSecur.h"
11 
12 #ifndef UNDER_CE
13 
14 Z7_DIAGNOSTIC_IGNORE_CAST_FUNCTION
15 
16 typedef BOOL (WINAPI *Func_SetDefaultDllDirectories)(DWORD DirectoryFlags);
17 
18 #define MY_LOAD_LIBRARY_SEARCH_USER_DIRS 0x400
19 #define MY_LOAD_LIBRARY_SEARCH_SYSTEM32  0x800
20 
21 #define DELIM "\0"
22 
23 static const char * const g_Dlls =
24          "userenv"
25   DELIM  "setupapi"
26   DELIM  "apphelp"
27   DELIM  "propsys"
28   DELIM  "dwmapi"
29   DELIM  "cryptbase"
30   DELIM  "oleacc"
31   DELIM  "clbcatq"
32   DELIM  "version"
33   #ifndef _CONSOLE
34   DELIM  "uxtheme"
35   #endif
36   DELIM;
37 
38 #endif
39 
40 #ifdef __clang__
41   #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
42 #endif
43 #if defined (_MSC_VER) && _MSC_VER >= 1900
44 // sysinfoapi.h: kit10: GetVersion was declared deprecated
45 #pragma warning(disable : 4996)
46 #endif
47 
48 #define IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN \
49     if ((UInt16)GetVersion() != 6) { \
50       const \
51        Func_SetDefaultDllDirectories setDllDirs = \
52       (Func_SetDefaultDllDirectories) Z7_CAST_FUNC_C GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), \
53            "SetDefaultDllDirectories"); \
54       if (setDllDirs) if (setDllDirs(MY_LOAD_LIBRARY_SEARCH_SYSTEM32 | MY_LOAD_LIBRARY_SEARCH_USER_DIRS)) return; }
55 
My_SetDefaultDllDirectories(void)56 void My_SetDefaultDllDirectories(void)
57 {
58   #ifndef UNDER_CE
59   IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN
60   #endif
61 }
62 
63 
LoadSecurityDlls(void)64 void LoadSecurityDlls(void)
65 {
66   #ifndef UNDER_CE
67   // at Vista (ver 6.0) : CoCreateInstance(CLSID_ShellLink, ...) doesn't work after SetDefaultDllDirectories() : Check it ???
68   IF_NON_VISTA_SET_DLL_DIRS_AND_RETURN
69   {
70     wchar_t buf[MAX_PATH + 100];
71     const char *dll;
72     unsigned pos = GetSystemDirectoryW(buf, MAX_PATH + 2);
73     if (pos == 0 || pos > MAX_PATH)
74       return;
75     if (buf[pos - 1] != '\\')
76       buf[pos++] = '\\';
77     for (dll = g_Dlls; *dll != 0;)
78     {
79       wchar_t *dest = &buf[pos];
80       for (;;)
81       {
82         const char c = *dll++;
83         if (c == 0)
84           break;
85         *dest++ = (Byte)c;
86       }
87       dest[0] = '.';
88       dest[1] = 'd';
89       dest[2] = 'l';
90       dest[3] = 'l';
91       dest[4] = 0;
92       // lstrcatW(buf, L".dll");
93       LoadLibraryExW(buf, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
94     }
95   }
96   #endif
97 }
98 
99 #endif // _WIN32
100