2 * PROJECT: ReactOS Application compatibility module
3 * LICENSE: GPL-2.0+ (https://spdx.org/licenses/GPL-2.0+)
4 * PURPOSE: Shim matching / data (un)packing
5 * COPYRIGHT: Copyright 2011 André Hentschel
6 * Copyright 2013 Mislav Blaževic
7 * Copyright 2015-2018 Mark Jansen (mark.jansen@reactos.org)
10 #define WIN32_NO_STATUS
17 #define MAX_LAYER_LENGTH 256
19 #define GPLK_MACHINE 2
21 typedef struct _ShimData
23 WCHAR szModule
[MAX_PATH
];
27 WCHAR szLayer
[MAX_LAYER_LENGTH
];
28 DWORD unknown
; // 0x14c
31 #define SHIMDATA_MAGIC 0xAC0DEDAB
34 static BOOL WINAPI
SdbpFileExists(LPCWSTR path
)
36 DWORD attr
= GetFileAttributesW(path
);
37 return (attr
!= INVALID_FILE_ATTRIBUTES
&& !(attr
& FILE_ATTRIBUTE_DIRECTORY
));
40 /* Given a 'MATCHING_FILE' tag and an ATTRINFO array,
41 check all tags defined in the MATCHING_FILE against the ATTRINFO */
42 static BOOL
SdbpMatchFileAttributes(PDB pdb
, TAGID matching_file
, PATTRINFO attribs
, DWORD attr_count
)
46 for (child
= SdbGetFirstChild(pdb
, matching_file
);
47 child
!= TAGID_NULL
; child
= SdbGetNextChild(pdb
, matching_file
, child
))
49 TAG tag
= SdbGetTagFromTagID(pdb
, child
);
52 /* Already handled! */
56 if (tag
== TAG_UPTO_BIN_FILE_VERSION
||
57 tag
== TAG_UPTO_BIN_PRODUCT_VERSION
||
58 tag
== TAG_UPTO_LINK_DATE
)
60 SHIM_WARN("Unimplemented TAG_UPTO_XXXXX\n");
64 for (n
= 0; n
< attr_count
; ++n
)
66 PATTRINFO attr
= attribs
+ n
;
67 if (attr
->flags
== ATTRIBUTE_AVAILABLE
&& attr
->type
== tag
)
72 switch (tag
& TAG_TYPE_MASK
)
75 dwval
= SdbReadDWORDTag(pdb
, child
, 0);
76 if (dwval
!= attr
->dwattr
)
79 case TAG_TYPE_STRINGREF
:
80 lpval
= SdbGetStringTagPtr(pdb
, child
);
81 if (!lpval
|| wcsicmp(attr
->lpattr
, lpval
))
85 qwval
= SdbReadQWORDTag(pdb
, child
, 0);
86 if (qwval
!= attr
->qwattr
)
90 SHIM_WARN("Unhandled type 0x%x MATCHING_FILE\n", (tag
& TAG_TYPE_MASK
));
96 SHIM_WARN("Unhandled tag %ws in MACHING_FILE\n", SdbTagToString(tag
));
101 /* Given an 'exe' tag and an ATTRINFO array (for the main file),
102 verify that the main file and any additional files match */
103 static BOOL WINAPI
SdbpMatchExe(PDB pdb
, TAGID exe
, const WCHAR
* dir
, PATTRINFO main_attribs
, DWORD main_attr_count
)
105 RTL_UNICODE_STRING_BUFFER FullPathName
= { { 0 } };
106 WCHAR FullPathBuffer
[MAX_PATH
];
107 UNICODE_STRING UnicodeDir
;
109 PATTRINFO attribs
= NULL
;
111 BOOL IsMatch
= FALSE
;
113 RtlInitUnicodeString(&UnicodeDir
, dir
);
114 RtlInitBuffer(&FullPathName
.ByteBuffer
, (PUCHAR
)FullPathBuffer
, sizeof(FullPathBuffer
));
116 for (matching_file
= SdbFindFirstTag(pdb
, exe
, TAG_MATCHING_FILE
);
117 matching_file
!= TAGID_NULL
; matching_file
= SdbFindNextTag(pdb
, exe
, matching_file
))
119 TAGID tagName
= SdbFindFirstTag(pdb
, matching_file
, TAG_NAME
);
123 RtlInitUnicodeString(&Name
, SdbGetStringTagPtr(pdb
, tagName
));
128 /* An '*' here means use the main executable' */
129 if (!wcscmp(Name
.Buffer
, L
"*"))
131 /* We already have these attributes, so we do not need to retrieve them */
132 if (!SdbpMatchFileAttributes(pdb
, matching_file
, main_attribs
, main_attr_count
))
137 /* Technically, one UNICODE_NULL and one path separator. */
138 Len
= UnicodeDir
.Length
+ Name
.Length
+ sizeof(UNICODE_NULL
) + sizeof(UNICODE_NULL
);
139 if (!NT_SUCCESS(RtlEnsureBufferSize(RTL_SKIP_BUFFER_COPY
, &FullPathName
.ByteBuffer
, Len
)))
142 if (Len
> FullPathName
.ByteBuffer
.Size
)
145 RtlInitEmptyUnicodeString(&FullPathName
.String
, (PWCHAR
)FullPathName
.ByteBuffer
.Buffer
, FullPathName
.ByteBuffer
.Size
);
147 RtlCopyUnicodeString(&FullPathName
.String
, &UnicodeDir
);
148 RtlAppendUnicodeToString(&FullPathName
.String
, L
"\\");
149 RtlAppendUnicodeStringToString(&FullPathName
.String
, &Name
);
151 /* If the file does not exist, do not bother trying to read it's attributes */
152 if (!SdbpFileExists(FullPathName
.String
.Buffer
))
155 /* Do we have some attributes from the previous iteration? */
157 SdbFreeFileAttributes(attribs
);
159 if (!SdbGetFileAttributes(FullPathName
.String
.Buffer
, &attribs
, &attr_count
))
162 if (!SdbpMatchFileAttributes(pdb
, matching_file
, attribs
, attr_count
))
169 RtlFreeBuffer(&FullPathName
.ByteBuffer
);
171 SdbFreeFileAttributes(attribs
);
176 /* Add a database guid to the query result */
177 static void SdbpAddDatabaseGuid(PDB pdb
, PSDBQUERYRESULT result
)
181 for (n
= 0; n
< _countof(result
->rgGuidDB
); ++n
)
183 if (!memcmp(&result
->rgGuidDB
[n
], &pdb
->database_id
, sizeof(pdb
->database_id
)))
186 if (result
->dwCustomSDBMap
& (1<<n
))
189 memcpy(&result
->rgGuidDB
[n
], &pdb
->database_id
, sizeof(result
->rgGuidDB
[n
]));
190 result
->dwCustomSDBMap
|= (1<<n
);
195 /* Add one layer to the query result */
196 static BOOL
SdbpAddSingleLayerMatch(TAGREF layer
, PSDBQUERYRESULT result
)
200 for (n
= 0; n
< result
->dwLayerCount
; ++n
)
202 if (result
->atrLayers
[n
] == layer
)
206 if (n
>= _countof(result
->atrLayers
))
209 result
->atrLayers
[n
] = layer
;
210 result
->dwLayerCount
++;
215 /* Translate a layer name to a tagref + add it to the query result */
216 static BOOL
SdbpAddNamedLayerMatch(HSDB hsdb
, PCWSTR layerName
, PSDBQUERYRESULT result
)
218 TAGID database
, layer
;
222 database
= SdbFindFirstTag(pdb
, TAGID_ROOT
, TAG_DATABASE
);
223 if (database
== TAGID_NULL
)
226 layer
= SdbFindFirstNamedTag(pdb
, database
, TAG_LAYER
, TAG_NAME
, layerName
);
227 if (layer
== TAGID_NULL
)
230 if (!SdbTagIDToTagRef(hsdb
, pdb
, layer
, &tr
))
233 if (!SdbpAddSingleLayerMatch(tr
, result
))
236 SdbpAddDatabaseGuid(pdb
, result
);
240 /* Add all layers for the exe tag to the query result */
241 static void SdbpAddExeLayers(HSDB hsdb
, PDB pdb
, TAGID tagExe
, PSDBQUERYRESULT result
)
243 TAGID layer
= SdbFindFirstTag(pdb
, tagExe
, TAG_LAYER
);
245 while (layer
!= TAGID_NULL
)
248 TAGID layerIdTag
= SdbFindFirstTag(pdb
, layer
, TAG_LAYER_TAGID
);
249 DWORD tagId
= SdbReadDWORDTag(pdb
, layerIdTag
, TAGID_NULL
);
251 if (layerIdTag
!= TAGID_NULL
&&
252 tagId
!= TAGID_NULL
&&
253 SdbTagIDToTagRef(hsdb
, pdb
, tagId
, &tr
))
255 SdbpAddSingleLayerMatch(tr
, result
);
259 /* Try a name lookup */
260 TAGID layerTag
= SdbFindFirstTag(pdb
, layer
, TAG_NAME
);
261 if (layerTag
!= TAGID_NULL
)
263 LPCWSTR layerName
= SdbGetStringTagPtr(pdb
, layerTag
);
266 SdbpAddNamedLayerMatch(hsdb
, layerName
, result
);
271 layer
= SdbFindNextTag(pdb
, tagExe
, layer
);
275 /* Add an exe tag to the query result */
276 static void SdbpAddExeMatch(HSDB hsdb
, PDB pdb
, TAGID tagExe
, PSDBQUERYRESULT result
)
281 if (!SdbTagIDToTagRef(hsdb
, pdb
, tagExe
, &tr
))
284 for (n
= 0; n
< result
->dwExeCount
; ++n
)
286 if (result
->atrExes
[n
] == tr
)
290 if (n
>= _countof(result
->atrExes
))
293 result
->atrExes
[n
] = tr
;
294 result
->dwExeCount
++;
296 SdbpAddExeLayers(hsdb
, pdb
, tagExe
, result
);
298 SdbpAddDatabaseGuid(pdb
, result
);
301 /* Add all named layers to the query result */
302 static ULONG
SdbpAddLayerMatches(HSDB hsdb
, PWSTR pwszLayers
, DWORD pdwBytes
, PSDBQUERYRESULT result
)
304 PWSTR start
= pwszLayers
, p
;
307 const PWSTR end
= pwszLayers
+ (pdwBytes
/ sizeof(WCHAR
));
308 while (start
< end
&& (*start
== L
'!' || *start
== L
'#' || *start
== L
' ' || *start
== L
'\t'))
316 while (*start
== L
' ' || *start
== L
'\t')
319 if (*start
== UNICODE_NULL
)
321 p
= wcspbrk(start
, L
" \t");
326 if (SdbpAddNamedLayerMatch(hsdb
, start
, result
))
330 } while (start
< end
&& p
);
335 static BOOL
SdbpPropagateEnvLayers(HSDB hsdb
, LPWSTR Environment
, PSDBQUERYRESULT Result
)
337 static const UNICODE_STRING EnvKey
= RTL_CONSTANT_STRING(L
"__COMPAT_LAYER");
338 UNICODE_STRING EnvValue
;
340 WCHAR Buffer
[MAX_LAYER_LENGTH
];
342 RtlInitEmptyUnicodeString(&EnvValue
, Buffer
, sizeof(Buffer
));
344 Status
= RtlQueryEnvironmentVariable_U(Environment
, &EnvKey
, &EnvValue
);
346 if (!NT_SUCCESS(Status
))
349 return SdbpAddLayerMatches(hsdb
, Buffer
, EnvValue
.Length
, Result
) > 0;
355 * Opens specified shim database file. Handle returned by this function may only be used by
356 * functions which take HSDB param thus differing it from SdbOpenDatabase.
358 * @param [in] flags Specifies type of path or predefined database.
359 * @param [in] path Path to the shim database file.
361 * @return Success: Handle to the opened shim database, NULL otherwise.
363 HSDB WINAPI
SdbInitDatabase(DWORD flags
, LPCWSTR path
)
365 static const WCHAR shim
[] = {'\\','s','y','s','m','a','i','n','.','s','d','b',0};
366 static const WCHAR msi
[] = {'\\','m','s','i','m','a','i','n','.','s','d','b',0};
367 static const WCHAR drivers
[] = {'\\','d','r','v','m','a','i','n','.','s','d','b',0};
372 hsdb
= SdbAlloc(sizeof(SDB
));
375 hsdb
->auto_loaded
= 0;
377 /* Check for predefined databases */
378 if ((flags
& HID_DATABASE_TYPE_MASK
) && path
== NULL
)
380 switch (flags
& HID_DATABASE_TYPE_MASK
)
382 case SDB_DATABASE_MAIN_SHIM
: name
= shim
; break;
383 case SDB_DATABASE_MAIN_MSI
: name
= msi
; break;
384 case SDB_DATABASE_MAIN_DRIVERS
: name
= drivers
; break;
386 SdbReleaseDatabase(hsdb
);
389 SdbGetAppPatchDir(NULL
, buffer
, _countof(buffer
));
390 StringCchCatW(buffer
, _countof(buffer
), name
);
391 flags
= HID_DOS_PATHS
;
394 hsdb
->pdb
= SdbOpenDatabase(path
? path
: buffer
, (flags
& 0xF) - 1);
396 /* If database could not be loaded, a handle doesn't make sense either */
399 SdbReleaseDatabase(hsdb
);
407 * Closes shim database opened by SdbInitDatabase.
409 * @param [in] hsdb Handle to the shim database.
411 void WINAPI
SdbReleaseDatabase(HSDB hsdb
)
413 SdbCloseDatabase(hsdb
->pdb
);
418 * Queries database for a specified exe If hsdb is NULL default database shall be loaded and
421 * @param [in] hsdb Handle to the shim database.
422 * @param [in] path Path to executable for which we query database.
423 * @param [in] module_name Unused.
424 * @param [in] env The environment block to use
425 * @param [in] flags 0 or SDBGMEF_IGNORE_ENVIRONMENT.
426 * @param [out] result Pointer to structure in which query result shall be stored.
428 * @return TRUE if it succeeds, FALSE if it fails.
430 BOOL WINAPI
SdbGetMatchingExe(HSDB hsdb
, LPCWSTR path
, LPCWSTR module_name
,
431 LPCWSTR env
, DWORD flags
, PSDBQUERYRESULT result
)
434 TAGID database
, iter
, name
;
435 PATTRINFO attribs
= NULL
;
437 RTL_UNICODE_STRING_BUFFER DosApplicationName
= { { 0 } };
438 WCHAR DosPathBuffer
[MAX_PATH
];
441 WCHAR wszLayers
[MAX_LAYER_LENGTH
];
445 /* Load default database if one is not specified */
448 /* To reproduce windows behaviour HID_DOS_PATHS needs
449 * to be specified when loading default database */
450 hsdb
= SdbInitDatabase(HID_DOS_PATHS
| SDB_DATABASE_MAIN_SHIM
, NULL
);
452 hsdb
->auto_loaded
= TRUE
;
455 ZeroMemory(result
, sizeof(*result
));
457 /* No database could be loaded */
461 /* We do not support multiple db's yet! */
464 RtlInitUnicodeString(&DosApplicationName
.String
, path
);
465 RtlInitBuffer(&DosApplicationName
.ByteBuffer
, (PUCHAR
)DosPathBuffer
, sizeof(DosPathBuffer
));
466 if (!NT_SUCCESS(RtlEnsureBufferSize(RTL_SKIP_BUFFER_COPY
, &DosApplicationName
.ByteBuffer
, DosApplicationName
.String
.MaximumLength
)))
468 SHIM_ERR("Failed to convert allocate buffer.");
471 /* Update the internal buffer to contain the string */
472 memcpy(DosApplicationName
.ByteBuffer
.Buffer
, path
, DosApplicationName
.String
.MaximumLength
);
473 /* Make sure the string uses our internal buffer (we want to modify the buffer,
474 and RtlNtPathNameToDosPathName does not always modify the String to point to the Buffer)! */
475 DosApplicationName
.String
.Buffer
= (PWSTR
)DosApplicationName
.ByteBuffer
.Buffer
;
477 if (!NT_SUCCESS(RtlNtPathNameToDosPathName(0, &DosApplicationName
, &PathType
, NULL
)))
479 SHIM_ERR("Failed to convert %S to DOS Path.", path
);
484 /* Extract file name */
485 file_name
= wcsrchr(DosApplicationName
.String
.Buffer
, '\\');
488 SHIM_ERR("Failed to find Exe name in %wZ.", &DosApplicationName
.String
);
492 /* We will use the buffer for exe name and directory. */
493 *(file_name
++) = UNICODE_NULL
;
495 /* DATABASE is list TAG which contains all executables */
496 database
= SdbFindFirstTag(pdb
, TAGID_ROOT
, TAG_DATABASE
);
497 if (database
== TAGID_NULL
)
502 /* EXE is list TAG which contains data required to match executable */
503 iter
= SdbFindFirstTag(pdb
, database
, TAG_EXE
);
505 /* Search for entry in database, we should look into indexing tags! */
506 while (iter
!= TAGID_NULL
)
509 /* Check if exe name matches */
510 name
= SdbFindFirstTag(pdb
, iter
, TAG_NAME
);
511 /* If this is a malformed DB, (no TAG_NAME), we should not crash. */
512 foundName
= SdbGetStringTagPtr(pdb
, name
);
513 if (foundName
&& !wcsicmp(foundName
, file_name
))
515 /* Get information about executable required to match it with database entry */
518 if (!SdbGetFileAttributes(path
, &attribs
, &attr_count
))
523 /* We have a null terminator before the application name, so DosApplicationName only contains the path. */
524 if (SdbpMatchExe(pdb
, iter
, DosApplicationName
.String
.Buffer
, attribs
, attr_count
))
527 SdbpAddExeMatch(hsdb
, pdb
, iter
, result
);
531 /* Continue iterating */
532 iter
= SdbFindNextTag(pdb
, database
, iter
);
535 /* Restore the full path. */
536 *(--file_name
) = L
'\\';
538 dwSize
= sizeof(wszLayers
);
539 if (SdbGetPermLayerKeys(DosApplicationName
.String
.Buffer
, wszLayers
, &dwSize
, GPLK_MACHINE
| GPLK_USER
))
541 SdbpAddLayerMatches(hsdb
, wszLayers
, dwSize
, result
);
545 if (!(flags
& SDBGMEF_IGNORE_ENVIRONMENT
))
547 if (SdbpPropagateEnvLayers(hsdb
, (LPWSTR
)env
, result
))
550 result
->dwFlags
|= SHIMREG_HAS_ENVIRONMENT
;
555 RtlFreeBuffer(&DosApplicationName
.ByteBuffer
);
557 SdbFreeFileAttributes(attribs
);
558 if (hsdb
->auto_loaded
)
559 SdbReleaseDatabase(hsdb
);
564 * Retrieves AppPatch directory.
566 * @param [in] pdb Handle to the shim database.
567 * @param [out] path Pointer to memory in which path shall be written.
568 * @param [in] size Size of the buffer in characters.
570 HRESULT WINAPI
SdbGetAppPatchDir(HSDB hsdb
, LPWSTR path
, DWORD size
)
572 static WCHAR
* default_dir
= NULL
;
573 static CONST WCHAR szAppPatch
[] = {'\\','A','p','p','P','a','t','c','h',0};
575 /* In case function fails, path holds empty string */
583 UINT len
= GetSystemWindowsDirectoryW(NULL
, 0) + SdbpStrlen(szAppPatch
);
584 tmp
= SdbAlloc((len
+ 1)* sizeof(WCHAR
));
587 UINT r
= GetSystemWindowsDirectoryW(tmp
, len
+1);
590 hr
= StringCchCatW(tmp
, len
+1, szAppPatch
);
593 if (InterlockedCompareExchangePointer((void**)&default_dir
, tmp
, NULL
) == NULL
)
602 SHIM_ERR("Unable to obtain default AppPatch directory (0x%x)\n", hr
);
609 return StringCchCopyW(path
, size
, default_dir
);
613 SHIM_ERR("Unimplemented for hsdb != NULL\n");
620 * Translates the given trWhich to a specific database / tagid
622 * @param [in] hsdb Handle to the database.
623 * @param [in] trWhich Tagref to find
624 * @param [out,opt] ppdb The Shim database that trWhich belongs to.
625 * @param [out,opt] ptiWhich The tagid that trWhich corresponds to.
627 * @return TRUE if it succeeds, FALSE if it fails.
629 BOOL WINAPI
SdbTagRefToTagID(HSDB hsdb
, TAGREF trWhich
, PDB
* ppdb
, TAGID
* ptiWhich
)
631 if (trWhich
& 0xf0000000)
633 SHIM_ERR("Multiple shim databases not yet implemented!\n");
637 *ptiWhich
= TAG_NULL
;
641 /* There seems to be no range checking on trWhich.. */
645 *ptiWhich
= trWhich
& 0x0fffffff;
651 * Translates the given trWhich to a specific database / tagid
653 * @param [in] hsdb Handle to the database.
654 * @param [in] pdb The Shim database that tiWhich belongs to.
655 * @param [in] tiWhich Path to executable for which we query database.
656 * @param [out,opt] ptrWhich The tagid that tiWhich corresponds to.
658 * @return TRUE if it succeeds, FALSE if it fails.
660 BOOL WINAPI
SdbTagIDToTagRef(HSDB hsdb
, PDB pdb
, TAGID tiWhich
, TAGREF
* ptrWhich
)
662 if (pdb
!= hsdb
->pdb
)
664 SHIM_ERR("Multiple shim databases not yet implemented!\n");
666 *ptrWhich
= TAGREF_NULL
;
671 *ptrWhich
= tiWhich
& 0x0fffffff;
677 /* Convert a query result to shim data that will be loaded in the child process */
678 BOOL WINAPI
SdbPackAppCompatData(HSDB hsdb
, PSDBQUERYRESULT pQueryResult
, PVOID
* ppData
, DWORD
*pdwSize
)
684 if (!pQueryResult
|| !ppData
|| !pdwSize
)
686 SHIM_WARN("Invalid params: %p, %p, %p\n", pQueryResult
, ppData
, pdwSize
);
690 pData
= RtlAllocateHeap(RtlGetProcessHeap(), HEAP_ZERO_MEMORY
, sizeof(ShimData
));
693 SHIM_WARN("Unable to allocate %d bytes\n", sizeof(ShimData
));
697 GetSystemWindowsDirectoryW(pData
->szModule
, _countof(pData
->szModule
));
698 hr
= StringCchCatW(pData
->szModule
, _countof(pData
->szModule
), L
"\\system32\\apphelp.dll");
701 SHIM_ERR("Unable to append module name (0x%x)\n", hr
);
702 RtlFreeHeap(RtlGetProcessHeap(), 0, pData
);
706 pData
->dwSize
= sizeof(*pData
);
707 pData
->dwMagic
= SHIMDATA_MAGIC
;
708 pData
->Query
= *pQueryResult
;
710 pData
->szLayer
[0] = UNICODE_NULL
; /* TODO */
712 SHIM_INFO("\ndwFlags 0x%x\ndwMagic 0x%x\ntrExe 0x%x\ntrLayer 0x%x\n",
713 pData
->Query
.dwFlags
, pData
->dwMagic
, pData
->Query
.atrExes
[0], pData
->Query
.atrLayers
[0]);
716 /* 0x0 {GUID} NAME */
718 for (n
= 0; n
< pQueryResult
->dwLayerCount
; ++n
)
720 SHIM_INFO("Layer 0x%x\n", pQueryResult
->atrLayers
[n
]);
724 *pdwSize
= pData
->dwSize
;
729 BOOL WINAPI
SdbUnpackAppCompatData(HSDB hsdb
, LPCWSTR pszImageName
, PVOID pData
, PSDBQUERYRESULT pQueryResult
)
731 ShimData
* pShimData
= pData
;
733 if (!pShimData
|| pShimData
->dwMagic
!= SHIMDATA_MAGIC
|| pShimData
->dwSize
< sizeof(ShimData
))
741 *pQueryResult
= pShimData
->Query
;
745 DWORD WINAPI
SdbGetAppCompatDataSize(ShimData
* pData
)
747 if (!pData
|| pData
->dwMagic
!= SHIMDATA_MAGIC
)
751 return pData
->dwSize
;