Index: boot/bootdata/hivesys.inf =================================================================== --- boot/bootdata/hivesys.inf (revision 68391) +++ boot/bootdata/hivesys.inf (working copy) @@ -1280,7 +1280,11 @@ HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager","ObjectDirectories",0x00010000, \ "\Windows", \ "\RPC Control" +# This is an empty app compat cache +HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\AppCompatCache","AppCompatCache", 0x00000001, \ + fe,0f,dc,ba,00,00,00,00 + ; DOS devices HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\DOS Devices","AUX",0x00000000,"\DosDevices\COM1" HKLM,"SYSTEM\CurrentControlSet\Control\Session Manager\DOS Devices","MAILSLOT",0x00000000,"\Device\MailSlot" Index: include/ndk/psfuncs.h =================================================================== --- include/ndk/psfuncs.h (revision 68391) +++ include/ndk/psfuncs.h (working copy) @@ -326,13 +326,12 @@ _Out_opt_ PULONG SuspendCount ); -typedef ULONG APPHELPCACHESERVICECLASS; NTSYSCALLAPI NTSTATUS NTAPI NtApphelpCacheControl( _In_ APPHELPCACHESERVICECLASS Service, - _In_ PVOID ServiceData + _In_opt_ PAPPHELP_CACHE_SERVICE_LOOKUP ServiceData ); NTSYSCALLAPI Index: include/ndk/pstypes.h =================================================================== --- include/ndk/pstypes.h (revision 68391) +++ include/ndk/pstypes.h (working copy) @@ -810,6 +810,27 @@ BOOLEAN Foreground; } PROCESS_FOREGROUND_BACKGROUND, *PPROCESS_FOREGROUND_BACKGROUND; + +typedef enum _APPHELPCACHESERVICECLASS +{ + ApphelpCacheServiceLookup = 0, + ApphelpCacheServiceRemove = 1, + ApphelpCacheServiceUpdate = 2, + ApphelpCacheServiceFlush = 3, + ApphelpCacheServiceDump = 4, + + ApphelpDBGReadRegistry = 0x100, + ApphelpDBGWriteRegistry = 0x101, +} APPHELPCACHESERVICECLASS; + + +typedef struct _APPHELP_CACHE_SERVICE_LOOKUP +{ + UNICODE_STRING ImageName; + HANDLE ImageHandle; +} APPHELP_CACHE_SERVICE_LOOKUP, *PAPPHELP_CACHE_SERVICE_LOOKUP; + + // // Thread Information Structures for NtQueryProcessInformation // Index: ntoskrnl/include/internal/ps.h =================================================================== --- ntoskrnl/include/internal/ps.h (revision 68391) +++ ntoskrnl/include/internal/ps.h (working copy) @@ -413,6 +413,18 @@ PspIsProcessExiting(IN PEPROCESS Process); // +// Apphelp functions +// +NTSTATUS +NTAPI +INIT_FUNCTION +ApphelpCacheInitialize(VOID); + +VOID +NTAPI +ApphelpCacheShutdown(VOID); + +// // Global data inside the Process Manager // extern ULONG PspTraceLevel; Index: ntoskrnl/io/iomgr/iomgr.c =================================================================== --- ntoskrnl/io/iomgr/iomgr.c (revision 68391) +++ ntoskrnl/io/iomgr/iomgr.c (working copy) @@ -531,6 +531,9 @@ /* Initialize PnP manager */ IopInitializePlugPlayServices(); + /* Initialize SHIM engine */ + ApphelpCacheInitialize(); + /* Initialize WMI */ WmiInitialize(); Index: ntoskrnl/ntos.cmake =================================================================== --- ntoskrnl/ntos.cmake (revision 68391) +++ ntoskrnl/ntos.cmake (working copy) @@ -248,6 +248,7 @@ ${REACTOS_SOURCE_DIR}/ntoskrnl/ps/job.c ${REACTOS_SOURCE_DIR}/ntoskrnl/ps/kill.c ${REACTOS_SOURCE_DIR}/ntoskrnl/ps/process.c + ${REACTOS_SOURCE_DIR}/ntoskrnl/ps/apphelp.c ${REACTOS_SOURCE_DIR}/ntoskrnl/ps/psmgr.c ${REACTOS_SOURCE_DIR}/ntoskrnl/ps/psnotify.c ${REACTOS_SOURCE_DIR}/ntoskrnl/ps/query.c Index: ntoskrnl/po/poshtdwn.c =================================================================== --- ntoskrnl/po/poshtdwn.c (revision 68391) +++ ntoskrnl/po/poshtdwn.c (working copy) @@ -267,6 +267,9 @@ DPRINT("HAL shutting down\n"); HalEndOfBoot(); + /* Shut down the Shim cache if enabled */ + ApphelpCacheShutdown(); + /* In this step, the I/O manager does first-chance shutdown notification */ DPRINT("I/O manager shutting down in phase 0\n"); IoShutdownSystem(0); Index: ntoskrnl/ps/apphelp.c =================================================================== --- ntoskrnl/ps/apphelp.c (revision 0) +++ ntoskrnl/ps/apphelp.c (working copy) @@ -0,0 +1,715 @@ +/* + * PROJECT: ReactOS Kernel + * LICENSE: BSD - See COPYING.ARM in the top level directory + * FILE: ntoskrnl/ps/apphelp.c + * PURPOSE: SHIM engine caching. + * This caching speeds up checks for the apphelp compatibility layer. + * PROGRAMMERS: Mark Jansen + */ + +/* +Useful references: +https://github.com/mandiant/ShimCacheParser/blob/master/ShimCacheParser.py +http://technet.microsoft.com/en-us/library/dd837644(v=ws.10).aspx +http://msdn.microsoft.com/en-us/library/bb432182(v=vs.85).aspx +http://www.alex-ionescu.com/?p=43 +http://recxltd.blogspot.nl/2012/04/windows-appcompat-research-notes-part-1.html +http://journeyintoir.blogspot.ch/2013/12/revealing-recentfilecachebcf-file.html +https://dl.mandiant.com/EE/library/Whitepaper_ShimCacheParser.pdf +*/ + +/* INCLUDES ******************************************************************/ + +#include +#define NDEBUG +#include + + +static BOOLEAN ApphelpCacheEnabled = FALSE; +static ERESOURCE ApphelpCacheLock; +static RTL_AVL_TABLE ApphelpShimCache; +static LIST_ENTRY ApphelpShimCacheAge; + +extern ULONG InitSafeBootMode; + +static UNICODE_STRING AppCompatCacheKey = RTL_CONSTANT_STRING(L"\\Registry\\MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\\AppCompatCache"); +static OBJECT_ATTRIBUTES AppCompatKeyAttributes = RTL_CONSTANT_OBJECT_ATTRIBUTES(&AppCompatCacheKey, OBJ_CASE_INSENSITIVE); +static UNICODE_STRING AppCompatCacheValue = RTL_CONSTANT_STRING(L"AppCompatCache"); + +#ifdef _WIN64 +#define SHIM_CACHE_OFFSET_TYPE ULONGLONG +#else +#define SHIM_CACHE_OFFSET_TYPE ULONG +#endif + +#define EMPTY_SHIM_ENTRY { { 0 }, { { 0 } }, 0 } +#define MAX_SHIM_ENTRIES 0x200 +#define TAG_SHIM 'MIHS' + +#include + +typedef struct SHIM_PERSISTENT_CACHE_HEADER_52 +{ + ULONG Magic; + ULONG NumEntries; +} SHIM_PERSISTENT_CACHE_HEADER_52, *LPSHIM_PERSISTENT_CACHE_HEADER_52; + +/* The data that is present in the registry (Win2k3 version) */ +typedef struct SHIM_PERSISTENT_CACHE_ENTRY_52 +{ + UNICODE_STRING ImageName; + ULONG LowDateTime; + ULONG HighDateTime; + ULONG FileSizeLow; + ULONG FileSizeHigh; +} SHIM_PERSISTENT_CACHE_ENTRY_52, *LPSHIM_PERSISTENT_CACHE_ENTRY_52; + +#include + +#define CACHE_MAGIC_NT_52 0xbadc0ffe +#define CACHE_HEADER_SIZE_NT_52 0x8 +#define NT52_PERSISTENT_ENTRY_SIZE32 0x18 +#define NT52_PERSISTENT_ENTRY_SIZE64 0x20 + +//#define CACHE_MAGIC_NT_61 0xbadc0fee +//#define CACHE_HEADER_SIZE_NT_61 0x80 +//#define NT61_PERSISTENT_ENTRY_SIZE32 0x20 +//#define NT61_PERSISTENT_ENTRY_SIZE64 0x30 + +#define SHIM_CACHE_MAGIC CACHE_MAGIC_NT_52 +#define SHIM_CACHE_HEADER_SIZE CACHE_HEADER_SIZE_NT_52 +#ifdef _WIN64 +#define SHIM_PERSISTENT_CACHE_ENTRY_SIZE NT52_PERSISTENT_ENTRY_SIZE64 +#else +#define SHIM_PERSISTENT_CACHE_ENTRY_SIZE NT52_PERSISTENT_ENTRY_SIZE32 +#endif +#define SHIM_PERSISTENT_CACHE_HEADER SHIM_PERSISTENT_CACHE_HEADER_52 +#define LPSHIM_PERSISTENT_CACHE_HEADER LPSHIM_PERSISTENT_CACHE_HEADER_52 +#define SHIM_PERSISTENT_CACHE_ENTRY SHIM_PERSISTENT_CACHE_ENTRY_52 +#define LPSHIM_PERSISTENT_CACHE_ENTRY LPSHIM_PERSISTENT_CACHE_ENTRY_52 + +C_ASSERT(sizeof(SHIM_PERSISTENT_CACHE_ENTRY) == SHIM_PERSISTENT_CACHE_ENTRY_SIZE); +C_ASSERT(sizeof(SHIM_PERSISTENT_CACHE_HEADER) == SHIM_CACHE_HEADER_SIZE); + +/* The struct we keep in memory */ +typedef struct SHIM_CACHE_ENTRY +{ + LIST_ENTRY List; + SHIM_PERSISTENT_CACHE_ENTRY Persistent; + ULONG CompatFlags; +} SHIM_CACHE_ENTRY, *LPSHIM_CACHE_ENTRY; + +/* Helper functions */ +PVOID +ApphelpAlloc(ULONG ByteSize) +{ + return ExAllocatePoolWithTag(PagedPool, ByteSize, TAG_SHIM); +} + +VOID +ApphelpFree(PVOID Data) +{ + ExFreePoolWithTag(Data, TAG_SHIM); +} + +VOID +ApphelpCacheAcquireLock(VOID) +{ + KeEnterCriticalRegion(); + ExAcquireResourceExclusiveLite(&ApphelpCacheLock, TRUE); +} + +BOOLEAN +ApphelpCacheTryAcquireLock(VOID) +{ + KeEnterCriticalRegion(); + if (!ExTryToAcquireResourceExclusiveLite(&ApphelpCacheLock)) + { + KeLeaveCriticalRegion(); + return FALSE; + } + return TRUE; +} + +VOID +ApphelpCacheReleaseLock(VOID) +{ + ExReleaseResourceLite(&ApphelpCacheLock); + KeLeaveCriticalRegion(); +} + +VOID ApphelpDuplicateUnicodeString(OUT PUNICODE_STRING Destination, + IN PUNICODE_STRING Source) +{ + Destination->Length = Source->Length; + if (Destination->Length) + { + Destination->MaximumLength = Destination->Length + sizeof(WCHAR); + Destination->Buffer = ApphelpAlloc(Destination->MaximumLength); + RtlCopyMemory(Destination->Buffer, Source->Buffer, Destination->Length); + Destination->Buffer[Destination->Length / sizeof(WCHAR)] = 0; + } + else + { + Destination->MaximumLength = 0; + Destination->Buffer = NULL; + } +} + +VOID ApphelpFreeUnicodeString(IN OUT PUNICODE_STRING String) +{ + if (String->Buffer) + ApphelpFree(String->Buffer); + String->Length = 0; + String->MaximumLength = 0; + String->Buffer = NULL; +} + +/* Query file info from a handle, storing it in Entry */ +NTSTATUS +ApphelpCacheQueryInfo(IN HANDLE ImageHandle, OUT LPSHIM_CACHE_ENTRY Entry) +{ + IO_STATUS_BLOCK IoStatusBlock; + FILE_BASIC_INFORMATION FileBasic; + FILE_STANDARD_INFORMATION FileStandard; + NTSTATUS Status = ZwQueryInformationFile(ImageHandle, &IoStatusBlock, + &FileBasic, sizeof(FileBasic), FileBasicInformation); + if (NT_SUCCESS(Status)) + { + Status = ZwQueryInformationFile(ImageHandle, &IoStatusBlock, + &FileStandard, sizeof(FileStandard), FileStandardInformation); + if (NT_SUCCESS(Status)) + { + Entry->Persistent.LowDateTime = FileBasic.LastWriteTime.LowPart; + Entry->Persistent.HighDateTime = FileBasic.LastWriteTime.HighPart; + Entry->Persistent.FileSizeLow = FileStandard.EndOfFile.LowPart; + Entry->Persistent.FileSizeHigh = FileStandard.EndOfFile.HighPart; + } + } + return Status; +} + +RTL_GENERIC_COMPARE_RESULTS +NTAPI +ApphelpShimCacheCompareRoutine(IN PRTL_AVL_TABLE Table, + IN PVOID FirstStruct, + IN PVOID SecondStruct) +{ + LONG lResult = RtlCompareUnicodeString( + &((LPSHIM_CACHE_ENTRY)FirstStruct)->Persistent.ImageName, + &((LPSHIM_CACHE_ENTRY)SecondStruct)->Persistent.ImageName, TRUE); + if (lResult < 0) + return GenericLessThan; + else if (lResult == 0) + return GenericEqual; + return GenericGreaterThan; +} + +PVOID +NTAPI +ApphelpShimCacheAllocateRoutine(IN PRTL_AVL_TABLE Table, + IN CLONG ByteSize) +{ + return ApphelpAlloc(ByteSize); +} + +VOID +NTAPI +ApphelpShimCacheFreeRoutine(IN PRTL_AVL_TABLE Table, + IN PVOID Buffer) +{ + ApphelpFree(Buffer); +} + +NTSTATUS +ApphelpCacheParse(IN PUCHAR Data, IN ULONG DataLength) +{ + LPSHIM_PERSISTENT_CACHE_HEADER Header = (LPSHIM_PERSISTENT_CACHE_HEADER)Data; + + if( DataLength < CACHE_HEADER_SIZE_NT_52 ) + { + DPRINT1("SHIMS: ApphelpCacheParse not enough data for a minimal header (0x%x)\n", DataLength); + return STATUS_INVALID_PARAMETER; + } + if (Header->Magic == SHIM_CACHE_MAGIC) + { + ULONG Cur; + ULONG NumEntries = Header->NumEntries; + DPRINT1("SHIMS: ApphelpCacheParse walking %d entries\n", NumEntries); + for (Cur = 0; Cur < NumEntries; ++Cur) + { + UNICODE_STRING String; + SHIM_CACHE_ENTRY Entry = EMPTY_SHIM_ENTRY; + LPSHIM_CACHE_ENTRY Result; + LPSHIM_PERSISTENT_CACHE_ENTRY pPersistent = + (LPSHIM_PERSISTENT_CACHE_ENTRY)(Data + SHIM_CACHE_HEADER_SIZE + + (Cur * SHIM_PERSISTENT_CACHE_ENTRY_SIZE)); + /* The entry in the Persitent storage is not really a UNICODE_STRING, + so we have to convert the offset into a real pointer before using it. */ + String.Length = pPersistent->ImageName.Length; + String.MaximumLength = pPersistent->ImageName.MaximumLength; + String.Buffer = (PWCHAR)((SHIM_CACHE_OFFSET_TYPE)pPersistent->ImageName.Buffer + Data); + + /* Now we copy all data to a local buffer, that can be safely duplicated by RtlInsert */ + Entry.Persistent = *pPersistent; + ApphelpDuplicateUnicodeString(&Entry.Persistent.ImageName, &String); + Result = RtlInsertElementGenericTableAvl(&ApphelpShimCache, &Entry, sizeof(Entry), NULL); + if (!Result) + { + DPRINT1("SHIMS: ApphelpCacheParse insert failed\n"); + ApphelpFreeUnicodeString(&Entry.Persistent.ImageName); + return STATUS_INVALID_PARAMETER; + } + InsertTailList(&ApphelpShimCacheAge, &Result->List); + } + return STATUS_SUCCESS; + } + DPRINT1("SHIMS: ApphelpCacheParse found invalid magic (0x%x)\n", Header->Magic); + return STATUS_INVALID_PARAMETER; +} + +BOOLEAN +ApphelpCacheRead(VOID) +{ + HANDLE KeyHandle; + NTSTATUS Status; + KEY_VALUE_PARTIAL_INFORMATION KeyValueObject; + PKEY_VALUE_PARTIAL_INFORMATION KeyValueInformation = &KeyValueObject; + ULONG KeyInfoSize, ResultSize; + + Status = ZwOpenKey(&KeyHandle, KEY_QUERY_VALUE, &AppCompatKeyAttributes); + + if (NT_SUCCESS(Status)) + { + Status = ZwQueryValueKey(KeyHandle, &AppCompatCacheValue, + KeyValuePartialInformation, KeyValueInformation, + sizeof(KeyValueObject), &ResultSize); + } + else + { + DPRINT1("SHIMS: ApphelpCacheRead could not even open Session Manager\\AppCompatCache (0x%x)\n", Status); + return FALSE; + } + + if (Status == STATUS_BUFFER_OVERFLOW) + { + KeyInfoSize = sizeof(KEY_VALUE_PARTIAL_INFORMATION) + KeyValueInformation->DataLength; + KeyValueInformation = ApphelpAlloc(KeyInfoSize); + if (KeyValueInformation != NULL) + { + Status = ZwQueryValueKey(KeyHandle, &AppCompatCacheValue, + KeyValuePartialInformation, KeyValueInformation, + KeyInfoSize, &ResultSize); + } + } + + if (NT_SUCCESS(Status) && KeyValueInformation->Type == REG_BINARY) + { + Status = ApphelpCacheParse(KeyValueInformation->Data, + KeyValueInformation->DataLength); + } + else + { + DPRINT1("SHIMS: ApphelpCacheRead not loaded from registry (0x%x)\n", Status); + } + + if (KeyValueInformation != &KeyValueObject && KeyValueInformation != NULL) + ApphelpFree(KeyValueInformation); + + ZwClose(KeyHandle); + return NT_SUCCESS(Status); +} + +BOOLEAN +ApphelpCacheWrite(VOID) +{ + ULONG Length = 8; + ULONG NumEntries = 0; + PLIST_ENTRY ListEntry; + PUCHAR Buffer, BufferNamePos; + LPSHIM_PERSISTENT_CACHE_HEADER Header; + LPSHIM_PERSISTENT_CACHE_ENTRY WriteEntry; + HANDLE KeyHandle; + NTSTATUS Status; + + /* First we have to calculate the required size. */ + ApphelpCacheAcquireLock(); + ListEntry = ApphelpShimCacheAge.Flink; + while (ListEntry != &ApphelpShimCacheAge) + { + LPSHIM_CACHE_ENTRY Entry = CONTAINING_RECORD(ListEntry, SHIM_CACHE_ENTRY, List); + Length += SHIM_PERSISTENT_CACHE_ENTRY_SIZE; + Length += Entry->Persistent.ImageName.MaximumLength; + ++NumEntries; + ListEntry = ListEntry->Flink; + } + DPRINT1("SHIMS: ApphelpCacheWrite, %d Entries, total size: %d\n", NumEntries, Length); + Length = ROUND_UP(Length, 8); + DPRINT1("SHIMS: ApphelpCacheWrite, Rounded to: %d\n", Length); + + /* Now we allocate and prepare some helpers */ + Buffer = ApphelpAlloc(Length); + BufferNamePos = Buffer + Length; + Header = (LPSHIM_PERSISTENT_CACHE_HEADER)Buffer; + WriteEntry = (LPSHIM_PERSISTENT_CACHE_ENTRY)(Buffer + SHIM_CACHE_HEADER_SIZE); + + Header->Magic = SHIM_CACHE_MAGIC; + Header->NumEntries = NumEntries; + + ListEntry = ApphelpShimCacheAge.Flink; + while (ListEntry != &ApphelpShimCacheAge) + { + LPSHIM_CACHE_ENTRY Entry = CONTAINING_RECORD(ListEntry, SHIM_CACHE_ENTRY, List);//(LPSHIM_CACHE_ENTRY)ListEntry; + USHORT ImageNameLen = Entry->Persistent.ImageName.MaximumLength; + /* Copy the Persistent structure over */ + *WriteEntry = Entry->Persistent; + BufferNamePos -= ImageNameLen; + /* Copy the image name over */ + RtlCopyMemory(BufferNamePos, Entry->Persistent.ImageName.Buffer, ImageNameLen); + /* Fix the Persistent structure, so that Buffer is once again an offset */ + WriteEntry->ImageName.Buffer = (PWCH)(BufferNamePos - Buffer); + + ++WriteEntry; + ListEntry = ListEntry->Flink; + } + ApphelpCacheReleaseLock(); + + Status = ZwOpenKey(&KeyHandle, KEY_SET_VALUE, &AppCompatKeyAttributes); + if (NT_SUCCESS(Status)) + { + Status = ZwSetValueKey(KeyHandle, &AppCompatCacheValue, 0, REG_BINARY, Buffer, Length); + } + else + { + DPRINT1("SHIMS: ApphelpCacheWrite could not even open Session Manager\\AppCompatCache (0x%x)\n", Status); + } + if (KeyHandle) + ZwClose(KeyHandle); + + ApphelpFree(Buffer); + return NT_SUCCESS(Status); +} + + +NTSTATUS +NTAPI +INIT_FUNCTION +ApphelpCacheInitialize(VOID) +{ + DPRINT1("SHIMS: ApphelpCacheInitialize\n"); + /* If we are booting in safemode we do not want to use the apphelp cache */ + if (InitSafeBootMode) + { + DPRINT1("SHIMS: Safe mode detected, disabling cache.\n"); + ApphelpCacheEnabled = FALSE; + } + else + { + ExInitializeResourceLite(&ApphelpCacheLock); + RtlInitializeGenericTableAvl(&ApphelpShimCache, + ApphelpShimCacheCompareRoutine, + ApphelpShimCacheAllocateRoutine, + ApphelpShimCacheFreeRoutine, + NULL); + InitializeListHead(&ApphelpShimCacheAge); + ApphelpCacheEnabled = ApphelpCacheRead(); + } + DPRINT1("SHIMS: ApphelpCacheInitialize: %d\n", ApphelpCacheEnabled); + return STATUS_SUCCESS; +} + +VOID +NTAPI +ApphelpCacheShutdown(VOID) +{ + if (ApphelpCacheEnabled) + { + ApphelpCacheWrite(); + } +} + +NTSTATUS +ApphelpValidateData(IN PAPPHELP_CACHE_SERVICE_LOOKUP ServiceData, + OUT PUNICODE_STRING ImageName, + OUT HANDLE* ImageHandle) +{ + NTSTATUS Status = STATUS_INVALID_PARAMETER; + if (ServiceData) + { + UNICODE_STRING LocalImageName; + _SEH2_TRY + { + ProbeForRead(ServiceData, sizeof(APPHELP_CACHE_SERVICE_LOOKUP), sizeof(ULONG)); + LocalImageName = ServiceData->ImageName; + *ImageHandle = ServiceData->ImageHandle; + if (LocalImageName.Length && LocalImageName.Buffer) + { + ProbeForRead(LocalImageName.Buffer, LocalImageName.Length * sizeof(WCHAR), 1); + ApphelpDuplicateUnicodeString(ImageName, &LocalImageName); + Status = STATUS_SUCCESS; + } + } + _SEH2_EXCEPT(EXCEPTION_EXECUTE_HANDLER) + { + _SEH2_YIELD(return _SEH2_GetExceptionCode()); + } + _SEH2_END; + } + if (!NT_SUCCESS(Status)) + { + DPRINT1("SHIMS: ApphelpValidateData: invalid data passed\n"); + } + return Status; +} + +NTSTATUS +ApphelpCacheRemoveEntryNolock(IN LPSHIM_CACHE_ENTRY Entry) +{ + if (Entry) + { + PWSTR Buffer = Entry->Persistent.ImageName.Buffer; + RemoveEntryList(&Entry->List); + if (RtlDeleteElementGenericTableAvl(&ApphelpShimCache, Entry)) + ApphelpFree(Buffer); + return STATUS_SUCCESS; + } + return STATUS_NOT_FOUND; +} + +NTSTATUS +ApphelpCacheLookupEntry(IN PUNICODE_STRING ImageName, + IN HANDLE ImageHandle) +{ + NTSTATUS Status = STATUS_NOT_FOUND; + if (ApphelpCacheTryAcquireLock()) + { + SHIM_CACHE_ENTRY Lookup = EMPTY_SHIM_ENTRY; + LPSHIM_CACHE_ENTRY Entry; + Lookup.Persistent.ImageName = *ImageName; + Entry = RtlLookupElementGenericTableAvl(&ApphelpShimCache, &Lookup); + if (Entry) + { + DPRINT1("SHIMS: ApphelpCacheLookupEntry: found %S\n", ImageName->Buffer); + if (ImageHandle == INVALID_HANDLE_VALUE) + { + DPRINT1("SHIMS: ApphelpCacheLookupEntry: ok\n"); + /* just return if we know it, do not query file info */ + Status = STATUS_SUCCESS; + } + else if (NT_SUCCESS(ApphelpCacheQueryInfo(ImageHandle, &Lookup)) && + Lookup.Persistent.LowDateTime == Entry->Persistent.LowDateTime && + Lookup.Persistent.HighDateTime == Entry->Persistent.HighDateTime && + Lookup.Persistent.FileSizeLow == Entry->Persistent.FileSizeLow && + Lookup.Persistent.FileSizeHigh == Entry->Persistent.FileSizeHigh) + { + DPRINT1("SHIMS: ApphelpCacheLookupEntry: found & validated\n"); + Status = STATUS_SUCCESS; + /* move it to the front to keep it alive */ + RemoveEntryList(&Entry->List); + InsertHeadList(&ApphelpShimCacheAge, &Entry->List); + } + else + { + DPRINT1("SHIMS: ApphelpCacheLookupEntry: file info mismatch\n"); + /* Could not read file info, or it did not match, drop it from the cache */ + ApphelpCacheRemoveEntryNolock(Entry); + } + } + else + { + DPRINT1("SHIMS: ApphelpCacheLookupEntry: could not find %S\n", ImageName->Buffer); + } + ApphelpCacheReleaseLock(); + } + return Status; +} + +NTSTATUS +ApphelpCacheRemoveEntry(IN PUNICODE_STRING ImageName) +{ + LPSHIM_CACHE_ENTRY Entry; + NTSTATUS Status; + ApphelpCacheAcquireLock(); + Entry = RtlLookupElementGenericTableAvl(&ApphelpShimCache, ImageName); + Status = ApphelpCacheRemoveEntryNolock(Entry); + ApphelpCacheReleaseLock(); + return Status; +} + +/* Validate that we are either called from r0, or from a service-like context */ +NTSTATUS +ApphelpCacheAccessCheck(VOID) +{ + if (ExGetPreviousMode() != KernelMode) + { + if (!SeSinglePrivilegeCheck(SeTcbPrivilege, UserMode)) + { + DPRINT1("SHIMS: ApphelpCacheAccessCheck failed\n"); + return STATUS_ACCESS_DENIED; + } + } + return STATUS_SUCCESS; +} + +NTSTATUS +ApphelpCacheUpdateEntry(IN PUNICODE_STRING ImageName, + IN HANDLE ImageHandle) +{ + NTSTATUS Status = STATUS_SUCCESS; + SHIM_CACHE_ENTRY Entry = EMPTY_SHIM_ENTRY; + LPSHIM_CACHE_ENTRY Lookup; + PVOID NodeOrParent; + TABLE_SEARCH_RESULT SearchResult; + + ApphelpCacheAcquireLock(); + + /* If we got a file handle, query it for info */ + if (ImageHandle != INVALID_HANDLE_VALUE) + Status = ApphelpCacheQueryInfo(ImageHandle, &Entry); + + if (NT_SUCCESS(Status)) + { + /* Use ImageName for the lookup, don't actually duplicate it */ + Entry.Persistent.ImageName = *ImageName; + Lookup = RtlLookupElementGenericTableFullAvl(&ApphelpShimCache, &Entry, + &NodeOrParent, &SearchResult); + if (Lookup) + { + DPRINT1("SHIMS: ApphelpCacheUpdateEntry: Entry already exists, reusing it\n"); + /* Unlink the found item, so we can put it back at the front, + and copy the earlier obtained file info*/ + RemoveEntryList(&Lookup->List); + Lookup->Persistent.LowDateTime = Entry.Persistent.LowDateTime; + Lookup->Persistent.HighDateTime = Entry.Persistent.HighDateTime; + Lookup->Persistent.FileSizeLow = Entry.Persistent.FileSizeLow; + Lookup->Persistent.FileSizeHigh = Entry.Persistent.FileSizeHigh; + } + else + { + DPRINT1("SHIMS: ApphelpCacheUpdateEntry: Inserting new Entry\n"); + /* Insert a new entry, with it's own copy of the ImageName */ + ApphelpDuplicateUnicodeString(&Entry.Persistent.ImageName, ImageName); + Lookup = RtlInsertElementGenericTableFullAvl(&ApphelpShimCache, + &Entry, sizeof(Entry), 0, NodeOrParent, SearchResult); + if (!Lookup) + { + ApphelpFreeUnicodeString(&Entry.Persistent.ImageName); + Status = STATUS_NO_MEMORY; + } + } + if (Lookup) + { + /* Either we re-used an existing item, or we inserted a new one, keep it alive */ + InsertHeadList(&ApphelpShimCacheAge, &Lookup->List); + if (RtlNumberGenericTableElementsAvl(&ApphelpShimCache) > MAX_SHIM_ENTRIES) + { + DPRINT1("SHIMS: ApphelpCacheUpdateEntry: Cache growing too big, dropping oldest item\n"); + Status = ApphelpCacheRemoveEntryNolock((LPSHIM_CACHE_ENTRY)ApphelpShimCacheAge.Blink); + } + } + } + ApphelpCacheReleaseLock(); + return Status; +} + +NTSTATUS +ApphelpCacheFlush(VOID) +{ + PVOID p; + DPRINT1("SHIMS: ApphelpCacheFlush\n"); + ApphelpCacheAcquireLock(); + while ((p = RtlEnumerateGenericTableAvl(&ApphelpShimCache, TRUE))) + { + ApphelpCacheRemoveEntryNolock((LPSHIM_CACHE_ENTRY)p); + } + ApphelpCacheReleaseLock(); + return STATUS_SUCCESS; +} + +NTSTATUS +ApphelpCacheDump(VOID) +{ + PLIST_ENTRY ListEntry; + DPRINT1("SHIMS: NtApphelpCacheControl( Dumping entries, newset to oldest )\n"); + ApphelpCacheAcquireLock(); + ListEntry = ApphelpShimCacheAge.Flink; + while (ListEntry != &ApphelpShimCacheAge) + { + LPSHIM_CACHE_ENTRY Entry = (LPSHIM_CACHE_ENTRY)ListEntry; + DPRINT1("Entry: %S\n", Entry->Persistent.ImageName.Buffer); + DPRINT1("DateTime High: 0x%x, Low: 0x%x\n", + Entry->Persistent.HighDateTime, Entry->Persistent.LowDateTime); + DPRINT1("FileSize High: 0x%x, Low: 0x%x\n", + Entry->Persistent.FileSizeHigh, Entry->Persistent.FileSizeLow); + DPRINT1("Flags: 0x%x\n", Entry->CompatFlags); + ListEntry = ListEntry->Flink; + } + ApphelpCacheReleaseLock(); + return STATUS_SUCCESS; +} + +NTSTATUS +NTAPI +NtApphelpCacheControl(IN APPHELPCACHESERVICECLASS Service, + IN PAPPHELP_CACHE_SERVICE_LOOKUP ServiceData) +{ + NTSTATUS Status = STATUS_INVALID_PARAMETER; + UNICODE_STRING ImageName = { 0 }; + HANDLE Handle = INVALID_HANDLE_VALUE; + + if (ApphelpCacheEnabled) + { + switch (Service) + { + case ApphelpCacheServiceLookup: + DPRINT1("SHIMS: NtApphelpCacheControl( ApphelpCacheServiceLookup )\n"); + Status = ApphelpValidateData(ServiceData, &ImageName, &Handle); + if (NT_SUCCESS(Status)) + Status = ApphelpCacheLookupEntry(&ImageName, Handle); + break; + case ApphelpCacheServiceRemove: + DPRINT1("SHIMS: NtApphelpCacheControl( ApphelpCacheServiceRemove )\n"); + Status = ApphelpValidateData(ServiceData, &ImageName, &Handle); + if (NT_SUCCESS(Status)) + Status = ApphelpCacheRemoveEntry(&ImageName); + break; + case ApphelpCacheServiceUpdate: + DPRINT1("SHIMS: NtApphelpCacheControl( ApphelpCacheServiceUpdate )\n"); + Status = ApphelpCacheAccessCheck(); + if (NT_SUCCESS(Status)) + { + Status = ApphelpValidateData(ServiceData, &ImageName, &Handle); + if (NT_SUCCESS(Status)) + Status = ApphelpCacheUpdateEntry(&ImageName, Handle); + } + break; + case ApphelpCacheServiceFlush: + Status = ApphelpCacheFlush(); + break; + case ApphelpCacheServiceDump: + Status = ApphelpCacheDump(); + break; + case ApphelpDBGReadRegistry: + DPRINT1("SHIMS: NtApphelpCacheControl( ApphelpDBGReadRegistry ): flushing cache.\n"); + ApphelpCacheFlush(); + DPRINT1("SHIMS: NtApphelpCacheControl( ApphelpDBGReadRegistry ): reading cache.\n"); + Status = ApphelpCacheRead() ? STATUS_SUCCESS : STATUS_NOT_FOUND; + break; + case ApphelpDBGWriteRegistry: + DPRINT1("SHIMS: NtApphelpCacheControl( ApphelpDBGWriteRegistry ): writing cache.\n"); + Status = ApphelpCacheWrite() ? STATUS_SUCCESS : STATUS_NOT_FOUND; + break; + default: + DPRINT1("SHIMS: NtApphelpCacheControl( Invalid service requested )\n"); + break; + } + } + else + { + DPRINT1("NtApphelpCacheControl: ApphelpCacheEnabled == 0\n"); + } + if (ImageName.Buffer) + ApphelpFreeUnicodeString(&ImageName); + return Status; +} + Index: ntoskrnl/ps/psmgr.c =================================================================== --- ntoskrnl/ps/psmgr.c (revision 68391) +++ ntoskrnl/ps/psmgr.c (working copy) @@ -678,13 +678,4 @@ return (NtBuildNumber >> 28) == 0xC; } -NTSTATUS -NTAPI -NtApphelpCacheControl(IN APPHELPCACHESERVICECLASS Service, - IN PVOID ServiceData) -{ - UNIMPLEMENTED; - return STATUS_NOT_IMPLEMENTED; -} - /* EOF */