[SHIMENG] Ignore shims that are loading
[reactos.git] / dll / appcompat / apphelp / shimeng.c
1 /*
2 * PROJECT: ReactOS Application compatibility module
3 * LICENSE: GPL-2.0+ (https://spdx.org/licenses/GPL-2.0+)
4 * PURPOSE: Shim engine core
5 * COPYRIGHT: Copyright 2015-2018 Mark Jansen (mark.jansen@reactos.org)
6 */
7
8 #define WIN32_NO_STATUS
9 #include "ntndk.h"
10 #define IN_APPHELP
11 #include "shimlib.h"
12 #include <strsafe.h>
13 /* Make sure we don't include apphelp logging */
14 #define APPHELP_NOSDBPAPI
15 #include "apphelp.h"
16 #include "shimeng.h"
17
18
19
20 FARPROC WINAPI StubGetProcAddress(HINSTANCE hModule, LPCSTR lpProcName);
21 BOOL WINAPI SE_IsShimDll(PVOID BaseAddress);
22
23
24 extern HMODULE g_hInstance;
25 static UNICODE_STRING g_WindowsDirectory;
26 static UNICODE_STRING g_System32Directory;
27 static UNICODE_STRING g_SxsDirectory;
28 static UNICODE_STRING g_LoadingShimDll;
29 ULONG g_ShimEngDebugLevel = 0xffffffff;
30 BOOL g_bComPlusImage = FALSE;
31 BOOL g_bShimDuringInit = FALSE;
32 BOOL g_bInternalHooksUsed = FALSE;
33 static ARRAY g_pShimInfo; /* PSHIMMODULE */
34 static ARRAY g_pHookArray; /* HOOKMODULEINFO */
35 static ARRAY g_InExclude; /* INEXCLUDE */
36
37 /* If we have setup a hook for a function, we should also redirect GetProcAddress for this function */
38 HOOKAPIEX g_IntHookEx[] =
39 {
40 {
41 "kernel32.dll", /* LibraryName */
42 "GetProcAddress", /* FunctionName */
43 StubGetProcAddress, /* ReplacementFunction*/
44 NULL, /* OriginalFunction */
45 NULL, /* pShimInfo */
46 NULL /* Unused */
47 },
48 };
49
50 static inline BOOL ARRAY_InitWorker(PARRAY Array, DWORD ItemSize)
51 {
52 Array->Data__ = NULL;
53 Array->Size__ = Array->MaxSize__ = 0;
54 Array->ItemSize__ = ItemSize;
55
56 return TRUE;
57 }
58
59 static inline BOOL ARRAY_EnsureSize(PARRAY Array, DWORD ItemSize, DWORD GrowWith)
60 {
61 PVOID pNewData;
62 DWORD Count;
63
64 ASSERT(Array);
65 ASSERT(ItemSize == Array->ItemSize__);
66
67 if (Array->MaxSize__ > Array->Size__)
68 return TRUE;
69
70 Count = Array->Size__ + GrowWith;
71 pNewData = SeiAlloc(Count * ItemSize);
72
73 if (!pNewData)
74 {
75 SHIMENG_FAIL("Failed to allocate %d bytes\n", Count * ItemSize);
76 return FALSE;
77 }
78 Array->MaxSize__ = Count;
79
80 if (Array->Data__)
81 {
82 memcpy(pNewData, Array->Data__, Array->Size__ * ItemSize);
83 SeiFree(Array->Data__);
84 }
85 Array->Data__ = pNewData;
86
87 return TRUE;
88 }
89
90 static inline PVOID ARRAY_AppendWorker(PARRAY Array, DWORD ItemSize, DWORD GrowWith)
91 {
92 PBYTE pData;
93
94 if (!ARRAY_EnsureSize(Array, ItemSize, GrowWith))
95 return NULL;
96
97 pData = Array->Data__;
98 pData += (Array->Size__ * ItemSize);
99 Array->Size__++;
100
101 return pData;
102 }
103
104 static inline PVOID ARRAY_AtWorker(PARRAY Array, DWORD ItemSize, DWORD n)
105 {
106 PBYTE pData;
107
108 ASSERT(Array);
109 ASSERT(ItemSize == Array->ItemSize__);
110 ASSERT(n < Array->Size__);
111
112 pData = Array->Data__;
113 return pData + (n * ItemSize);
114 }
115
116
117 #define ARRAY_Init(Array, TypeOfArray) ARRAY_InitWorker((Array), sizeof(TypeOfArray))
118 #define ARRAY_Append(Array, TypeOfArray) (TypeOfArray*)ARRAY_AppendWorker((Array), sizeof(TypeOfArray), 5)
119 #define ARRAY_At(Array, TypeOfArray, at) (TypeOfArray*)ARRAY_AtWorker((Array), sizeof(TypeOfArray), at)
120 #define ARRAY_Size(Array) (Array)->Size__
121
122
123 VOID SeiInitDebugSupport(VOID)
124 {
125 static const UNICODE_STRING DebugKey = RTL_CONSTANT_STRING(L"SHIMENG_DEBUG_LEVEL");
126 UNICODE_STRING DebugValue;
127 NTSTATUS Status;
128 ULONG NewLevel = SEI_MSG; /* Show some basic info in the logs, unless configured different */
129 WCHAR Buffer[40];
130
131 RtlInitEmptyUnicodeString(&DebugValue, Buffer, sizeof(Buffer));
132
133 Status = RtlQueryEnvironmentVariable_U(NULL, &DebugKey, &DebugValue);
134
135 if (NT_SUCCESS(Status))
136 {
137 if (!NT_SUCCESS(RtlUnicodeStringToInteger(&DebugValue, 10, &NewLevel)))
138 NewLevel = 0;
139 }
140 g_ShimEngDebugLevel = NewLevel;
141 }
142
143
144 /**
145 * Outputs diagnostic info.
146 *
147 * @param [in] Level The level to log this message with, choose any of [SHIM_ERR,
148 * SHIM_WARN, SHIM_INFO].
149 * @param [in] FunctionName The function this log should be attributed to.
150 * @param [in] Format The format string.
151 * @param ... Variable arguments providing additional information.
152 *
153 * @return Success: TRUE Failure: FALSE.
154 */
155 BOOL WINAPIV SeiDbgPrint(SEI_LOG_LEVEL Level, PCSTR Function, PCSTR Format, ...)
156 {
157 char Buffer[512];
158 char* Current = Buffer;
159 const char* LevelStr;
160 size_t Length = sizeof(Buffer);
161 va_list ArgList;
162 HRESULT hr;
163
164 if (g_ShimEngDebugLevel == 0xffffffff)
165 SeiInitDebugSupport();
166
167 if (Level > g_ShimEngDebugLevel)
168 return FALSE;
169
170 switch (Level)
171 {
172 case SEI_MSG:
173 LevelStr = "MSG ";
174 break;
175 case SEI_FAIL:
176 LevelStr = "FAIL";
177 break;
178 case SEI_WARN:
179 LevelStr = "WARN";
180 break;
181 case SEI_INFO:
182 LevelStr = "INFO";
183 break;
184 default:
185 LevelStr = "USER";
186 break;
187 }
188
189 if (Function)
190 hr = StringCchPrintfExA(Current, Length, &Current, &Length, STRSAFE_NULL_ON_FAILURE, "[%s] [%s] ", LevelStr, Function);
191 else
192 hr = StringCchPrintfExA(Current, Length, &Current, &Length, STRSAFE_NULL_ON_FAILURE, "[%s] ", LevelStr);
193
194 if (!SUCCEEDED(hr))
195 return FALSE;
196
197 va_start(ArgList, Format);
198 hr = StringCchVPrintfExA(Current, Length, &Current, &Length, STRSAFE_NULL_ON_FAILURE, Format, ArgList);
199 va_end(ArgList);
200 if (!SUCCEEDED(hr))
201 return FALSE;
202
203 DbgPrint("%s", Buffer);
204 return TRUE;
205 }
206
207
208 PVOID SeiGetModuleFromAddress(PVOID addr)
209 {
210 PVOID hModule = NULL;
211 RtlPcToFileHeader(addr, &hModule);
212 return hModule;
213 }
214
215
216
217 /* TODO: Guard against recursive calling / calling init multiple times! */
218 VOID NotifyShims(DWORD dwReason, PVOID Info)
219 {
220 DWORD n;
221
222 for (n = 0; n < ARRAY_Size(&g_pShimInfo); ++n)
223 {
224 PSHIMMODULE pShimModule = *ARRAY_At(&g_pShimInfo, PSHIMMODULE, n);
225 if (!pShimModule->pNotifyShims)
226 continue;
227
228 pShimModule->pNotifyShims(dwReason, Info);
229 }
230 }
231
232
233
234 VOID SeiCheckComPlusImage(PVOID BaseAddress)
235 {
236 ULONG ComSectionSize;
237 g_bComPlusImage = RtlImageDirectoryEntryToData(BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR, &ComSectionSize) != NULL;
238
239 SHIMENG_INFO("COM+ executable %s\n", g_bComPlusImage ? "TRUE" : "FALSE");
240 }
241
242
243 PSHIMMODULE SeiGetShimModuleInfo(PVOID BaseAddress)
244 {
245 DWORD n;
246
247 for (n = 0; n < ARRAY_Size(&g_pShimInfo); ++n)
248 {
249 PSHIMMODULE pShimModule = *ARRAY_At(&g_pShimInfo, PSHIMMODULE, n);
250
251 if (pShimModule->BaseAddress == BaseAddress)
252 return pShimModule;
253 }
254 return NULL;
255 }
256
257 PSHIMMODULE SeiCreateShimModuleInfo(PCWSTR DllName, PVOID BaseAddress)
258 {
259 static const ANSI_STRING GetHookAPIs = RTL_CONSTANT_STRING("GetHookAPIs");
260 static const ANSI_STRING NotifyShims = RTL_CONSTANT_STRING("NotifyShims");
261 PSHIMMODULE* pData, Data;
262 PVOID pGetHookAPIs, pNotifyShims;
263
264 if (!NT_SUCCESS(LdrGetProcedureAddress(BaseAddress, (PANSI_STRING)&GetHookAPIs, 0, &pGetHookAPIs)) ||
265 !NT_SUCCESS(LdrGetProcedureAddress(BaseAddress, (PANSI_STRING)&NotifyShims, 0, &pNotifyShims)))
266 {
267 SHIMENG_WARN("Failed to resolve entry points for %S\n", DllName);
268 return NULL;
269 }
270
271 pData = ARRAY_Append(&g_pShimInfo, PSHIMMODULE);
272 if (!pData)
273 return NULL;
274
275 *pData = SeiAlloc(sizeof(SHIMMODULE));
276
277 Data = *pData;
278
279 RtlCreateUnicodeString(&Data->Name, DllName);
280 Data->BaseAddress = BaseAddress;
281
282 Data->pGetHookAPIs = pGetHookAPIs;
283 Data->pNotifyShims = pNotifyShims;
284
285 ARRAY_Init(&Data->EnabledShims, PSHIMINFO);
286
287 return Data;
288 }
289
290 PSHIMINFO SeiAppendHookInfo(PSHIMMODULE pShimModuleInfo, PHOOKAPIEX pHookApi, DWORD dwHookCount, PCWSTR ShimName)
291 {
292 PSHIMINFO* pData, Data;
293
294 pData = ARRAY_Append(&pShimModuleInfo->EnabledShims, PSHIMINFO);
295 if (!pData)
296 return NULL;
297
298 *pData = SeiAlloc(sizeof(SHIMINFO));
299 Data = *pData;
300
301 if (!Data)
302 return NULL;
303
304 Data->ShimName = SdbpStrDup(ShimName);
305 if (!Data->ShimName)
306 return NULL;
307
308 Data->pHookApi = pHookApi;
309 Data->dwHookCount = dwHookCount;
310 Data->pShimModule = pShimModuleInfo;
311 ARRAY_Init(&Data->InExclude, INEXCLUDE);
312 return Data;
313 }
314
315 PHOOKMODULEINFO SeiFindHookModuleInfo(PUNICODE_STRING ModuleName, PVOID BaseAddress)
316 {
317 DWORD n;
318
319 if (ModuleName == NULL && BaseAddress == NULL)
320 {
321 BaseAddress = NtCurrentPeb()->ImageBaseAddress;
322 }
323
324 for (n = 0; n < ARRAY_Size(&g_pHookArray); ++n)
325 {
326 PHOOKMODULEINFO pModuleInfo = ARRAY_At(&g_pHookArray, HOOKMODULEINFO, n);
327
328 if (BaseAddress && BaseAddress == pModuleInfo->BaseAddress)
329 return pModuleInfo;
330
331 if (!BaseAddress && RtlEqualUnicodeString(ModuleName, &pModuleInfo->Name, TRUE))
332 return pModuleInfo;
333 }
334
335 return NULL;
336 }
337
338 PHOOKMODULEINFO SeiFindHookModuleInfoForImportDescriptor(PBYTE DllBase, PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor)
339 {
340 UNICODE_STRING DllName;
341 PVOID DllHandle;
342 NTSTATUS Success;
343
344 if (!RtlCreateUnicodeStringFromAsciiz(&DllName, (PCSZ)(DllBase + ImportDescriptor->Name)))
345 {
346 SHIMENG_FAIL("Unable to convert dll name to unicode\n");
347 return NULL;
348 }
349
350 Success = LdrGetDllHandle(NULL, NULL, &DllName, &DllHandle);
351
352 if (!NT_SUCCESS(Success))
353 {
354 SHIMENG_FAIL("Unable to get module handle for %wZ (%p)\n", &DllName, DllBase);
355 RtlFreeUnicodeString(&DllName);
356
357 return NULL;
358 }
359 RtlFreeUnicodeString(&DllName);
360
361 return SeiFindHookModuleInfo(NULL, DllHandle);
362 }
363
364 static LPCWSTR SeiGetStringPtr(PDB pdb, TAGID tag, TAG type)
365 {
366 TAGID tagEntry = SdbFindFirstTag(pdb, tag, type);
367 if (tagEntry == TAGID_NULL)
368 return NULL;
369
370 return SdbGetStringTagPtr(pdb, tagEntry);
371 }
372
373 static DWORD SeiGetDWORD(PDB pdb, TAGID tag, TAG type)
374 {
375 TAGID tagEntry = SdbFindFirstTag(pdb, tag, type);
376 if (tagEntry == TAGID_NULL)
377 return 0;
378
379 return SdbReadDWORDTag(pdb, tagEntry, 0);
380 }
381
382 static QWORD SeiGetQWORD(PDB pdb, TAGID tag, TAG type)
383 {
384 TAGID tagEntry = SdbFindFirstTag(pdb, tag, type);
385 if (tagEntry == TAGID_NULL)
386 return 0;
387
388 return SdbReadQWORDTag(pdb, tagEntry, 0);
389 }
390
391 static VOID SeiAddShim(TAGREF trShimRef, PARRAY pShimRef)
392 {
393 TAGREF* Data;
394
395 Data = ARRAY_Append(pShimRef, TAGREF);
396 if (!Data)
397 return;
398
399 *Data = trShimRef;
400 }
401
402 static VOID SeiAddFlag(PDB pdb, TAGID tiFlagRef, PFLAGINFO pFlagInfo)
403 {
404 ULARGE_INTEGER Flag;
405
406 /* Resolve the FLAG_REF to the real FLAG node */
407 TAGID FlagTag = SeiGetDWORD(pdb, tiFlagRef, TAG_FLAG_TAGID);
408
409 if (FlagTag == TAGID_NULL)
410 return;
411
412 pFlagInfo->AppCompatFlags.QuadPart |= SeiGetQWORD(pdb, FlagTag, TAG_FLAG_MASK_KERNEL);
413 pFlagInfo->AppCompatFlagsUser.QuadPart |= SeiGetQWORD(pdb, FlagTag, TAG_FLAG_MASK_USER);
414 Flag.QuadPart = SeiGetQWORD(pdb, FlagTag, TAG_FLAG_PROCESSPARAM);
415 pFlagInfo->ProcessParameters_Flags |= Flag.LowPart;
416 }
417
418 /* Propagate layers to child processes */
419 static VOID SeiSetLayerEnvVar(LPCWSTR wszLayer)
420 {
421 NTSTATUS Status;
422 UNICODE_STRING VarName = RTL_CONSTANT_STRING(L"__COMPAT_LAYER");
423 UNICODE_STRING Value;
424
425 RtlInitUnicodeString(&Value, wszLayer);
426
427 Status = RtlSetEnvironmentVariable(NULL, &VarName, &Value);
428 if (NT_SUCCESS(Status))
429 SHIMENG_INFO("Set env var %wZ=%wZ\n", &VarName, &Value);
430 else
431 SHIMENG_FAIL("Failed to set %wZ: 0x%x\n", &VarName, Status);
432 }
433
434 #define MAX_LAYER_LENGTH 256
435
436 /* Translate all Exe and Layer entries to Shims, and propagate all layers */
437 static VOID SeiBuildShimRefArray(HSDB hsdb, SDBQUERYRESULT* pQuery, PARRAY pShimRef, PFLAGINFO pFlagInfo)
438 {
439 WCHAR wszLayerEnvVar[MAX_LAYER_LENGTH] = { 0 };
440 DWORD n;
441
442 for (n = 0; n < pQuery->dwExeCount; ++n)
443 {
444 PDB pdb;
445 TAGID tag;
446 if (SdbTagRefToTagID(hsdb, pQuery->atrExes[n], &pdb, &tag))
447 {
448 LPCWSTR ExeName = SeiGetStringPtr(pdb, tag, TAG_NAME);
449 TAGID ShimRef = SdbFindFirstTag(pdb, tag, TAG_SHIM_REF);
450 TAGID FlagRef = SdbFindFirstTag(pdb, tag, TAG_FLAG_REF);
451
452 if (ExeName)
453 SeiDbgPrint(SEI_MSG, NULL, "ShimInfo(Exe(%S))\n", ExeName);
454
455 while (ShimRef != TAGID_NULL)
456 {
457 TAGREF trShimRef;
458 if (SdbTagIDToTagRef(hsdb, pdb, ShimRef, &trShimRef))
459 SeiAddShim(trShimRef, pShimRef);
460
461 ShimRef = SdbFindNextTag(pdb, tag, ShimRef);
462 }
463
464 while (FlagRef != TAGID_NULL)
465 {
466 SeiAddFlag(pdb, FlagRef, pFlagInfo);
467
468 FlagRef = SdbFindNextTag(pdb, tag, FlagRef);
469 }
470 }
471 }
472
473
474 for (n = 0; n < pQuery->dwLayerCount; ++n)
475 {
476 PDB pdb;
477 TAGID tag;
478 if (SdbTagRefToTagID(hsdb, pQuery->atrLayers[n], &pdb, &tag))
479 {
480 LPCWSTR LayerName = SeiGetStringPtr(pdb, tag, TAG_NAME);
481 TAGID ShimRef = SdbFindFirstTag(pdb, tag, TAG_SHIM_REF);
482 TAGID FlagRef = SdbFindFirstTag(pdb, tag, TAG_FLAG_REF);
483
484 if (LayerName)
485 {
486 HRESULT hr;
487 SeiDbgPrint(SEI_MSG, NULL, "ShimInfo(Layer(%S))\n", LayerName);
488 if (wszLayerEnvVar[0])
489 StringCchCatW(wszLayerEnvVar, ARRAYSIZE(wszLayerEnvVar), L" ");
490 hr = StringCchCatW(wszLayerEnvVar, ARRAYSIZE(wszLayerEnvVar), LayerName);
491 if (!SUCCEEDED(hr))
492 {
493 SHIMENG_FAIL("Unable to append %S\n", LayerName);
494 }
495 }
496
497 while (ShimRef != TAGID_NULL)
498 {
499 TAGREF trShimRef;
500 if (SdbTagIDToTagRef(hsdb, pdb, ShimRef, &trShimRef))
501 SeiAddShim(trShimRef, pShimRef);
502
503 ShimRef = SdbFindNextTag(pdb, tag, ShimRef);
504 }
505
506 while (FlagRef != TAGID_NULL)
507 {
508 SeiAddFlag(pdb, FlagRef, pFlagInfo);
509
510 FlagRef = SdbFindNextTag(pdb, tag, FlagRef);
511 }
512 }
513 }
514 if (wszLayerEnvVar[0])
515 SeiSetLayerEnvVar(wszLayerEnvVar);
516 }
517
518 /* Given the hooks from one shim, find the relevant modules and store the combination of module + hook */
519 VOID SeiAddHooks(PHOOKAPIEX hooks, DWORD dwHookCount, PSHIMINFO pShim)
520 {
521 DWORD n, j;
522 UNICODE_STRING UnicodeModName;
523 WCHAR Buf[512];
524
525 RtlInitEmptyUnicodeString(&UnicodeModName, Buf, sizeof(Buf));
526
527 for (n = 0; n < dwHookCount; ++n)
528 {
529 ANSI_STRING AnsiString;
530 PVOID DllHandle;
531 PHOOKAPIEX hook = hooks + n;
532 PHOOKAPIEX* pHookApi;
533 PHOOKMODULEINFO HookModuleInfo;
534
535 RtlInitAnsiString(&AnsiString, hook->LibraryName);
536 if (!NT_SUCCESS(RtlAnsiStringToUnicodeString(&UnicodeModName, &AnsiString, FALSE)))
537 {
538 SHIMENG_FAIL("Unable to convert %s to Unicode\n", hook->LibraryName);
539 continue;
540 }
541
542 RtlInitAnsiString(&AnsiString, hook->FunctionName);
543 if (NT_SUCCESS(LdrGetDllHandle(NULL, 0, &UnicodeModName, &DllHandle)))
544 {
545 PVOID ProcAddress;
546
547
548 if (!NT_SUCCESS(LdrGetProcedureAddress(DllHandle, &AnsiString, 0, &ProcAddress)))
549 {
550 SHIMENG_FAIL("Unable to retrieve %s!%s\n", hook->LibraryName, hook->FunctionName);
551 continue;
552 }
553
554 HookModuleInfo = SeiFindHookModuleInfo(NULL, DllHandle);
555 hook->OriginalFunction = ProcAddress;
556 }
557 else
558 {
559 HookModuleInfo = SeiFindHookModuleInfo(&UnicodeModName, NULL);
560 DllHandle = NULL;
561 }
562
563 if (!HookModuleInfo)
564 {
565 HookModuleInfo = ARRAY_Append(&g_pHookArray, HOOKMODULEINFO);
566 if (!HookModuleInfo)
567 continue;
568
569 HookModuleInfo->BaseAddress = DllHandle;
570 ARRAY_Init(&HookModuleInfo->HookApis, PHOOKAPIEX);
571 RtlCreateUnicodeString(&HookModuleInfo->Name, UnicodeModName.Buffer);
572 }
573
574 hook->pShimInfo = pShim;
575
576 for (j = 0; j < ARRAY_Size(&HookModuleInfo->HookApis); ++j)
577 {
578 PHOOKAPIEX HookApi = *ARRAY_At(&HookModuleInfo->HookApis, PHOOKAPIEX, j);
579 int CmpResult = strcmp(hook->FunctionName, HookApi->FunctionName);
580 if (CmpResult == 0)
581 {
582 /* Multiple hooks on one function? --> use ApiLink */
583 SHIMENG_FAIL("Multiple hooks on one API is not yet supported!\n");
584 ASSERT(0);
585 }
586 }
587 pHookApi = ARRAY_Append(&HookModuleInfo->HookApis, PHOOKAPIEX);
588 *pHookApi = hook;
589 }
590 }
591
592 typedef FARPROC(WINAPI* GETPROCADDRESSPROC)(HINSTANCE, LPCSTR);
593
594 /* Check if we should fake the return from GetProcAddress (because we also redirected the iat for this module) */
595 FARPROC WINAPI StubGetProcAddress(HINSTANCE hModule, LPCSTR lpProcName)
596 {
597 char szOrdProcName[10] = "";
598 LPCSTR lpPrintName = lpProcName;
599 PVOID Addr = _ReturnAddress();
600 PHOOKMODULEINFO HookModuleInfo;
601 FARPROC proc = ((GETPROCADDRESSPROC)g_IntHookEx[0].OriginalFunction)(hModule, lpProcName);
602
603 if ((DWORD_PTR)lpProcName <= MAXUSHORT)
604 {
605 sprintf(szOrdProcName, "#%Iu", (DWORD_PTR)lpProcName);
606 lpPrintName = szOrdProcName;
607 }
608
609 Addr = SeiGetModuleFromAddress(Addr);
610 if (SE_IsShimDll(Addr))
611 {
612 SHIMENG_MSG("Not touching GetProcAddress for shim dll (%p!%s)", hModule, lpPrintName);
613 return proc;
614 }
615
616 SHIMENG_INFO("(GetProcAddress(%p!%s) => %p\n", hModule, lpPrintName, proc);
617
618 HookModuleInfo = SeiFindHookModuleInfo(NULL, hModule);
619
620 /* FIXME: Ordinal not yet supported */
621 if (HookModuleInfo && HIWORD(lpProcName))
622 {
623 DWORD n;
624 for (n = 0; n < ARRAY_Size(&HookModuleInfo->HookApis); ++n)
625 {
626 PHOOKAPIEX HookApi = *ARRAY_At(&HookModuleInfo->HookApis, PHOOKAPIEX, n);
627 int CmpResult = strcmp(lpProcName, HookApi->FunctionName);
628 if (CmpResult == 0)
629 {
630 SHIMENG_MSG("Redirecting %p to %p\n", proc, HookApi->ReplacementFunction);
631 proc = HookApi->ReplacementFunction;
632 break;
633 }
634 }
635 }
636
637 return proc;
638 }
639
640 /* Walk all shim modules / enabled shims, and add their hooks */
641 VOID SeiResolveAPIs(VOID)
642 {
643 DWORD mod, n;
644
645 /* Enumerate all Shim modules */
646 for (mod = 0; mod < ARRAY_Size(&g_pShimInfo); ++mod)
647 {
648 PSHIMMODULE pShimModule = *ARRAY_At(&g_pShimInfo, PSHIMMODULE, mod);
649 DWORD dwShimCount = ARRAY_Size(&pShimModule->EnabledShims);
650
651 /* Enumerate all Shims */
652 for (n = 0; n < dwShimCount; ++n)
653 {
654 PSHIMINFO pShim = *ARRAY_At(&pShimModule->EnabledShims, PSHIMINFO, n);
655
656 PHOOKAPIEX hooks = pShim->pHookApi;
657 DWORD dwHookCount = pShim->dwHookCount;
658
659 SeiAddHooks(hooks, dwHookCount, pShim);
660 }
661 }
662 }
663
664 /* If we hooked something, we should also redirect GetProcAddress */
665 VOID SeiAddInternalHooks(DWORD dwNumHooks)
666 {
667 if (dwNumHooks == 0)
668 {
669 g_bInternalHooksUsed = FALSE;
670 return;
671 }
672
673 SeiAddHooks(g_IntHookEx, ARRAYSIZE(g_IntHookEx), NULL);
674 g_bInternalHooksUsed = TRUE;
675 }
676
677 /* Patch one function in the iat */
678 VOID SeiPatchNewImport(PIMAGE_THUNK_DATA FirstThunk, PHOOKAPIEX HookApi, PLDR_DATA_TABLE_ENTRY LdrEntry)
679 {
680 ULONG OldProtection = 0;
681 PVOID Ptr;
682 SIZE_T Size;
683 NTSTATUS Status;
684
685 SHIMENG_INFO("Hooking API \"%s!%s\" for DLL \"%wZ\"\n", HookApi->LibraryName, HookApi->FunctionName, &LdrEntry->BaseDllName);
686
687 Ptr = &FirstThunk->u1.Function;
688 Size = sizeof(FirstThunk->u1.Function);
689 Status = NtProtectVirtualMemory(NtCurrentProcess(), &Ptr, &Size, PAGE_EXECUTE_READWRITE, &OldProtection);
690
691 if (!NT_SUCCESS(Status))
692 {
693 SHIMENG_FAIL("Unable to unprotect 0x%p\n", &FirstThunk->u1.Function);
694 return;
695 }
696
697 SHIMENG_INFO("changing 0x%p to 0x%p\n", FirstThunk->u1.Function, HookApi->ReplacementFunction);
698 #ifdef _WIN64
699 FirstThunk->u1.Function = (ULONGLONG)HookApi->ReplacementFunction;
700 #else
701 FirstThunk->u1.Function = (DWORD)HookApi->ReplacementFunction;
702 #endif
703
704 Size = sizeof(FirstThunk->u1.Function);
705 Status = NtProtectVirtualMemory(NtCurrentProcess(), &Ptr, &Size, OldProtection, &OldProtection);
706
707 if (!NT_SUCCESS(Status))
708 {
709 SHIMENG_WARN("Unable to reprotect 0x%p\n", &FirstThunk->u1.Function);
710 }
711 }
712
713
714 PINEXCLUDE SeiFindInExclude(PARRAY InExclude, PCUNICODE_STRING DllName)
715 {
716 DWORD n;
717
718 for (n = 0; n < ARRAY_Size(InExclude); ++n)
719 {
720 PINEXCLUDE InEx = ARRAY_At(InExclude, INEXCLUDE, n);
721
722 if (RtlEqualUnicodeString(&InEx->Module, DllName, TRUE))
723 return InEx;
724 }
725
726 return NULL;
727 }
728
729 BOOL SeiIsExcluded(PLDR_DATA_TABLE_ENTRY LdrEntry, PHOOKAPIEX HookApi)
730 {
731 PSHIMINFO pShimInfo = HookApi->pShimInfo;
732 PINEXCLUDE InExclude;
733 BOOL IsExcluded = FALSE;
734
735 if (!pShimInfo)
736 {
737 /* Internal hook, do not exclude it */
738 return FALSE;
739 }
740
741 /* By default, everything from System32 or WinSxs is excluded */
742 if (RtlPrefixUnicodeString(&g_System32Directory, &LdrEntry->FullDllName, TRUE) ||
743 RtlPrefixUnicodeString(&g_SxsDirectory, &LdrEntry->FullDllName, TRUE))
744 IsExcluded = TRUE;
745
746 InExclude = SeiFindInExclude(&pShimInfo->InExclude, &LdrEntry->BaseDllName);
747 if (InExclude)
748 {
749 /* If it is on the 'exclude' list, bail out */
750 if (!InExclude->Include)
751 {
752 SHIMENG_INFO("Module '%wZ' excluded for shim %S, API '%s!%s', because it on in the exclude list.\n",
753 &LdrEntry->BaseDllName, pShimInfo->ShimName, HookApi->LibraryName, HookApi->FunctionName);
754
755 return TRUE;
756 }
757 /* If it is on the 'include' list, override System32 / Winsxs check. */
758 if (IsExcluded)
759 {
760 SHIMENG_INFO("Module '%wZ' included for shim %S, API '%s!%s', because it is on the include list.\n",
761 &LdrEntry->BaseDllName, pShimInfo->ShimName, HookApi->LibraryName, HookApi->FunctionName);
762
763 }
764 IsExcluded = FALSE;
765 }
766
767 if (IsExcluded)
768 {
769 SHIMENG_INFO("Module '%wZ' excluded for shim %S, API '%s!%s', because it is in System32/WinSXS.\n",
770 &LdrEntry->BaseDllName, pShimInfo->ShimName, HookApi->LibraryName, HookApi->FunctionName);
771 }
772
773 return IsExcluded;
774 }
775
776 VOID SeiAppendInExclude(PARRAY dest, PCWSTR ModuleName, BOOL IsInclude)
777 {
778 PINEXCLUDE InExclude;
779 UNICODE_STRING ModuleNameU;
780 RtlInitUnicodeString(&ModuleNameU, ModuleName);
781
782 InExclude = SeiFindInExclude(dest, &ModuleNameU);
783 if (InExclude)
784 {
785 InExclude->Include = IsInclude;
786 return;
787 }
788
789 InExclude = ARRAY_Append(dest, INEXCLUDE);
790 if (InExclude)
791 {
792 PCWSTR ModuleNameCopy = SdbpStrDup(ModuleName);
793 RtlInitUnicodeString(&InExclude->Module, ModuleNameCopy);
794 InExclude->Include = IsInclude;
795 }
796 }
797
798 /* Read the INEXCLUD tags from a given parent tag */
799 VOID SeiReadInExclude(PDB pdb, TAGID parent, PARRAY dest)
800 {
801 TAGID InExcludeTag;
802
803 InExcludeTag = SdbFindFirstTag(pdb, parent, TAG_INEXCLUD);
804
805 while (InExcludeTag != TAGID_NULL)
806 {
807 PCWSTR ModuleName;
808 TAGID ModuleTag = SdbFindFirstTag(pdb, InExcludeTag, TAG_MODULE);
809 TAGID IncludeTag = SdbFindFirstTag(pdb, InExcludeTag, TAG_INCLUDE);
810
811 ModuleName = SdbGetStringTagPtr(pdb, ModuleTag);
812 if (ModuleName)
813 {
814 SeiAppendInExclude(dest, ModuleName, IncludeTag != TAGID_NULL);
815 }
816 else
817 {
818 SHIMENG_WARN("INEXCLUDE without Module: 0x%x\n", InExcludeTag);
819 }
820
821 InExcludeTag = SdbFindNextTag(pdb, parent, InExcludeTag);
822 }
823 }
824
825 VOID SeiBuildGlobalInclExclList(HSDB hsdb)
826 {
827 PDB pdb;
828 TAGREF tr = TAGREF_ROOT;
829 TAGID root, db, library;
830
831 if (!SdbTagRefToTagID(hsdb, tr, &pdb, &root))
832 {
833 SHIMENG_WARN("Unable to resolve database root\n");
834 return;
835 }
836 db = SdbFindFirstTag(pdb, root, TAG_DATABASE);
837 if (db == TAGID_NULL)
838 {
839 SHIMENG_WARN("Unable to resolve database\n");
840 return;
841 }
842 library = SdbFindFirstTag(pdb, db, TAG_LIBRARY);
843 if (library == TAGID_NULL)
844 {
845 SHIMENG_WARN("Unable to resolve library\n");
846 return;
847 }
848
849 SeiReadInExclude(pdb, library, &g_InExclude);
850 }
851
852 VOID SeiBuildInclExclList(PDB pdb, TAGID ShimTag, PSHIMINFO pShimInfo)
853 {
854 DWORD n;
855
856 /* First duplicate the global in/excludes */
857 for (n = 0; n < ARRAY_Size(&g_InExclude); ++n)
858 {
859 PINEXCLUDE InEx = ARRAY_At(&g_InExclude, INEXCLUDE, n);
860 SeiAppendInExclude(&pShimInfo->InExclude, InEx->Module.Buffer, InEx->Include);
861 }
862
863 /* Now read this shim's in/excludes (possibly overriding the global ones) */
864 SeiReadInExclude(pdb, ShimTag, &pShimInfo->InExclude);
865 }
866
867 /* Given one loaded module, redirect (hook) all functions from the iat that are registered by shims */
868 VOID SeiHookImports(PLDR_DATA_TABLE_ENTRY LdrEntry)
869 {
870 ULONG Size;
871 PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor;
872 PBYTE DllBase = LdrEntry->DllBase;
873
874 if (SE_IsShimDll(DllBase) || g_hInstance == LdrEntry->DllBase ||
875 (g_LoadingShimDll.Buffer && RtlEqualUnicodeString(&g_LoadingShimDll, &LdrEntry->BaseDllName, TRUE)))
876 {
877 SHIMENG_INFO("Skipping shim module 0x%p \"%wZ\"\n", LdrEntry->DllBase, &LdrEntry->BaseDllName);
878 return;
879 }
880
881 if (LdrEntry->Flags & LDRP_COMPAT_DATABASE_PROCESSED)
882 {
883 SHIMENG_INFO("Skipping module 0x%p \"%wZ\" because it was already processed\n", LdrEntry->DllBase, &LdrEntry->BaseDllName);
884 return;
885 }
886
887 ImportDescriptor = RtlImageDirectoryEntryToData(DllBase, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &Size);
888 if (!ImportDescriptor)
889 {
890 SHIMENG_INFO("Skipping module 0x%p \"%wZ\" due to no iat found\n", LdrEntry->DllBase, &LdrEntry->BaseDllName);
891 return;
892 }
893
894 SHIMENG_INFO("Hooking module 0x%p \"%wZ\"\n", LdrEntry->DllBase, &LdrEntry->BaseDllName);
895
896 for ( ;ImportDescriptor->Name && ImportDescriptor->OriginalFirstThunk; ImportDescriptor++)
897 {
898 PHOOKMODULEINFO HookModuleInfo;
899
900 /* Do we have hooks for this module? */
901 HookModuleInfo = SeiFindHookModuleInfoForImportDescriptor(DllBase, ImportDescriptor);
902
903 if (HookModuleInfo)
904 {
905 PIMAGE_THUNK_DATA OriginalThunk, FirstThunk;
906 DWORD n;
907
908 for (n = 0; n < ARRAY_Size(&HookModuleInfo->HookApis); ++n)
909 {
910 DWORD dwFound = 0;
911 PHOOKAPIEX HookApi = *ARRAY_At(&HookModuleInfo->HookApis, PHOOKAPIEX, n);
912
913 /* Check if this module should be excluded from being hooked (system32/winsxs, global or shim exclude) */
914 if (SeiIsExcluded(LdrEntry, HookApi))
915 {
916 continue;
917 }
918
919 OriginalThunk = (PIMAGE_THUNK_DATA)(DllBase + ImportDescriptor->OriginalFirstThunk);
920 FirstThunk = (PIMAGE_THUNK_DATA)(DllBase + ImportDescriptor->FirstThunk);
921
922 /* Walk all imports */
923 for (;OriginalThunk->u1.AddressOfData && FirstThunk->u1.Function; OriginalThunk++, FirstThunk++)
924 {
925 if (!IMAGE_SNAP_BY_ORDINAL32(OriginalThunk->u1.AddressOfData))
926 {
927 PIMAGE_IMPORT_BY_NAME ImportName;
928
929 ImportName = (PIMAGE_IMPORT_BY_NAME)(DllBase + OriginalThunk->u1.AddressOfData);
930 if (!strcmp((PCSTR)ImportName->Name, HookApi->FunctionName))
931 {
932 SeiPatchNewImport(FirstThunk, HookApi, LdrEntry);
933
934 /* Sadly, iat does not have to be sorted, and can even contain duplicate entries. */
935 dwFound++;
936 }
937 }
938 else
939 {
940 SHIMENG_FAIL("Ordinals not yet supported\n");
941 ASSERT(0);
942 }
943 }
944
945 if (dwFound != 1)
946 {
947 /* One entry not found. */
948 if (!dwFound)
949 SHIMENG_INFO("Entry \"%s!%s\" not found for \"%wZ\"\n", HookApi->LibraryName, HookApi->FunctionName, &LdrEntry->BaseDllName);
950 else
951 SHIMENG_INFO("Entry \"%s!%s\" found %d times for \"%wZ\"\n", HookApi->LibraryName, HookApi->FunctionName, dwFound, &LdrEntry->BaseDllName);
952 }
953 }
954 }
955 }
956
957 /* Mark this module as processed. */
958 LdrEntry->Flags |= LDRP_COMPAT_DATABASE_PROCESSED;
959 }
960
961
962 VOID PatchNewModules(PPEB Peb)
963 {
964 PLIST_ENTRY ListHead, ListEntry;
965 PLDR_DATA_TABLE_ENTRY LdrEntry;
966
967 ListHead = &NtCurrentPeb()->Ldr->InLoadOrderModuleList;
968 ListEntry = ListHead->Flink;
969
970 while (ListHead != ListEntry)
971 {
972 LdrEntry = CONTAINING_RECORD(ListEntry, LDR_DATA_TABLE_ENTRY, InLoadOrderLinks);
973 SeiHookImports(LdrEntry);
974
975 ListEntry = ListEntry->Flink;
976 }
977 }
978
979
980 VOID SeiInitPaths(VOID)
981 {
982 #define SYSTEM32 L"\\system32"
983 #define WINSXS L"\\winsxs"
984
985 PWSTR WindowsDirectory = SdbpStrDup(SharedUserData->NtSystemRoot);
986 RtlInitUnicodeString(&g_WindowsDirectory, WindowsDirectory);
987
988 g_System32Directory.MaximumLength = g_WindowsDirectory.Length + SdbpStrsize(SYSTEM32);
989 g_System32Directory.Buffer = SdbpAlloc(g_System32Directory.MaximumLength);
990 RtlCopyUnicodeString(&g_System32Directory, &g_WindowsDirectory);
991 RtlAppendUnicodeToString(&g_System32Directory, SYSTEM32);
992
993 g_SxsDirectory.MaximumLength = g_WindowsDirectory.Length + SdbpStrsize(WINSXS);
994 g_SxsDirectory.Buffer = SdbpAlloc(g_SxsDirectory.MaximumLength);
995 RtlCopyUnicodeString(&g_SxsDirectory, &g_WindowsDirectory);
996 RtlAppendUnicodeToString(&g_SxsDirectory, WINSXS);
997
998 #undef SYSTEM32
999 #undef WINSXS
1000 }
1001
1002 VOID SeiInit(PUNICODE_STRING ProcessImage, HSDB hsdb, SDBQUERYRESULT* pQuery)
1003 {
1004 DWORD n;
1005 ARRAY ShimRefArray;
1006 DWORD dwTotalHooks = 0;
1007 FLAGINFO ShimFlags;
1008
1009 PPEB Peb = NtCurrentPeb();
1010
1011 /* We should only be called once! */
1012 ASSERT(g_pShimInfo.ItemSize__ == 0);
1013
1014 ARRAY_Init(&ShimRefArray, TAGREF);
1015 ARRAY_Init(&g_pShimInfo, PSHIMMODULE);
1016 ARRAY_Init(&g_pHookArray, HOOKMODULEINFO);
1017 ARRAY_Init(&g_InExclude, INEXCLUDE);
1018 RtlZeroMemory(&ShimFlags, sizeof(ShimFlags));
1019
1020 SeiInitPaths();
1021
1022 SeiCheckComPlusImage(Peb->ImageBaseAddress);
1023
1024 /* TODO:
1025 if (pQuery->trApphelp)
1026 SeiDisplayAppHelp(?pQuery->trApphelp?);
1027 */
1028
1029 SeiDbgPrint(SEI_MSG, NULL, "ShimInfo(ExePath(%wZ))\n", ProcessImage);
1030 SeiBuildShimRefArray(hsdb, pQuery, &ShimRefArray, &ShimFlags);
1031 if (ShimFlags.AppCompatFlags.QuadPart)
1032 {
1033 SeiDbgPrint(SEI_MSG, NULL, "Using KERNEL apphack flags 0x%I64x\n", ShimFlags.AppCompatFlags.QuadPart);
1034 Peb->AppCompatFlags.QuadPart |= ShimFlags.AppCompatFlags.QuadPart;
1035 }
1036 if (ShimFlags.AppCompatFlagsUser.QuadPart)
1037 {
1038 SeiDbgPrint(SEI_MSG, NULL, "Using USER apphack flags 0x%I64x\n", ShimFlags.AppCompatFlagsUser.QuadPart);
1039 Peb->AppCompatFlagsUser.QuadPart |= ShimFlags.AppCompatFlagsUser.QuadPart;
1040 }
1041 if (ShimFlags.ProcessParameters_Flags)
1042 {
1043 SeiDbgPrint(SEI_MSG, NULL, "Using ProcessParameters flags 0x%x\n", ShimFlags.ProcessParameters_Flags);
1044 Peb->ProcessParameters->Flags |= ShimFlags.ProcessParameters_Flags;
1045 }
1046 SeiDbgPrint(SEI_MSG, NULL, "ShimInfo(Complete)\n");
1047
1048 SHIMENG_INFO("Got %d shims\n", ARRAY_Size(&ShimRefArray));
1049 SeiBuildGlobalInclExclList(hsdb);
1050
1051 /* Walk all shims referenced (in layers + exes), and load their modules */
1052 for (n = 0; n < ARRAY_Size(&ShimRefArray); ++n)
1053 {
1054 PDB pdb;
1055 TAGID ShimRef;
1056
1057 TAGREF tr = *ARRAY_At(&ShimRefArray, TAGREF, n);
1058
1059 if (SdbTagRefToTagID(hsdb, tr, &pdb, &ShimRef))
1060 {
1061 LPCWSTR ShimName, DllName, CommandLine = NULL;
1062 TAGID ShimTag;
1063 WCHAR FullNameBuffer[MAX_PATH];
1064 UNICODE_STRING UnicodeDllName;
1065 PVOID BaseAddress;
1066 PSHIMMODULE pShimModuleInfo = NULL;
1067 ANSI_STRING AnsiCommandLine = RTL_CONSTANT_STRING("");
1068 PSHIMINFO pShimInfo = NULL;
1069 PHOOKAPIEX pHookApi;
1070 DWORD dwHookCount;
1071
1072 ShimName = SeiGetStringPtr(pdb, ShimRef, TAG_NAME);
1073 if (!ShimName)
1074 {
1075 SHIMENG_FAIL("Failed to retrieve the name for 0x%x\n", tr);
1076 continue;
1077 }
1078
1079 CommandLine = SeiGetStringPtr(pdb, ShimRef, TAG_COMMAND_LINE);
1080 if (CommandLine && *CommandLine)
1081 {
1082 RtlInitUnicodeString(&UnicodeDllName, CommandLine);
1083 if (NT_SUCCESS(RtlUnicodeStringToAnsiString(&AnsiCommandLine, &UnicodeDllName, TRUE)))
1084 {
1085 SHIMENG_INFO("COMMAND LINE %s for %S", AnsiCommandLine.Buffer, ShimName);
1086 }
1087 else
1088 {
1089 AnsiCommandLine.Buffer = "";
1090 CommandLine = NULL;
1091 }
1092 }
1093
1094 ShimTag = SeiGetDWORD(pdb, ShimRef, TAG_SHIM_TAGID);
1095 if (!ShimTag)
1096 {
1097 SHIMENG_FAIL("Failed to resolve %S to a shim\n", ShimName);
1098 continue;
1099 }
1100
1101 if (!SUCCEEDED(SdbGetAppPatchDir(NULL, FullNameBuffer, ARRAYSIZE(FullNameBuffer))))
1102 {
1103 SHIMENG_WARN("Failed to get the AppPatch dir\n");
1104 continue;
1105 }
1106
1107 DllName = SeiGetStringPtr(pdb, ShimTag, TAG_DLLFILE);
1108 if (DllName == NULL ||
1109 !SUCCEEDED(StringCchCatW(FullNameBuffer, ARRAYSIZE(FullNameBuffer), L"\\")) ||
1110 !SUCCEEDED(StringCchCatW(FullNameBuffer, ARRAYSIZE(FullNameBuffer), DllName)))
1111 {
1112 SHIMENG_WARN("Failed to build a full path for %S\n", ShimName);
1113 continue;
1114 }
1115
1116 RtlInitUnicodeString(&g_LoadingShimDll, DllName);
1117 RtlInitUnicodeString(&UnicodeDllName, FullNameBuffer);
1118 if (NT_SUCCESS(LdrGetDllHandle(NULL, NULL, &UnicodeDllName, &BaseAddress)))
1119 {
1120 /* This shim dll was already loaded, let's find it */
1121 pShimModuleInfo = SeiGetShimModuleInfo(BaseAddress);
1122 }
1123 else if (!NT_SUCCESS(LdrLoadDll(NULL, NULL, &UnicodeDllName, &BaseAddress)))
1124 {
1125 SHIMENG_WARN("Failed to load %wZ for %S\n", &UnicodeDllName, ShimName);
1126 continue;
1127 }
1128 RtlInitUnicodeString(&g_LoadingShimDll, NULL);
1129 /* No shim module found (or we just loaded it) */
1130 if (!pShimModuleInfo)
1131 {
1132 pShimModuleInfo = SeiCreateShimModuleInfo(DllName, BaseAddress);
1133 if (!pShimModuleInfo)
1134 {
1135 SHIMENG_FAIL("Failed to allocate ShimInfo for %S\n", DllName);
1136 continue;
1137 }
1138 }
1139
1140 SHIMENG_INFO("Shim DLL 0x%p \"%wZ\" loaded\n", BaseAddress, &UnicodeDllName);
1141 SHIMENG_INFO("Using SHIM \"%S!%S\"\n", DllName, ShimName);
1142
1143 /* Ask this shim what hooks it needs (and pass along the commandline) */
1144 pHookApi = pShimModuleInfo->pGetHookAPIs(AnsiCommandLine.Buffer, ShimName, &dwHookCount);
1145 SHIMENG_INFO("GetHookAPIs returns %d hooks for DLL \"%wZ\" SHIM \"%S\"\n", dwHookCount, &UnicodeDllName, ShimName);
1146 if (dwHookCount)
1147 pShimInfo = SeiAppendHookInfo(pShimModuleInfo, pHookApi, dwHookCount, ShimName);
1148
1149 /* If this shim has hooks, create the include / exclude lists */
1150 if (pShimInfo)
1151 SeiBuildInclExclList(pdb, ShimTag, pShimInfo);
1152
1153 if (CommandLine && *CommandLine)
1154 RtlFreeAnsiString(&AnsiCommandLine);
1155
1156 dwTotalHooks += dwHookCount;
1157 }
1158 }
1159
1160 SeiAddInternalHooks(dwTotalHooks);
1161 SeiResolveAPIs();
1162 PatchNewModules(Peb);
1163 }
1164
1165
1166 /* Load the database + unpack the shim data (if this process is allowed) */
1167 BOOL SeiGetShimData(PUNICODE_STRING ProcessImage, PVOID pShimData, HSDB* pHsdb, SDBQUERYRESULT* pQuery)
1168 {
1169 static const UNICODE_STRING ForbiddenShimmingApps[] = {
1170 RTL_CONSTANT_STRING(L"ntsd.exe"),
1171 RTL_CONSTANT_STRING(L"windbg.exe"),
1172 #if WINVER >= 0x600
1173 RTL_CONSTANT_STRING(L"slsvc.exe"),
1174 #endif
1175 };
1176 static const UNICODE_STRING BackSlash = RTL_CONSTANT_STRING(L"\\");
1177 static const UNICODE_STRING ForwdSlash = RTL_CONSTANT_STRING(L"/");
1178 UNICODE_STRING ProcessName;
1179 USHORT Back, Forward;
1180 HSDB hsdb;
1181 DWORD n;
1182
1183 if (!NT_SUCCESS(RtlFindCharInUnicodeString(RTL_FIND_CHAR_IN_UNICODE_STRING_START_AT_END, ProcessImage, &BackSlash, &Back)))
1184 Back = 0;
1185
1186 if (!NT_SUCCESS(RtlFindCharInUnicodeString(RTL_FIND_CHAR_IN_UNICODE_STRING_START_AT_END, ProcessImage, &ForwdSlash, &Forward)))
1187 Forward = 0;
1188
1189 if (Back < Forward)
1190 Back = Forward;
1191
1192 if (Back)
1193 Back += sizeof(WCHAR);
1194
1195 ProcessName.Buffer = ProcessImage->Buffer + Back / sizeof(WCHAR);
1196 ProcessName.Length = ProcessImage->Length - Back;
1197 ProcessName.MaximumLength = ProcessImage->MaximumLength - Back;
1198
1199 for (n = 0; n < ARRAYSIZE(ForbiddenShimmingApps); ++n)
1200 {
1201 if (RtlEqualUnicodeString(&ProcessName, ForbiddenShimmingApps + n, TRUE))
1202 {
1203 SHIMENG_MSG("Not shimming %wZ\n", ForbiddenShimmingApps + n);
1204 return FALSE;
1205 }
1206 }
1207
1208 /* We should probably load all db's here, but since we do not support that yet... */
1209 hsdb = SdbInitDatabase(HID_DOS_PATHS | SDB_DATABASE_MAIN_SHIM, NULL);
1210 if (hsdb)
1211 {
1212 if (SdbUnpackAppCompatData(hsdb, ProcessImage->Buffer, pShimData, pQuery))
1213 {
1214 *pHsdb = hsdb;
1215 return TRUE;
1216 }
1217 SdbReleaseDatabase(hsdb);
1218 }
1219 return FALSE;
1220 }
1221
1222
1223
1224 VOID NTAPI SE_InstallBeforeInit(PUNICODE_STRING ProcessImage, PVOID pShimData)
1225 {
1226 HSDB hsdb = NULL;
1227 SDBQUERYRESULT QueryResult = { { 0 } };
1228 SHIMENG_INFO("(%wZ, %p)\n", ProcessImage, pShimData);
1229
1230 if (!SeiGetShimData(ProcessImage, pShimData, &hsdb, &QueryResult))
1231 {
1232 SHIMENG_FAIL("Failed to get shim data\n");
1233 return;
1234 }
1235
1236 g_bShimDuringInit = TRUE;
1237 SeiInit(ProcessImage, hsdb, &QueryResult);
1238 g_bShimDuringInit = FALSE;
1239
1240 SdbReleaseDatabase(hsdb);
1241 }
1242
1243 VOID NTAPI SE_InstallAfterInit(PUNICODE_STRING ProcessImage, PVOID pShimData)
1244 {
1245 NotifyShims(SHIM_NOTIFY_ATTACH, NULL);
1246 }
1247
1248 VOID NTAPI SE_ProcessDying(VOID)
1249 {
1250 SHIMENG_MSG("()\n");
1251 NotifyShims(SHIM_NOTIFY_DETACH, NULL);
1252 }
1253
1254 VOID WINAPI SE_DllLoaded(PLDR_DATA_TABLE_ENTRY LdrEntry)
1255 {
1256 SHIMENG_INFO("%sINIT. loading DLL \"%wZ\"\n", g_bShimDuringInit ? "" : "AFTER ", &LdrEntry->BaseDllName);
1257
1258 SeiHookImports(LdrEntry);
1259
1260 NotifyShims(SHIM_REASON_DLL_LOAD, LdrEntry);
1261 }
1262
1263 VOID WINAPI SE_DllUnloaded(PLDR_DATA_TABLE_ENTRY LdrEntry)
1264 {
1265 SHIMENG_INFO("(%p)\n", LdrEntry);
1266
1267 /* Should we unhook here? */
1268
1269 NotifyShims(SHIM_REASON_DLL_UNLOAD, LdrEntry);
1270 }
1271
1272 BOOL WINAPI SE_IsShimDll(PVOID BaseAddress)
1273 {
1274 SHIMENG_INFO("(%p)\n", BaseAddress);
1275
1276 return SeiGetShimModuleInfo(BaseAddress) != NULL;
1277 }
1278