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)
8 #define WIN32_NO_STATUS
13 /* Make sure we don't include apphelp logging */
14 #define APPHELP_NOSDBPAPI
20 FARPROC WINAPI
StubGetProcAddress(HINSTANCE hModule
, LPCSTR lpProcName
);
21 BOOL WINAPI
SE_IsShimDll(PVOID BaseAddress
);
24 extern HMODULE g_hInstance
;
25 static UNICODE_STRING g_WindowsDirectory
;
26 static UNICODE_STRING g_System32Directory
;
27 static UNICODE_STRING g_SxsDirectory
;
28 ULONG g_ShimEngDebugLevel
= 0xffffffff;
29 BOOL g_bComPlusImage
= FALSE
;
30 BOOL g_bShimDuringInit
= FALSE
;
31 BOOL g_bInternalHooksUsed
= FALSE
;
32 static ARRAY g_pShimInfo
; /* PSHIMMODULE */
33 static ARRAY g_pHookArray
; /* HOOKMODULEINFO */
34 static ARRAY g_InExclude
; /* INEXCLUDE */
36 /* If we have setup a hook for a function, we should also redirect GetProcAddress for this function */
37 HOOKAPIEX g_IntHookEx
[] =
40 "kernel32.dll", /* LibraryName */
41 "GetProcAddress", /* FunctionName */
42 StubGetProcAddress
, /* ReplacementFunction*/
43 NULL
, /* OriginalFunction */
49 static inline BOOL
ARRAY_InitWorker(PARRAY Array
, DWORD ItemSize
)
52 Array
->Size__
= Array
->MaxSize__
= 0;
53 Array
->ItemSize__
= ItemSize
;
58 static inline BOOL
ARRAY_EnsureSize(PARRAY Array
, DWORD ItemSize
, DWORD GrowWith
)
64 ASSERT(ItemSize
== Array
->ItemSize__
);
66 if (Array
->MaxSize__
> Array
->Size__
)
69 Count
= Array
->Size__
+ GrowWith
;
70 pNewData
= SeiAlloc(Count
* ItemSize
);
74 SHIMENG_FAIL("Failed to allocate %d bytes\n", Count
* ItemSize
);
77 Array
->MaxSize__
= Count
;
81 memcpy(pNewData
, Array
->Data__
, Array
->Size__
* ItemSize
);
82 SeiFree(Array
->Data__
);
84 Array
->Data__
= pNewData
;
89 static inline PVOID
ARRAY_AppendWorker(PARRAY Array
, DWORD ItemSize
, DWORD GrowWith
)
93 if (!ARRAY_EnsureSize(Array
, ItemSize
, GrowWith
))
96 pData
= Array
->Data__
;
97 pData
+= (Array
->Size__
* ItemSize
);
103 static inline PVOID
ARRAY_AtWorker(PARRAY Array
, DWORD ItemSize
, DWORD n
)
108 ASSERT(ItemSize
== Array
->ItemSize__
);
109 ASSERT(n
< Array
->Size__
);
111 pData
= Array
->Data__
;
112 return pData
+ (n
* ItemSize
);
116 #define ARRAY_Init(Array, TypeOfArray) ARRAY_InitWorker((Array), sizeof(TypeOfArray))
117 #define ARRAY_Append(Array, TypeOfArray) (TypeOfArray*)ARRAY_AppendWorker((Array), sizeof(TypeOfArray), 5)
118 #define ARRAY_At(Array, TypeOfArray, at) (TypeOfArray*)ARRAY_AtWorker((Array), sizeof(TypeOfArray), at)
119 #define ARRAY_Size(Array) (Array)->Size__
122 VOID
SeiInitDebugSupport(VOID
)
124 static const UNICODE_STRING DebugKey
= RTL_CONSTANT_STRING(L
"SHIMENG_DEBUG_LEVEL");
125 UNICODE_STRING DebugValue
;
127 ULONG NewLevel
= SEI_MSG
; /* Show some basic info in the logs, unless configured different */
130 RtlInitEmptyUnicodeString(&DebugValue
, Buffer
, sizeof(Buffer
));
132 Status
= RtlQueryEnvironmentVariable_U(NULL
, &DebugKey
, &DebugValue
);
134 if (NT_SUCCESS(Status
))
136 if (!NT_SUCCESS(RtlUnicodeStringToInteger(&DebugValue
, 10, &NewLevel
)))
139 g_ShimEngDebugLevel
= NewLevel
;
144 * Outputs diagnostic info.
146 * @param [in] Level The level to log this message with, choose any of [SHIM_ERR,
147 * SHIM_WARN, SHIM_INFO].
148 * @param [in] FunctionName The function this log should be attributed to.
149 * @param [in] Format The format string.
150 * @param ... Variable arguments providing additional information.
152 * @return Success: TRUE Failure: FALSE.
154 BOOL WINAPIV
SeiDbgPrint(SEI_LOG_LEVEL Level
, PCSTR Function
, PCSTR Format
, ...)
157 char* Current
= Buffer
;
158 const char* LevelStr
;
159 size_t Length
= sizeof(Buffer
);
163 if (g_ShimEngDebugLevel
== 0xffffffff)
164 SeiInitDebugSupport();
166 if (Level
> g_ShimEngDebugLevel
)
189 hr
= StringCchPrintfExA(Current
, Length
, &Current
, &Length
, STRSAFE_NULL_ON_FAILURE
, "[%s] [%s] ", LevelStr
, Function
);
191 hr
= StringCchPrintfExA(Current
, Length
, &Current
, &Length
, STRSAFE_NULL_ON_FAILURE
, "[%s] ", LevelStr
);
196 va_start(ArgList
, Format
);
197 hr
= StringCchVPrintfExA(Current
, Length
, &Current
, &Length
, STRSAFE_NULL_ON_FAILURE
, Format
, ArgList
);
202 DbgPrint("%s", Buffer
);
207 PVOID
SeiGetModuleFromAddress(PVOID addr
)
209 PVOID hModule
= NULL
;
210 RtlPcToFileHeader(addr
, &hModule
);
216 /* TODO: Guard against recursive calling / calling init multiple times! */
217 VOID
NotifyShims(DWORD dwReason
, PVOID Info
)
221 for (n
= 0; n
< ARRAY_Size(&g_pShimInfo
); ++n
)
223 PSHIMMODULE pShimModule
= *ARRAY_At(&g_pShimInfo
, PSHIMMODULE
, n
);
224 if (!pShimModule
->pNotifyShims
)
227 pShimModule
->pNotifyShims(dwReason
, Info
);
233 VOID
SeiCheckComPlusImage(PVOID BaseAddress
)
235 ULONG ComSectionSize
;
236 g_bComPlusImage
= RtlImageDirectoryEntryToData(BaseAddress
, TRUE
, IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
, &ComSectionSize
) != NULL
;
238 SHIMENG_INFO("COM+ executable %s\n", g_bComPlusImage
? "TRUE" : "FALSE");
242 PSHIMMODULE
SeiGetShimModuleInfo(PVOID BaseAddress
)
246 for (n
= 0; n
< ARRAY_Size(&g_pShimInfo
); ++n
)
248 PSHIMMODULE pShimModule
= *ARRAY_At(&g_pShimInfo
, PSHIMMODULE
, n
);
250 if (pShimModule
->BaseAddress
== BaseAddress
)
256 PSHIMMODULE
SeiCreateShimModuleInfo(PCWSTR DllName
, PVOID BaseAddress
)
258 static const ANSI_STRING GetHookAPIs
= RTL_CONSTANT_STRING("GetHookAPIs");
259 static const ANSI_STRING NotifyShims
= RTL_CONSTANT_STRING("NotifyShims");
260 PSHIMMODULE
* pData
, Data
;
261 PVOID pGetHookAPIs
, pNotifyShims
;
263 if (!NT_SUCCESS(LdrGetProcedureAddress(BaseAddress
, (PANSI_STRING
)&GetHookAPIs
, 0, &pGetHookAPIs
)) ||
264 !NT_SUCCESS(LdrGetProcedureAddress(BaseAddress
, (PANSI_STRING
)&NotifyShims
, 0, &pNotifyShims
)))
266 SHIMENG_WARN("Failed to resolve entry points for %S\n", DllName
);
270 pData
= ARRAY_Append(&g_pShimInfo
, PSHIMMODULE
);
274 *pData
= SeiAlloc(sizeof(SHIMMODULE
));
278 RtlCreateUnicodeString(&Data
->Name
, DllName
);
279 Data
->BaseAddress
= BaseAddress
;
281 Data
->pGetHookAPIs
= pGetHookAPIs
;
282 Data
->pNotifyShims
= pNotifyShims
;
284 ARRAY_Init(&Data
->EnabledShims
, PSHIMINFO
);
289 PSHIMINFO
SeiAppendHookInfo(PSHIMMODULE pShimModuleInfo
, PHOOKAPIEX pHookApi
, DWORD dwHookCount
, PCWSTR ShimName
)
291 PSHIMINFO
* pData
, Data
;
293 pData
= ARRAY_Append(&pShimModuleInfo
->EnabledShims
, PSHIMINFO
);
297 *pData
= SeiAlloc(sizeof(SHIMINFO
));
303 Data
->ShimName
= SdbpStrDup(ShimName
);
307 Data
->pHookApi
= pHookApi
;
308 Data
->dwHookCount
= dwHookCount
;
309 Data
->pShimModule
= pShimModuleInfo
;
310 ARRAY_Init(&Data
->InExclude
, INEXCLUDE
);
314 PHOOKMODULEINFO
SeiFindHookModuleInfo(PUNICODE_STRING ModuleName
, PVOID BaseAddress
)
318 for (n
= 0; n
< ARRAY_Size(&g_pHookArray
); ++n
)
320 PHOOKMODULEINFO pModuleInfo
= ARRAY_At(&g_pHookArray
, HOOKMODULEINFO
, n
);
322 if (BaseAddress
&& BaseAddress
== pModuleInfo
->BaseAddress
)
325 if (!BaseAddress
&& RtlEqualUnicodeString(ModuleName
, &pModuleInfo
->Name
, TRUE
))
332 PHOOKMODULEINFO
SeiFindHookModuleInfoForImportDescriptor(PBYTE DllBase
, PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor
)
334 UNICODE_STRING DllName
;
338 if (!RtlCreateUnicodeStringFromAsciiz(&DllName
, (PCSZ
)(DllBase
+ ImportDescriptor
->Name
)))
340 SHIMENG_FAIL("Unable to convert dll name to unicode\n");
344 Success
= LdrGetDllHandle(NULL
, NULL
, &DllName
, &DllHandle
);
345 RtlFreeUnicodeString(&DllName
);
347 if (!NT_SUCCESS(Success
))
349 SHIMENG_FAIL("Unable to get module handle for %wZ\n", &DllName
);
353 return SeiFindHookModuleInfo(NULL
, DllHandle
);
356 static LPCWSTR
SeiGetStringPtr(PDB pdb
, TAGID tag
, TAG type
)
358 TAGID tagEntry
= SdbFindFirstTag(pdb
, tag
, type
);
359 if (tagEntry
== TAGID_NULL
)
362 return SdbGetStringTagPtr(pdb
, tagEntry
);
365 static DWORD
SeiGetDWORD(PDB pdb
, TAGID tag
, TAG type
)
367 TAGID tagEntry
= SdbFindFirstTag(pdb
, tag
, type
);
368 if (tagEntry
== TAGID_NULL
)
371 return SdbReadDWORDTag(pdb
, tagEntry
, 0);
374 static QWORD
SeiGetQWORD(PDB pdb
, TAGID tag
, TAG type
)
376 TAGID tagEntry
= SdbFindFirstTag(pdb
, tag
, type
);
377 if (tagEntry
== TAGID_NULL
)
380 return SdbReadQWORDTag(pdb
, tagEntry
, 0);
383 static VOID
SeiAddShim(TAGREF trShimRef
, PARRAY pShimRef
)
387 Data
= ARRAY_Append(pShimRef
, TAGREF
);
394 static VOID
SeiAddFlag(PDB pdb
, TAGID tiFlagRef
, PFLAGINFO pFlagInfo
)
398 /* Resolve the FLAG_REF to the real FLAG node */
399 TAGID FlagTag
= SeiGetDWORD(pdb
, tiFlagRef
, TAG_FLAG_TAGID
);
401 if (FlagTag
== TAGID_NULL
)
404 pFlagInfo
->AppCompatFlags
.QuadPart
|= SeiGetQWORD(pdb
, FlagTag
, TAG_FLAG_MASK_KERNEL
);
405 pFlagInfo
->AppCompatFlagsUser
.QuadPart
|= SeiGetQWORD(pdb
, FlagTag
, TAG_FLAG_MASK_USER
);
406 Flag
.QuadPart
= SeiGetQWORD(pdb
, FlagTag
, TAG_FLAG_PROCESSPARAM
);
407 pFlagInfo
->ProcessParameters_Flags
|= Flag
.LowPart
;
410 /* Propagate layers to child processes */
411 static VOID
SeiSetLayerEnvVar(LPCWSTR wszLayer
)
414 UNICODE_STRING VarName
= RTL_CONSTANT_STRING(L
"__COMPAT_LAYER");
415 UNICODE_STRING Value
;
417 RtlInitUnicodeString(&Value
, wszLayer
);
419 Status
= RtlSetEnvironmentVariable(NULL
, &VarName
, &Value
);
420 if (NT_SUCCESS(Status
))
421 SHIMENG_INFO("Set env var %wZ=%wZ\n", &VarName
, &Value
);
423 SHIMENG_FAIL("Failed to set %wZ: 0x%x\n", &VarName
, Status
);
426 #define MAX_LAYER_LENGTH 256
428 /* Translate all Exe and Layer entries to Shims, and propagate all layers */
429 static VOID
SeiBuildShimRefArray(HSDB hsdb
, SDBQUERYRESULT
* pQuery
, PARRAY pShimRef
, PFLAGINFO pFlagInfo
)
431 WCHAR wszLayerEnvVar
[MAX_LAYER_LENGTH
] = { 0 };
434 for (n
= 0; n
< pQuery
->dwExeCount
; ++n
)
438 if (SdbTagRefToTagID(hsdb
, pQuery
->atrExes
[n
], &pdb
, &tag
))
440 LPCWSTR ExeName
= SeiGetStringPtr(pdb
, tag
, TAG_NAME
);
441 TAGID ShimRef
= SdbFindFirstTag(pdb
, tag
, TAG_SHIM_REF
);
442 TAGID FlagRef
= SdbFindFirstTag(pdb
, tag
, TAG_FLAG_REF
);
445 SeiDbgPrint(SEI_MSG
, NULL
, "ShimInfo(Exe(%S))\n", ExeName
);
447 while (ShimRef
!= TAGID_NULL
)
450 if (SdbTagIDToTagRef(hsdb
, pdb
, ShimRef
, &trShimRef
))
451 SeiAddShim(trShimRef
, pShimRef
);
453 ShimRef
= SdbFindNextTag(pdb
, tag
, ShimRef
);
456 while (FlagRef
!= TAGID_NULL
)
458 SeiAddFlag(pdb
, FlagRef
, pFlagInfo
);
460 FlagRef
= SdbFindNextTag(pdb
, tag
, FlagRef
);
466 for (n
= 0; n
< pQuery
->dwLayerCount
; ++n
)
470 if (SdbTagRefToTagID(hsdb
, pQuery
->atrLayers
[n
], &pdb
, &tag
))
472 LPCWSTR LayerName
= SeiGetStringPtr(pdb
, tag
, TAG_NAME
);
473 TAGID ShimRef
= SdbFindFirstTag(pdb
, tag
, TAG_SHIM_REF
);
474 TAGID FlagRef
= SdbFindFirstTag(pdb
, tag
, TAG_FLAG_REF
);
479 SeiDbgPrint(SEI_MSG
, NULL
, "ShimInfo(Layer(%S))\n", LayerName
);
480 if (wszLayerEnvVar
[0])
481 StringCchCatW(wszLayerEnvVar
, ARRAYSIZE(wszLayerEnvVar
), L
" ");
482 hr
= StringCchCatW(wszLayerEnvVar
, ARRAYSIZE(wszLayerEnvVar
), LayerName
);
485 SHIMENG_FAIL("Unable to append %S\n", LayerName
);
489 while (ShimRef
!= TAGID_NULL
)
492 if (SdbTagIDToTagRef(hsdb
, pdb
, ShimRef
, &trShimRef
))
493 SeiAddShim(trShimRef
, pShimRef
);
495 ShimRef
= SdbFindNextTag(pdb
, tag
, ShimRef
);
498 while (FlagRef
!= TAGID_NULL
)
500 SeiAddFlag(pdb
, FlagRef
, pFlagInfo
);
502 FlagRef
= SdbFindNextTag(pdb
, tag
, FlagRef
);
506 if (wszLayerEnvVar
[0])
507 SeiSetLayerEnvVar(wszLayerEnvVar
);
510 /* Given the hooks from one shim, find the relevant modules and store the combination of module + hook */
511 VOID
SeiAddHooks(PHOOKAPIEX hooks
, DWORD dwHookCount
, PSHIMINFO pShim
)
514 UNICODE_STRING UnicodeModName
;
517 RtlInitEmptyUnicodeString(&UnicodeModName
, Buf
, sizeof(Buf
));
519 for (n
= 0; n
< dwHookCount
; ++n
)
521 ANSI_STRING AnsiString
;
523 PHOOKAPIEX hook
= hooks
+ n
;
524 PHOOKAPIEX
* pHookApi
;
525 PHOOKMODULEINFO HookModuleInfo
;
527 RtlInitAnsiString(&AnsiString
, hook
->LibraryName
);
528 if (!NT_SUCCESS(RtlAnsiStringToUnicodeString(&UnicodeModName
, &AnsiString
, FALSE
)))
530 SHIMENG_FAIL("Unable to convert %s to Unicode\n", hook
->LibraryName
);
534 RtlInitAnsiString(&AnsiString
, hook
->FunctionName
);
535 if (NT_SUCCESS(LdrGetDllHandle(NULL
, 0, &UnicodeModName
, &DllHandle
)))
540 if (!NT_SUCCESS(LdrGetProcedureAddress(DllHandle
, &AnsiString
, 0, &ProcAddress
)))
542 SHIMENG_FAIL("Unable to retrieve %s!%s\n", hook
->LibraryName
, hook
->FunctionName
);
546 HookModuleInfo
= SeiFindHookModuleInfo(NULL
, DllHandle
);
547 hook
->OriginalFunction
= ProcAddress
;
551 HookModuleInfo
= SeiFindHookModuleInfo(&UnicodeModName
, NULL
);
557 HookModuleInfo
= ARRAY_Append(&g_pHookArray
, HOOKMODULEINFO
);
561 HookModuleInfo
->BaseAddress
= DllHandle
;
562 ARRAY_Init(&HookModuleInfo
->HookApis
, PHOOKAPIEX
);
563 RtlCreateUnicodeString(&HookModuleInfo
->Name
, UnicodeModName
.Buffer
);
566 hook
->pShimInfo
= pShim
;
568 for (j
= 0; j
< ARRAY_Size(&HookModuleInfo
->HookApis
); ++j
)
570 PHOOKAPIEX HookApi
= *ARRAY_At(&HookModuleInfo
->HookApis
, PHOOKAPIEX
, j
);
571 int CmpResult
= strcmp(hook
->FunctionName
, HookApi
->FunctionName
);
574 /* Multiple hooks on one function? --> use ApiLink */
575 SHIMENG_FAIL("Multiple hooks on one API is not yet supported!\n");
579 pHookApi
= ARRAY_Append(&HookModuleInfo
->HookApis
, PHOOKAPIEX
);
584 typedef FARPROC(WINAPI
* GETPROCADDRESSPROC
)(HINSTANCE
, LPCSTR
);
586 /* Check if we should fake the return from GetProcAddress (because we also redirected the iat for this module) */
587 FARPROC WINAPI
StubGetProcAddress(HINSTANCE hModule
, LPCSTR lpProcName
)
589 char szOrdProcName
[10] = "";
590 LPCSTR lpPrintName
= lpProcName
;
591 PVOID Addr
= _ReturnAddress();
592 PHOOKMODULEINFO HookModuleInfo
;
593 FARPROC proc
= ((GETPROCADDRESSPROC
)g_IntHookEx
[0].OriginalFunction
)(hModule
, lpProcName
);
595 if (!HIWORD(lpProcName
))
597 sprintf(szOrdProcName
, "#%lu", (DWORD
)lpProcName
);
598 lpPrintName
= szOrdProcName
;
601 Addr
= SeiGetModuleFromAddress(Addr
);
602 if (SE_IsShimDll(Addr
))
604 SHIMENG_MSG("Not touching GetProcAddress for shim dll (%p!%s)", hModule
, lpPrintName
);
608 SHIMENG_INFO("(GetProcAddress(%p!%s) => %p\n", hModule
, lpPrintName
, proc
);
610 HookModuleInfo
= SeiFindHookModuleInfo(NULL
, hModule
);
612 /* FIXME: Ordinal not yet supported */
613 if (HookModuleInfo
&& HIWORD(lpProcName
))
616 for (n
= 0; n
< ARRAY_Size(&HookModuleInfo
->HookApis
); ++n
)
618 PHOOKAPIEX HookApi
= *ARRAY_At(&HookModuleInfo
->HookApis
, PHOOKAPIEX
, n
);
619 int CmpResult
= strcmp(lpProcName
, HookApi
->FunctionName
);
622 SHIMENG_MSG("Redirecting %p to %p\n", proc
, HookApi
->ReplacementFunction
);
623 proc
= HookApi
->ReplacementFunction
;
632 /* Walk all shim modules / enabled shims, and add their hooks */
633 VOID
SeiResolveAPIs(VOID
)
637 /* Enumerate all Shim modules */
638 for (mod
= 0; mod
< ARRAY_Size(&g_pShimInfo
); ++mod
)
640 PSHIMMODULE pShimModule
= *ARRAY_At(&g_pShimInfo
, PSHIMMODULE
, mod
);
641 DWORD dwShimCount
= ARRAY_Size(&pShimModule
->EnabledShims
);
643 /* Enumerate all Shims */
644 for (n
= 0; n
< dwShimCount
; ++n
)
646 PSHIMINFO pShim
= *ARRAY_At(&pShimModule
->EnabledShims
, PSHIMINFO
, n
);
648 PHOOKAPIEX hooks
= pShim
->pHookApi
;
649 DWORD dwHookCount
= pShim
->dwHookCount
;
651 SeiAddHooks(hooks
, dwHookCount
, pShim
);
656 /* If we hooked something, we should also redirect GetProcAddress */
657 VOID
SeiAddInternalHooks(DWORD dwNumHooks
)
661 g_bInternalHooksUsed
= FALSE
;
665 SeiAddHooks(g_IntHookEx
, ARRAYSIZE(g_IntHookEx
), NULL
);
666 g_bInternalHooksUsed
= TRUE
;
669 /* Patch one function in the iat */
670 VOID
SeiPatchNewImport(PIMAGE_THUNK_DATA FirstThunk
, PHOOKAPIEX HookApi
, PLDR_DATA_TABLE_ENTRY LdrEntry
)
672 ULONG OldProtection
= 0;
677 SHIMENG_INFO("Hooking API \"%s!%s\" for DLL \"%wZ\"\n", HookApi
->LibraryName
, HookApi
->FunctionName
, &LdrEntry
->BaseDllName
);
679 Ptr
= &FirstThunk
->u1
.Function
;
680 Size
= sizeof(FirstThunk
->u1
.Function
);
681 Status
= NtProtectVirtualMemory(NtCurrentProcess(), &Ptr
, &Size
, PAGE_EXECUTE_READWRITE
, &OldProtection
);
683 if (!NT_SUCCESS(Status
))
685 SHIMENG_FAIL("Unable to unprotect 0x%p\n", &FirstThunk
->u1
.Function
);
689 SHIMENG_INFO("changing 0x%p to 0x%p\n", FirstThunk
->u1
.Function
, HookApi
->ReplacementFunction
);
691 FirstThunk
->u1
.Function
= (ULONGLONG
)HookApi
->ReplacementFunction
;
693 FirstThunk
->u1
.Function
= (DWORD
)HookApi
->ReplacementFunction
;
696 Size
= sizeof(FirstThunk
->u1
.Function
);
697 Status
= NtProtectVirtualMemory(NtCurrentProcess(), &Ptr
, &Size
, OldProtection
, &OldProtection
);
699 if (!NT_SUCCESS(Status
))
701 SHIMENG_WARN("Unable to reprotect 0x%p\n", &FirstThunk
->u1
.Function
);
706 PINEXCLUDE
SeiFindInExclude(PARRAY InExclude
, PCUNICODE_STRING DllName
)
710 for (n
= 0; n
< ARRAY_Size(InExclude
); ++n
)
712 PINEXCLUDE InEx
= ARRAY_At(InExclude
, INEXCLUDE
, n
);
714 if (RtlEqualUnicodeString(&InEx
->Module
, DllName
, TRUE
))
721 BOOL
SeiIsExcluded(PLDR_DATA_TABLE_ENTRY LdrEntry
, PHOOKAPIEX HookApi
)
723 PSHIMINFO pShimInfo
= HookApi
->pShimInfo
;
724 PINEXCLUDE InExclude
;
725 BOOL IsExcluded
= FALSE
;
729 /* Internal hook, do not exclude it */
733 /* By default, everything from System32 or WinSxs is excluded */
734 if (RtlPrefixUnicodeString(&g_System32Directory
, &LdrEntry
->FullDllName
, TRUE
) ||
735 RtlPrefixUnicodeString(&g_SxsDirectory
, &LdrEntry
->FullDllName
, TRUE
))
738 InExclude
= SeiFindInExclude(&pShimInfo
->InExclude
, &LdrEntry
->BaseDllName
);
741 /* If it is on the 'exclude' list, bail out */
742 if (!InExclude
->Include
)
744 SHIMENG_INFO("Module '%wZ' excluded for shim %S, API '%s!%s', because it on in the exclude list.\n",
745 &LdrEntry
->BaseDllName
, pShimInfo
->ShimName
, HookApi
->LibraryName
, HookApi
->FunctionName
);
749 /* If it is on the 'include' list, override System32 / Winsxs check. */
752 SHIMENG_INFO("Module '%wZ' included for shim %S, API '%s!%s', because it is on the include list.\n",
753 &LdrEntry
->BaseDllName
, pShimInfo
->ShimName
, HookApi
->LibraryName
, HookApi
->FunctionName
);
761 SHIMENG_INFO("Module '%wZ' excluded for shim %S, API '%s!%s', because it is in System32/WinSXS.\n",
762 &LdrEntry
->BaseDllName
, pShimInfo
->ShimName
, HookApi
->LibraryName
, HookApi
->FunctionName
);
768 VOID
SeiAppendInExclude(PARRAY dest
, PCWSTR ModuleName
, BOOL IsInclude
)
770 PINEXCLUDE InExclude
;
771 UNICODE_STRING ModuleNameU
;
772 RtlInitUnicodeString(&ModuleNameU
, ModuleName
);
774 InExclude
= SeiFindInExclude(dest
, &ModuleNameU
);
777 InExclude
->Include
= IsInclude
;
781 InExclude
= ARRAY_Append(dest
, INEXCLUDE
);
784 PCWSTR ModuleNameCopy
= SdbpStrDup(ModuleName
);
785 RtlInitUnicodeString(&InExclude
->Module
, ModuleNameCopy
);
786 InExclude
->Include
= IsInclude
;
790 /* Read the INEXCLUD tags from a given parent tag */
791 VOID
SeiReadInExclude(PDB pdb
, TAGID parent
, PARRAY dest
)
795 InExcludeTag
= SdbFindFirstTag(pdb
, parent
, TAG_INEXCLUD
);
797 while (InExcludeTag
!= TAGID_NULL
)
800 TAGID ModuleTag
= SdbFindFirstTag(pdb
, InExcludeTag
, TAG_MODULE
);
801 TAGID IncludeTag
= SdbFindFirstTag(pdb
, InExcludeTag
, TAG_INCLUDE
);
803 ModuleName
= SdbGetStringTagPtr(pdb
, ModuleTag
);
806 SeiAppendInExclude(dest
, ModuleName
, IncludeTag
!= TAGID_NULL
);
810 SHIMENG_WARN("INEXCLUDE without Module: 0x%x\n", InExcludeTag
);
813 InExcludeTag
= SdbFindNextTag(pdb
, parent
, InExcludeTag
);
817 VOID
SeiBuildGlobalInclExclList(HSDB hsdb
)
820 TAGREF tr
= TAGREF_ROOT
;
821 TAGID root
, db
, library
;
823 if (!SdbTagRefToTagID(hsdb
, tr
, &pdb
, &root
))
825 SHIMENG_WARN("Unable to resolve database root\n");
828 db
= SdbFindFirstTag(pdb
, root
, TAG_DATABASE
);
829 if (db
== TAGID_NULL
)
831 SHIMENG_WARN("Unable to resolve database\n");
834 library
= SdbFindFirstTag(pdb
, db
, TAG_LIBRARY
);
835 if (library
== TAGID_NULL
)
837 SHIMENG_WARN("Unable to resolve library\n");
841 SeiReadInExclude(pdb
, library
, &g_InExclude
);
844 VOID
SeiBuildInclExclList(PDB pdb
, TAGID ShimTag
, PSHIMINFO pShimInfo
)
848 /* First duplicate the global in/excludes */
849 for (n
= 0; n
< ARRAY_Size(&g_InExclude
); ++n
)
851 PINEXCLUDE InEx
= ARRAY_At(&g_InExclude
, INEXCLUDE
, n
);
852 SeiAppendInExclude(&pShimInfo
->InExclude
, InEx
->Module
.Buffer
, InEx
->Include
);
855 /* Now read this shim's in/excludes (possibly overriding the global ones) */
856 SeiReadInExclude(pdb
, ShimTag
, &pShimInfo
->InExclude
);
859 /* Given one loaded module, redirect (hook) all functions from the iat that are registered by shims */
860 VOID
SeiHookImports(PLDR_DATA_TABLE_ENTRY LdrEntry
)
863 PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor
;
864 PBYTE DllBase
= LdrEntry
->DllBase
;
866 if (SE_IsShimDll(DllBase
) || g_hInstance
== LdrEntry
->DllBase
)
868 SHIMENG_INFO("Skipping shim module 0x%p \"%wZ\"\n", LdrEntry
->DllBase
, &LdrEntry
->BaseDllName
);
872 if (LdrEntry
->Flags
& LDRP_COMPAT_DATABASE_PROCESSED
)
874 SHIMENG_INFO("Skipping module 0x%p \"%wZ\" because it was already processed\n", LdrEntry
->DllBase
, &LdrEntry
->BaseDllName
);
878 ImportDescriptor
= RtlImageDirectoryEntryToData(DllBase
, TRUE
, IMAGE_DIRECTORY_ENTRY_IMPORT
, &Size
);
879 if (!ImportDescriptor
)
881 SHIMENG_INFO("Skipping module 0x%p \"%wZ\" due to no iat found\n", LdrEntry
->DllBase
, &LdrEntry
->BaseDllName
);
885 SHIMENG_INFO("Hooking module 0x%p \"%wZ\"\n", LdrEntry
->DllBase
, &LdrEntry
->BaseDllName
);
887 for ( ;ImportDescriptor
->Name
&& ImportDescriptor
->OriginalFirstThunk
; ImportDescriptor
++)
889 PHOOKMODULEINFO HookModuleInfo
;
891 /* Do we have hooks for this module? */
892 HookModuleInfo
= SeiFindHookModuleInfoForImportDescriptor(DllBase
, ImportDescriptor
);
896 PIMAGE_THUNK_DATA OriginalThunk
, FirstThunk
;
899 for (n
= 0; n
< ARRAY_Size(&HookModuleInfo
->HookApis
); ++n
)
902 PHOOKAPIEX HookApi
= *ARRAY_At(&HookModuleInfo
->HookApis
, PHOOKAPIEX
, n
);
904 /* Check if this module should be excluded from being hooked (system32/winsxs, global or shim exclude) */
905 if (SeiIsExcluded(LdrEntry
, HookApi
))
910 OriginalThunk
= (PIMAGE_THUNK_DATA
)(DllBase
+ ImportDescriptor
->OriginalFirstThunk
);
911 FirstThunk
= (PIMAGE_THUNK_DATA
)(DllBase
+ ImportDescriptor
->FirstThunk
);
913 /* Walk all imports */
914 for (;OriginalThunk
->u1
.AddressOfData
&& FirstThunk
->u1
.Function
; OriginalThunk
++, FirstThunk
++)
916 if (!IMAGE_SNAP_BY_ORDINAL32(OriginalThunk
->u1
.AddressOfData
))
918 PIMAGE_IMPORT_BY_NAME ImportName
;
920 ImportName
= (PIMAGE_IMPORT_BY_NAME
)(DllBase
+ OriginalThunk
->u1
.AddressOfData
);
921 if (!strcmp((PCSTR
)ImportName
->Name
, HookApi
->FunctionName
))
923 SeiPatchNewImport(FirstThunk
, HookApi
, LdrEntry
);
925 /* Sadly, iat does not have to be sorted, and can even contain duplicate entries. */
931 SHIMENG_FAIL("Ordinals not yet supported\n");
938 /* One entry not found. */
940 SHIMENG_INFO("Entry \"%s!%s\" not found for \"%wZ\"\n", HookApi
->LibraryName
, HookApi
->FunctionName
, &LdrEntry
->BaseDllName
);
942 SHIMENG_INFO("Entry \"%s!%s\" found %d times for \"%wZ\"\n", HookApi
->LibraryName
, HookApi
->FunctionName
, dwFound
, &LdrEntry
->BaseDllName
);
948 /* Mark this module as processed. */
949 LdrEntry
->Flags
|= LDRP_COMPAT_DATABASE_PROCESSED
;
953 VOID
PatchNewModules(PPEB Peb
)
955 PLIST_ENTRY ListHead
, ListEntry
;
956 PLDR_DATA_TABLE_ENTRY LdrEntry
;
958 ListHead
= &NtCurrentPeb()->Ldr
->InLoadOrderModuleList
;
959 ListEntry
= ListHead
->Flink
;
961 while (ListHead
!= ListEntry
)
963 LdrEntry
= CONTAINING_RECORD(ListEntry
, LDR_DATA_TABLE_ENTRY
, InLoadOrderLinks
);
964 SeiHookImports(LdrEntry
);
966 ListEntry
= ListEntry
->Flink
;
971 VOID
SeiInitPaths(VOID
)
973 #define SYSTEM32 L"\\system32"
974 #define WINSXS L"\\winsxs"
976 PWSTR WindowsDirectory
= SdbpStrDup(SharedUserData
->NtSystemRoot
);
977 RtlInitUnicodeString(&g_WindowsDirectory
, WindowsDirectory
);
979 g_System32Directory
.MaximumLength
= g_WindowsDirectory
.Length
+ SdbpStrsize(SYSTEM32
);
980 g_System32Directory
.Buffer
= SdbpAlloc(g_System32Directory
.MaximumLength
);
981 RtlCopyUnicodeString(&g_System32Directory
, &g_WindowsDirectory
);
982 RtlAppendUnicodeToString(&g_System32Directory
, SYSTEM32
);
984 g_SxsDirectory
.MaximumLength
= g_WindowsDirectory
.Length
+ SdbpStrsize(WINSXS
);
985 g_SxsDirectory
.Buffer
= SdbpAlloc(g_SxsDirectory
.MaximumLength
);
986 RtlCopyUnicodeString(&g_SxsDirectory
, &g_WindowsDirectory
);
987 RtlAppendUnicodeToString(&g_SxsDirectory
, WINSXS
);
993 VOID
SeiInit(PUNICODE_STRING ProcessImage
, HSDB hsdb
, SDBQUERYRESULT
* pQuery
)
997 DWORD dwTotalHooks
= 0;
1000 PPEB Peb
= NtCurrentPeb();
1002 /* We should only be called once! */
1003 ASSERT(g_pShimInfo
.ItemSize__
== 0);
1005 ARRAY_Init(&ShimRefArray
, TAGREF
);
1006 ARRAY_Init(&g_pShimInfo
, PSHIMMODULE
);
1007 ARRAY_Init(&g_pHookArray
, HOOKMODULEINFO
);
1008 ARRAY_Init(&g_InExclude
, INEXCLUDE
);
1009 RtlZeroMemory(&ShimFlags
, sizeof(ShimFlags
));
1013 SeiCheckComPlusImage(Peb
->ImageBaseAddress
);
1016 if (pQuery->trApphelp)
1017 SeiDisplayAppHelp(?pQuery->trApphelp?);
1020 SeiDbgPrint(SEI_MSG
, NULL
, "ShimInfo(ExePath(%wZ))\n", ProcessImage
);
1021 SeiBuildShimRefArray(hsdb
, pQuery
, &ShimRefArray
, &ShimFlags
);
1022 if (ShimFlags
.AppCompatFlags
.QuadPart
)
1024 SeiDbgPrint(SEI_MSG
, NULL
, "Using KERNEL apphack flags 0x%I64x\n", ShimFlags
.AppCompatFlags
.QuadPart
);
1025 Peb
->AppCompatFlags
.QuadPart
|= ShimFlags
.AppCompatFlags
.QuadPart
;
1027 if (ShimFlags
.AppCompatFlagsUser
.QuadPart
)
1029 SeiDbgPrint(SEI_MSG
, NULL
, "Using USER apphack flags 0x%I64x\n", ShimFlags
.AppCompatFlagsUser
.QuadPart
);
1030 Peb
->AppCompatFlagsUser
.QuadPart
|= ShimFlags
.AppCompatFlagsUser
.QuadPart
;
1032 if (ShimFlags
.ProcessParameters_Flags
)
1034 SeiDbgPrint(SEI_MSG
, NULL
, "Using ProcessParameters flags 0x%x\n", ShimFlags
.ProcessParameters_Flags
);
1035 Peb
->ProcessParameters
->Flags
|= ShimFlags
.ProcessParameters_Flags
;
1037 SeiDbgPrint(SEI_MSG
, NULL
, "ShimInfo(Complete)\n");
1039 SHIMENG_INFO("Got %d shims\n", ARRAY_Size(&ShimRefArray
));
1040 SeiBuildGlobalInclExclList(hsdb
);
1042 /* Walk all shims referenced (in layers + exes), and load their modules */
1043 for (n
= 0; n
< ARRAY_Size(&ShimRefArray
); ++n
)
1048 TAGREF tr
= *ARRAY_At(&ShimRefArray
, TAGREF
, n
);
1050 if (SdbTagRefToTagID(hsdb
, tr
, &pdb
, &ShimRef
))
1052 LPCWSTR ShimName
, DllName
, CommandLine
= NULL
;
1054 WCHAR FullNameBuffer
[MAX_PATH
];
1055 UNICODE_STRING UnicodeDllName
;
1057 PSHIMMODULE pShimModuleInfo
= NULL
;
1058 ANSI_STRING AnsiCommandLine
= RTL_CONSTANT_STRING("");
1059 PSHIMINFO pShimInfo
= NULL
;
1060 PHOOKAPIEX pHookApi
;
1063 ShimName
= SeiGetStringPtr(pdb
, ShimRef
, TAG_NAME
);
1066 SHIMENG_FAIL("Failed to retrieve the name for 0x%x\n", tr
);
1070 CommandLine
= SeiGetStringPtr(pdb
, ShimRef
, TAG_COMMAND_LINE
);
1071 if (CommandLine
&& *CommandLine
)
1073 RtlInitUnicodeString(&UnicodeDllName
, CommandLine
);
1074 if (NT_SUCCESS(RtlUnicodeStringToAnsiString(&AnsiCommandLine
, &UnicodeDllName
, TRUE
)))
1076 SHIMENG_INFO("COMMAND LINE %s for %S", AnsiCommandLine
.Buffer
, ShimName
);
1080 AnsiCommandLine
.Buffer
= "";
1085 ShimTag
= SeiGetDWORD(pdb
, ShimRef
, TAG_SHIM_TAGID
);
1088 SHIMENG_FAIL("Failed to resolve %S to a shim\n", ShimName
);
1092 if (!SUCCEEDED(SdbGetAppPatchDir(NULL
, FullNameBuffer
, ARRAYSIZE(FullNameBuffer
))))
1094 SHIMENG_WARN("Failed to get the AppPatch dir\n");
1098 DllName
= SeiGetStringPtr(pdb
, ShimTag
, TAG_DLLFILE
);
1099 if (DllName
== NULL
||
1100 !SUCCEEDED(StringCchCatW(FullNameBuffer
, ARRAYSIZE(FullNameBuffer
), L
"\\")) ||
1101 !SUCCEEDED(StringCchCatW(FullNameBuffer
, ARRAYSIZE(FullNameBuffer
), DllName
)))
1103 SHIMENG_WARN("Failed to build a full path for %S\n", ShimName
);
1107 RtlInitUnicodeString(&UnicodeDllName
, FullNameBuffer
);
1108 if (NT_SUCCESS(LdrGetDllHandle(NULL
, NULL
, &UnicodeDllName
, &BaseAddress
)))
1110 /* This shim dll was already loaded, let's find it */
1111 pShimModuleInfo
= SeiGetShimModuleInfo(BaseAddress
);
1113 else if (!NT_SUCCESS(LdrLoadDll(NULL
, NULL
, &UnicodeDllName
, &BaseAddress
)))
1115 SHIMENG_WARN("Failed to load %wZ for %S\n", &UnicodeDllName
, ShimName
);
1118 /* No shim module found (or we just loaded it) */
1119 if (!pShimModuleInfo
)
1121 pShimModuleInfo
= SeiCreateShimModuleInfo(DllName
, BaseAddress
);
1122 if (!pShimModuleInfo
)
1124 SHIMENG_FAIL("Failed to allocate ShimInfo for %S\n", DllName
);
1129 SHIMENG_INFO("Shim DLL 0x%p \"%wZ\" loaded\n", BaseAddress
, &UnicodeDllName
);
1130 SHIMENG_INFO("Using SHIM \"%S!%S\"\n", DllName
, ShimName
);
1132 /* Ask this shim what hooks it needs (and pass along the commandline) */
1133 pHookApi
= pShimModuleInfo
->pGetHookAPIs(AnsiCommandLine
.Buffer
, ShimName
, &dwHookCount
);
1134 SHIMENG_INFO("GetHookAPIs returns %d hooks for DLL \"%wZ\" SHIM \"%S\"\n", dwHookCount
, &UnicodeDllName
, ShimName
);
1136 pShimInfo
= SeiAppendHookInfo(pShimModuleInfo
, pHookApi
, dwHookCount
, ShimName
);
1138 /* If this shim has hooks, create the include / exclude lists */
1140 SeiBuildInclExclList(pdb
, ShimTag
, pShimInfo
);
1142 if (CommandLine
&& *CommandLine
)
1143 RtlFreeAnsiString(&AnsiCommandLine
);
1145 dwTotalHooks
+= dwHookCount
;
1149 SeiAddInternalHooks(dwTotalHooks
);
1151 PatchNewModules(Peb
);
1155 /* Load the database + unpack the shim data (if this process is allowed) */
1156 BOOL
SeiGetShimData(PUNICODE_STRING ProcessImage
, PVOID pShimData
, HSDB
* pHsdb
, SDBQUERYRESULT
* pQuery
)
1158 static const UNICODE_STRING ForbiddenShimmingApps
[] = {
1159 RTL_CONSTANT_STRING(L
"ntsd.exe"),
1160 RTL_CONSTANT_STRING(L
"windbg.exe"),
1162 RTL_CONSTANT_STRING(L
"slsvc.exe"),
1165 static const UNICODE_STRING BackSlash
= RTL_CONSTANT_STRING(L
"\\");
1166 static const UNICODE_STRING ForwdSlash
= RTL_CONSTANT_STRING(L
"/");
1167 UNICODE_STRING ProcessName
;
1168 USHORT Back
, Forward
;
1172 if (!NT_SUCCESS(RtlFindCharInUnicodeString(RTL_FIND_CHAR_IN_UNICODE_STRING_START_AT_END
, ProcessImage
, &BackSlash
, &Back
)))
1175 if (!NT_SUCCESS(RtlFindCharInUnicodeString(RTL_FIND_CHAR_IN_UNICODE_STRING_START_AT_END
, ProcessImage
, &ForwdSlash
, &Forward
)))
1182 Back
+= sizeof(WCHAR
);
1184 ProcessName
.Buffer
= ProcessImage
->Buffer
+ Back
/ sizeof(WCHAR
);
1185 ProcessName
.Length
= ProcessImage
->Length
- Back
;
1186 ProcessName
.MaximumLength
= ProcessImage
->MaximumLength
- Back
;
1188 for (n
= 0; n
< ARRAYSIZE(ForbiddenShimmingApps
); ++n
)
1190 if (RtlEqualUnicodeString(&ProcessName
, ForbiddenShimmingApps
+ n
, TRUE
))
1192 SHIMENG_MSG("Not shimming %wZ\n", ForbiddenShimmingApps
+ n
);
1197 /* We should probably load all db's here, but since we do not support that yet... */
1198 hsdb
= SdbInitDatabase(HID_DOS_PATHS
| SDB_DATABASE_MAIN_SHIM
, NULL
);
1201 if (SdbUnpackAppCompatData(hsdb
, ProcessImage
->Buffer
, pShimData
, pQuery
))
1206 SdbReleaseDatabase(hsdb
);
1213 VOID NTAPI
SE_InstallBeforeInit(PUNICODE_STRING ProcessImage
, PVOID pShimData
)
1216 SDBQUERYRESULT QueryResult
= { { 0 } };
1217 SHIMENG_INFO("(%wZ, %p)\n", ProcessImage
, pShimData
);
1219 if (!SeiGetShimData(ProcessImage
, pShimData
, &hsdb
, &QueryResult
))
1221 SHIMENG_FAIL("Failed to get shim data\n");
1225 g_bShimDuringInit
= TRUE
;
1226 SeiInit(ProcessImage
, hsdb
, &QueryResult
);
1227 g_bShimDuringInit
= FALSE
;
1229 SdbReleaseDatabase(hsdb
);
1232 VOID NTAPI
SE_InstallAfterInit(PUNICODE_STRING ProcessImage
, PVOID pShimData
)
1234 NotifyShims(SHIM_NOTIFY_ATTACH
, NULL
);
1237 VOID NTAPI
SE_ProcessDying(VOID
)
1239 SHIMENG_MSG("()\n");
1240 NotifyShims(SHIM_NOTIFY_DETACH
, NULL
);
1243 VOID WINAPI
SE_DllLoaded(PLDR_DATA_TABLE_ENTRY LdrEntry
)
1245 SHIMENG_INFO("%sINIT. loading DLL \"%wZ\"\n", g_bShimDuringInit
? "" : "AFTER ", &LdrEntry
->BaseDllName
);
1247 SeiHookImports(LdrEntry
);
1249 NotifyShims(SHIM_REASON_DLL_LOAD
, LdrEntry
);
1252 VOID WINAPI
SE_DllUnloaded(PLDR_DATA_TABLE_ENTRY LdrEntry
)
1254 SHIMENG_INFO("(%p)\n", LdrEntry
);
1256 /* Should we unhook here? */
1258 NotifyShims(SHIM_REASON_DLL_UNLOAD
, LdrEntry
);
1261 BOOL WINAPI
SE_IsShimDll(PVOID BaseAddress
)
1263 SHIMENG_INFO("(%p)\n", BaseAddress
);
1265 return SeiGetShimModuleInfo(BaseAddress
) != NULL
;