#include <windows.h>
#include <stdint.h>
#include <algorithm>
#include <vector>
#include "base/base_paths.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/files/memory_mapped_file.h"
#include "base/functional/bind.h"
#include "base/path_service.h"
#include "base/strings/pattern.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/test/launcher/test_launcher.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "base/test/test_suite.h"
#include "base/win/pe_image.h"
#include "build/branding_buildflags.h"
#include "build/build_config.h"
#include "chrome/install_static/test/scoped_install_details.h"
#include "mojo/buildflags.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest-spi.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
using DetailedImports = std::map<std::string, std::set<std::string>>;
using SupportedApiSets = std::map<std::string, size_t>;
const DetailedImports kAvailableImports = {
#include "chrome/test/delayload/supported_imports.inc"
};
const SupportedApiSets kSupportedApiSets = {
#include "chrome/test/delayload/supported_apisets_10.0.10240.inc"
};
class DelayloadsTest : public testing::Test {
protected:
static bool ImportsCallback(const base::win::PEImage& image,
LPCSTR module,
PIMAGE_THUNK_DATA name_table,
PIMAGE_THUNK_DATA iat,
PVOID cookie) {
std::vector<std::string>* import_list =
reinterpret_cast<std::vector<std::string>*>(cookie);
import_list->push_back(module);
return true;
}
static std::vector<std::string> GetImports(
const base::FilePath& module_path) {
std::vector<std::string> imports;
base::MemoryMappedFile module_mmap;
CHECK(module_mmap.Initialize(module_path));
base::win::PEImageAsData pe_image_data(
reinterpret_cast<HMODULE>(const_cast<uint8_t*>(module_mmap.data())));
pe_image_data.EnumImportChunks(DelayloadsTest::ImportsCallback, &imports,
nullptr);
return imports;
}
};
class MinimumWindowsSupportTest : public DelayloadsTest {
protected:
void SetExtraAllowedImports(std::set<std::string> internal_modules) {
modules_ = internal_modules;
}
void Validate(const std::wstring& module) {
base::FilePath module_path;
ASSERT_TRUE(base::PathService::Get(base::DIR_EXE, &module_path));
ValidateImportsForEarliestWindowsVersion(module_path.Append(module),
modules_);
}
static bool SupportedApiSet(const std::string& import) {
if (!base::StartsWith(import, "api-") || !base::EndsWith(import, ".dll")) {
return false;
}
if (std::ranges::count(import, '-') < 5) {
return false;
}
const size_t last_dash = import.rfind("-");
const size_t dot = import.rfind(".");
size_t requested_version = 0;
const auto requested_version_str =
import.substr(last_dash + 1, dot - last_dash - 1);
if (!base::StringToSizeT(requested_version_str, &requested_version)) {
return false;
}
const auto requested_api = import.substr(0, last_dash);
const auto api_to_max_ver = kSupportedApiSets.find(requested_api);
if (api_to_max_ver == kSupportedApiSets.end()) {
return false;
}
return requested_version <= api_to_max_ver->second;
}
static bool DetailedImportsCallback(const base::win::PEImage& image,
const char* module,
DWORD ordinal,
const char* import_name,
DWORD hint,
IMAGE_THUNK_DATA* iat,
void* cookie) {
if (!module) {
return false;
}
if (!import_name) {
return true;
}
const std::string mod_str = base::ToLowerASCII(module);
DetailedImports* imports = reinterpret_cast<DetailedImports*>(cookie);
if (auto fn_names = imports->find(mod_str); fn_names != imports->end()) {
fn_names->second.emplace(import_name);
} else {
std::set<std::string> empty_fn_names;
empty_fn_names.emplace(import_name);
imports->emplace(std::move(mod_str), std::move(empty_fn_names));
}
return true;
}
static DetailedImports GetDetailedImports(const base::FilePath& module_path) {
base::MemoryMappedFile module_mmap;
DetailedImports imports;
CHECK(module_mmap.Initialize(module_path));
base::win::PEImageAsData pe_image_data(
reinterpret_cast<HMODULE>(const_cast<uint8_t*>(module_mmap.data())));
pe_image_data.EnumAllImports(
MinimumWindowsSupportTest::DetailedImportsCallback, &imports, nullptr);
return imports;
}
static void AreImportsOk(DetailedImports& imports,
const std::set<std::string>& extra_imports) {
for (const auto& imports_entry : imports) {
const std::string& module = imports_entry.first;
auto available_functions = kAvailableImports.find(module);
if (available_functions == kAvailableImports.end()) {
if (!SupportedApiSet(module)) {
EXPECT_THAT(extra_imports, testing::Contains(module));
}
} else {
for (const auto& function : imports_entry.second) {
EXPECT_THAT(available_functions->second, testing::Contains(function));
}
}
}
}
static void ValidateImportsForEarliestWindowsVersion(
const base::FilePath& mod_path,
const std::set<std::string>& extra_imports) {
DetailedImports imports = GetDetailedImports(mod_path);
AreImportsOk(imports, extra_imports);
}
std::set<std::string> modules_;
};
#if defined(NDEBUG) && !defined(COMPONENT_BUILD)
TEST_F(DelayloadsTest, ChromeDllDelayloadsCheck) {
base::FilePath dll;
ASSERT_TRUE(base::PathService::Get(base::DIR_EXE, &dll));
dll = dll.Append(L"chrome.dll");
std::vector<std::string> dll_imports = GetImports(dll);
ASSERT_LT(0u, dll_imports.size())
<< "Ensure the delayloads_unittests "
"target was built, instead of delayloads_unittests.exe";
static const char* const kValidFilePatterns[] = {
"KERNEL32.dll",
"chrome_elf.dll",
"DWrite.dll",
"CRYPT32.dll",
"dhcpcsvc.DLL",
"IPHLPAPI.DLL",
"ntdll.dll",
"Secur32.dll",
"USERENV.dll",
"WINHTTP.dll",
"WINMM.dll",
"WINSPOOL.DRV",
"WINTRUST.dll",
"WS2_32.dll",
"VERSION.dll",
#if defined(ADDRESS_SANITIZER)
"clang_rt.asan_dynamic-x86_64.dll",
#endif
};
for (const std::string& dll_import : dll_imports) {
bool match = false;
for (const char* kValidFilePattern : kValidFilePatterns) {
if (base::MatchPattern(dll_import, kValidFilePattern)) {
match = true;
break;
}
}
EXPECT_TRUE(match) << "Illegal import in chrome.dll: " << dll_import;
}
}
#if defined(ADDRESS_SANITIZER)
#define MAYBE_ChromeDllLoadSanityTest DISABLED_ChromeDllLoadSanityTest
#else
#define MAYBE_ChromeDllLoadSanityTest ChromeDllLoadSanityTest
#endif
TEST_F(DelayloadsTest, MAYBE_ChromeDllLoadSanityTest) {
base::CommandLine new_test =
base::CommandLine(base::CommandLine::ForCurrentProcess()->GetProgram());
new_test.AppendSwitchASCII(
base::kGTestFilterFlag,
"DelayloadsTest.DISABLED_ChromeDllLoadSanityTestImpl");
new_test.AppendSwitch("gtest_also_run_disabled_tests");
new_test.AppendSwitch("single-process-tests");
std::string output;
ASSERT_TRUE(base::GetAppOutput(new_test, &output));
std::string crash_string =
"OK ] DelayloadsTest.DISABLED_ChromeDllLoadSanityTestImpl";
if (output.find(crash_string) == std::string::npos) {
GTEST_FAIL() << "Couldn't find\n"
<< crash_string << "\n in output\n " << output;
}
}
TEST_F(DelayloadsTest, DISABLED_ChromeDllLoadSanityTestImpl) {
base::FilePath dll;
ASSERT_TRUE(base::PathService::Get(base::DIR_EXE, &dll));
dll = dll.Append(L"chrome.dll");
ASSERT_EQ(nullptr, ::GetModuleHandle(L"user32.dll"));
HMODULE chrome_module_handle = ::LoadLibrary(dll.value().c_str());
ASSERT_TRUE(chrome_module_handle != nullptr);
EXPECT_EQ(nullptr, ::GetModuleHandle(L"user32.dll"));
}
TEST_F(DelayloadsTest, ChromeElfDllDelayloadsCheck) {
base::FilePath dll;
ASSERT_TRUE(base::PathService::Get(base::DIR_EXE, &dll));
dll = dll.Append(L"chrome_elf.dll");
std::vector<std::string> dll_imports = GetImports(dll);
ASSERT_LT(0u, dll_imports.size())
<< "Ensure the delayloads_unittests "
"target was built, instead of delayloads_unittests.exe";
static const char* const kValidFilePatterns[] = {
"KERNEL32.dll",
"ntdll.dll",
"VERSION.dll",
#if defined(ADDRESS_SANITIZER)
"clang_rt.asan_dynamic-x86_64.dll",
#endif
};
for (const std::string& dll_import : dll_imports) {
bool match = false;
for (const char* kValidFilePattern : kValidFilePatterns) {
if (base::MatchPattern(dll_import, kValidFilePattern)) {
match = true;
break;
}
}
ASSERT_TRUE(match) << "Illegal import in chrome_elf.dll: " << dll_import;
}
}
TEST_F(DelayloadsTest, ChromeElfDllLoadSanityTest) {
base::CommandLine new_test =
base::CommandLine(base::CommandLine::ForCurrentProcess()->GetProgram());
new_test.AppendSwitchASCII(
base::kGTestFilterFlag,
"DelayloadsTest.DISABLED_ChromeElfDllLoadSanityTestImpl");
new_test.AppendSwitchASCII("type", "crashpad-handler");
new_test.AppendSwitch("gtest_also_run_disabled_tests");
new_test.AppendSwitch("single-process-tests");
std::string output;
ASSERT_TRUE(base::GetAppOutput(new_test, &output));
std::string crash_string =
"OK ] DelayloadsTest.DISABLED_ChromeElfDllLoadSanityTestImpl";
if (output.find(crash_string) == std::string::npos) {
GTEST_FAIL() << "Couldn't find\n"
<< crash_string << "\n in output\n " << output;
}
}
TEST_F(DelayloadsTest, DISABLED_ChromeElfDllLoadSanityTestImpl) {
base::FilePath dll;
ASSERT_TRUE(base::PathService::Get(base::DIR_EXE, &dll));
dll = dll.Append(L"chrome_elf.dll");
ASSERT_EQ(nullptr, ::GetModuleHandle(L"user32.dll"));
HMODULE chrome_elf_module_handle = ::LoadLibrary(dll.value().c_str());
ASSERT_TRUE(chrome_elf_module_handle != nullptr);
EXPECT_EQ(nullptr, ::GetModuleHandle(L"user32.dll"));
EXPECT_TRUE(::FreeLibrary(chrome_elf_module_handle));
}
TEST_F(DelayloadsTest, ChromeExeDelayloadsCheck) {
base::FilePath exe;
ASSERT_TRUE(base::PathService::Get(base::DIR_EXE, &exe));
exe = exe.Append(L"chrome.exe");
std::vector<std::string> exe_imports = GetImports(exe);
ASSERT_LT(0u, exe_imports.size())
<< "Ensure the delayloads_unittests "
"target was built, instead of delayloads_unittests.exe";
static const char* const kValidFilePatterns[] = {
"KERNEL32.dll",
"ntdll.dll",
"chrome_elf.dll",
"VERSION.dll",
#if defined(ADDRESS_SANITIZER)
"clang_rt.asan_dynamic-x86_64.dll",
"api-ms-win-core-synch-l1-2-0.dll",
#endif
};
for (const std::string& exe_import : exe_imports) {
bool match = false;
for (const char* kValidFilePattern : kValidFilePatterns) {
if (base::MatchPattern(exe_import, kValidFilePattern)) {
match = true;
break;
}
}
EXPECT_TRUE(match) << "Illegal import in chrome.exe: " << exe_import;
}
}
TEST_F(MinimumWindowsSupportTest, ChromeElf) {
#if defined(ADDRESS_SANITIZER)
SetExtraAllowedImports({"clang_rt.asan_dynamic-x86_64.dll"});
#endif
Validate(L"chrome_elf.dll");
}
TEST_F(MinimumWindowsSupportTest, ChromeWer) {
#if defined(ADDRESS_SANITIZER)
SetExtraAllowedImports({"clang_rt.asan_dynamic-x86_64.dll"});
#endif
Validate(L"chrome_wer.dll");
}
TEST_F(MinimumWindowsSupportTest, ChromeExe) {
SetExtraAllowedImports({
"chrome_elf.dll",
#if defined(ADDRESS_SANITIZER)
"clang_rt.asan_dynamic-x86_64.dll",
#endif
});
Validate(L"chrome.exe");
}
TEST_F(MinimumWindowsSupportTest, ChromeDll) {
SetExtraAllowedImports({
"chrome_elf.dll",
#if defined(ADDRESS_SANITIZER)
"clang_rt.asan_dynamic-x86_64.dll",
#endif
});
Validate(L"chrome.dll");
}
TEST_F(MinimumWindowsSupportTest, ChromeExtraDlls) {
#if defined(ADDRESS_SANITIZER)
SetExtraAllowedImports({"clang_rt.asan_dynamic-x86_64.dll"});
#endif
std::vector<std::wstring> extra_dlls = {
L"d3dcompiler_47.dll",
#if !defined(ARCH_CPU_ARM64)
L"dxcompiler.dll", L"dxil.dll",
#endif
L"vk_swiftshader.dll", L"vulkan-1.dll"};
for (const auto& dll : extra_dlls) {
Validate(dll);
}
}
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
TEST_F(MinimumWindowsSupportTest, ChromeOptimizationGuide) {
Validate(L"optimization_guide_internal.dll");
}
#endif
#endif
TEST_F(DelayloadsTest, ChromeExeLoadSanityCheck) {
base::FilePath exe;
ASSERT_TRUE(base::PathService::Get(base::DIR_EXE, &exe));
exe = exe.Append(L"chrome.exe");
std::vector<std::string> exe_imports = GetImports(exe);
ASSERT_LT(0u, exe_imports.size())
<< "Ensure the delayloads_unittests "
"target was built, instead of delayloads_unittests.exe";
EXPECT_EQ("chrome_elf.dll", exe_imports[0])
<< "Illegal import order in chrome.exe (ensure the "
"delayloads_unittests "
"target was built, instead of just delayloads_unittests.exe)";
}
TEST_F(MinimumWindowsSupportTest, ValidateImportChecker) {
DetailedImports expected_ok = {{"ntdll.dll", {"DbgPrint"}}};
AreImportsOk(expected_ok, {});
DetailedImports expected_missing = {
{"kernel32.dll", {"IsEnclaveTypeSupported"}}};
EXPECT_NONFATAL_FAILURE(AreImportsOk(expected_missing, {}), "");
}
TEST_F(MinimumWindowsSupportTest, ValidateApisetChecker) {
ASSERT_TRUE(SupportedApiSet("api-ms-win-core-synch-l1-2-0.dll"));
ASSERT_FALSE(SupportedApiSet("api-ms-win-core-synch-l1-2-2.dll"));
ASSERT_FALSE(SupportedApiSet("api-ms-win-core-synch-l1-3-0.dll"));
}
}
int main(int argc, char** argv) {
base::CommandLine::InitUsingArgvForTesting(argc, argv);
install_static::ScopedInstallDetails scoped_install_details;
base::TestSuite test_suite(argc, argv);
return base::LaunchUnitTests(
argc, argv,
base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite)));
}