Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions build/CopyFilesToStagingDir.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ PublishFile $FullBuildOutput\WindowsAppRuntime_UniversalBGTaskDLL\Microsoft.Wind
# Common Auto-Initializer Files
PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\WindowsAppRuntimeAutoInitializer.cpp $NugetDir\include
PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\WindowsAppRuntimeAutoInitializer.cs $NugetDir\include
PublishFile $FullBuildOutput\WindowsAppRuntime_DLL\WindowsAppRuntimeBaseDirectoryAutoInitializer.cs $NugetDir\include
#
# Bootstrap Auto-Initializer Files
PublishFile $FullBuildOutput\WindowsAppRuntime_BootstrapDLL\MddBootstrapAutoInitializer.cpp $NugetDir\include
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,18 @@
<DefineConstants Condition="'$(WindowsAppSdkBootstrapInitialize)'=='true'">$(DefineConstants);MICROSOFT_WINDOWSAPPSDK_AUTOINITIALIZE_BOOTSTRAP</DefineConstants>
<DefineConstants Condition="'$(WindowsAppSdkDeploymentManagerInitialize)'=='true'">$(DefineConstants);MICROSOFT_WINDOWSAPPSDK_AUTOINITIALIZE_DEPLOYMENTMANAGER</DefineConstants>
<DefineConstants Condition="'$(WindowsAppSdkUndockedRegFreeWinRTInitialize)'=='true'">$(DefineConstants);MICROSOFT_WINDOWSAPPSDK_AUTOINITIALIZE_UNDOCKEDREGFREEWINRT</DefineConstants>
<!-- The resource base directory (%MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY%, used by the app
manifest's SxS DLL redirection and by MRTCore) is published for self-contained apps. It shares
the self-contained trigger with undocked reg-free WinRT initialization. See issue #5987. -->
<DefineConstants Condition="'$(WindowsAppSdkUndockedRegFreeWinRTInitialize)'=='true'">$(DefineConstants);MICROSOFT_WINDOWSAPPSDK_AUTOINITIALIZE_BASEDIRECTORY</DefineConstants>
<DefineConstants Condition="'$(WindowsAppSdkCompatibilityInitialize)'=='true'">$(DefineConstants);MICROSOFT_WINDOWSAPPSDK_AUTOINITIALIZE_COMPATIBILITY</DefineConstants>
</PropertyGroup>

<!-- "BeforeCompile" is used here to ensure this happens at the same time as possible codegen from WindowsAppSdkCompatibilitySetterTarget -->
<Target Name="WindowsAppRuntimeAutoInitializer" BeforeTargets="BeforeCompile">
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)..\include\WindowsAppRuntimeAutoInitializer.cs" />
<Compile Condition="'$(WindowsAppSdkUndockedRegFreeWinRTInitialize)'=='true'" Include="$(MSBuildThisFileDirectory)..\include\WindowsAppRuntimeBaseDirectoryAutoInitializer.cs" />
</ItemGroup>
</Target>

Expand Down
1 change: 1 addition & 0 deletions dev/Common/Common.vcxitems
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,6 @@
<ItemGroup>
<PublicHeaders Include="$(MSBuildThisFileDirectory)WindowsAppRuntimeAutoInitializer.cs" />
<PublicHeaders Include="$(MSBuildThisFileDirectory)WindowsAppRuntimeAutoInitializer.cpp" />
<PublicHeaders Include="$(MSBuildThisFileDirectory)WindowsAppRuntimeBaseDirectoryAutoInitializer.cs" />
</ItemGroup>
</Project>
6 changes: 6 additions & 0 deletions dev/Common/WindowsAppRuntimeAutoInitializer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 35 additions & 0 deletions dev/Common/WindowsAppRuntimeBaseDirectoryAutoInitializer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 29 additions & 1 deletion dev/MRTCore/mrt/Core/src/MRM.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

#include <memory>
#include <string>
#include <cstdlib>

using namespace Microsoft::Resources;

Expand Down Expand Up @@ -950,6 +951,26 @@ STDAPI_(void) MrmFreeResource(_In_opt_ void* resource)
return;
}

// The base directory is communicated via the MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY process
// environment variable, which is inherited by child processes spawned via CreateProcess. Its owner
// also stamps its process id in MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY_PID. Honor the base
// directory only when that stamp matches the current process; otherwise it was inherited from a
// parent and must be ignored (a child would otherwise resolve resources from the parent's directory).
// See https://github.com/microsoft/WindowsAppSDK/issues/5987.
static bool IsBaseDirectoryStampedByCurrentProcess()
{
wchar_t stampedPidText[16]{};
const DWORD length{ ::GetEnvironmentVariableW(
L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY_PID", stampedPidText, ARRAYSIZE(stampedPidText)) };
if ((length == 0) || (length >= ARRAYSIZE(stampedPidText)))
{
// Not stamped (absent) or unexpectedly long: do not honor the base directory.
return false;
}

return static_cast<DWORD>(wcstoul(stampedPidText, nullptr, 10)) == ::GetCurrentProcessId();
}

// When filename is provided, append filename to current module path. If the file doesn't exist, it will
// append the filename to parent path. If none exists, file in current module
// path will be returned.
Expand Down Expand Up @@ -1003,7 +1024,14 @@ STDAPI MrmGetFilePathFromName(_In_opt_ PCWSTR filename, _Outptr_ PWSTR* filePath
if (filename == nullptr || *filename == L'\0')
{
searchStart = SearchPass::exeDirForResourcesPri;
if (SUCCEEDED(wil::TryGetEnvironmentVariableW(L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY", baseDir)) && baseDir)
// Honor MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY only when it was stamped by the current
// process. It is a process environment variable (inherited across CreateProcess), so without
// this guard a child would load the parent's resources.pri from the parent's base directory.
// When the stamp is foreign or absent, leave baseDir empty and fall back to the module (exe)
// directory (handled by the passes below and DefaultFallback).
// See https://github.com/microsoft/WindowsAppSDK/issues/5987.
if (IsBaseDirectoryStampedByCurrentProcess() &&
SUCCEEDED(wil::TryGetEnvironmentVariableW(L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY", baseDir)) && baseDir)
{
searchStart = SearchPass::BaseDirForResourcesPri;
RETURN_IF_FAILED(StringCchLengthW(baseDir.get(), STRSAFE_MAX_CCH, &baseDirCount));
Expand Down
222 changes: 222 additions & 0 deletions dev/MRTCore/mrt/Core/unittests/MrmTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
#include <WexTestClass.h>
#include "..\src\MRM.h"

#include <string>
#include <stdlib.h>

using namespace WEX::Common;
using namespace WEX::TestExecution;
using namespace WEX::Logging;
Expand Down Expand Up @@ -725,4 +728,223 @@ class BasicTest

wchar_t previousWorkingDirectory[MAX_PATH];
};

// Regression tests for https://github.com/microsoft/WindowsAppSDK/issues/5987.
//
// MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY is a process environment variable set by the Windows App
// SDK auto-initializer (for PublishSingleFile SxS redirection). Because it is a process environment
// variable it is inherited by child processes spawned via CreateProcess. To keep a child from loading
// the parent's resources.pri, the auto-initializer also stamps MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY_PID
// with the owning process id, and MrmGetFilePathFromName honors the base directory only when that stamp
// matches the current process.
class EnvironmentVariableIsolationTests
{
public:
TEST_CLASS(EnvironmentVariableIsolationTests);

// In-process guard: the base directory is honored only when its PID stamp matches this process.
TEST_METHOD(GetFilePath_HonorsBaseDirectoryOnlyWhenStampedByCurrentProcess)
{
const std::wstring baseDir{ CreateTempDirWithResourcesPri() };
// AppContext.BaseDirectory (the real setter's value) ends with a directory separator, and
// MrmGetFilePathFromName's buffer sizing relies on that, so mimic it here.
const std::wstring baseDirWithSeparator{ baseDir + L"\\" };
const std::wstring moduleDir{ GetCurrentProcessModuleDirectory() };

VERIFY_WIN32_BOOL_SUCCEEDED(SetEnvironmentVariableW(
L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY", baseDirWithSeparator.c_str()));

wchar_t* path{};

// Stamped by the current process: the base directory is honored.
SetBaseDirectoryPid(GetCurrentProcessId());
VERIFY_ARE_EQUAL(S_OK, MrmGetFilePathFromName(nullptr, &path));
VERIFY_IS_TRUE(IsUnderDirectory(path, baseDirWithSeparator),
String().Format(L"Expected a path under the base directory, got '%s'.", path));
MrmFreeResource(path);
path = nullptr;

// Stamped by a foreign process (as when inherited across CreateProcess): the base directory is
// ignored and the module (exe) directory is used instead.
SetBaseDirectoryPid(GetCurrentProcessId() ^ 0x1);
VERIFY_ARE_EQUAL(S_OK, MrmGetFilePathFromName(nullptr, &path));
VERIFY_IS_FALSE(IsUnderDirectory(path, baseDirWithSeparator),
String().Format(L"Expected the inherited base directory to be ignored, got '%s'.", path));
VERIFY_IS_TRUE(IsUnderDirectory(path, moduleDir),
String().Format(L"Expected a path under the module directory, got '%s'.", path));
MrmFreeResource(path);
path = nullptr;

// No stamp at all: the base directory is ignored.
VERIFY_WIN32_BOOL_SUCCEEDED(SetEnvironmentVariableW(
L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY_PID", nullptr));
VERIFY_ARE_EQUAL(S_OK, MrmGetFilePathFromName(nullptr, &path));
VERIFY_IS_FALSE(IsUnderDirectory(path, baseDirWithSeparator),
String().Format(L"Expected an unstamped base directory to be ignored, got '%s'.", path));
MrmFreeResource(path);
path = nullptr;

SetEnvironmentVariableW(L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY", nullptr);
SetEnvironmentVariableW(L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY_PID", nullptr);
RemoveTempDirectory(baseDir);
}

// End-to-end insulation: a real child process must ignore the inherited base directory. This
// reproduces the reported scenario where one Windows App SDK app launches another via CreateProcess.
TEST_METHOD(ChildProcessIsInsulatedFromInheritedBaseDirectory)
{
const std::wstring baseDir{ CreateTempDirWithResourcesPri() };
const std::wstring baseDirWithSeparator{ baseDir + L"\\" };

// Configure the environment exactly as the setter does for this (parent) process, then spawn a
// child that inherits it. The child's process id differs from this stamp, so it must not honor
// the base directory.
VERIFY_WIN32_BOOL_SUCCEEDED(SetEnvironmentVariableW(
L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY", baseDirWithSeparator.c_str()));
SetBaseDirectoryPid(GetCurrentProcessId());
VERIFY_WIN32_BOOL_SUCCEEDED(SetEnvironmentVariableW(L"MRM_TEST_CHILD_WORKER", L"1"));

const std::wstring commandLine{ BuildChildWorkerCommandLine() };
Log::Comment(String().Format(L"Spawning child: %s", commandLine.c_str()));

std::wstring mutableCommandLine{ commandLine };
STARTUPINFOW startupInfo{};
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInfo{};
const BOOL created{ CreateProcessW(nullptr, mutableCommandLine.data(), nullptr, nullptr,
/*bInheritHandles*/ FALSE, /*dwCreationFlags*/ 0, /*lpEnvironment*/ nullptr,
/*lpCurrentDirectory*/ nullptr, &startupInfo, &processInfo) };

// Clear the environment before asserting so it never leaks into sibling tests.
SetEnvironmentVariableW(L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY", nullptr);
SetEnvironmentVariableW(L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY_PID", nullptr);
SetEnvironmentVariableW(L"MRM_TEST_CHILD_WORKER", nullptr);

VERIFY_WIN32_BOOL_SUCCEEDED(created);
VERIFY_ARE_EQUAL(WAIT_OBJECT_0, WaitForSingleObject(processInfo.hProcess, 60 * 1000));

DWORD exitCode{ MAXDWORD };
VERIFY_WIN32_BOOL_SUCCEEDED(GetExitCodeProcess(processInfo.hProcess, &exitCode));
CloseHandle(processInfo.hThread);
CloseHandle(processInfo.hProcess);
RemoveTempDirectory(baseDir);

// The child runs only ChildProcessInsulationWorker; a zero exit code means it passed (i.e. it
// ignored the inherited base directory and resolved resources under its own module directory).
VERIFY_ARE_EQUAL(0u, exitCode,
String().Format(L"Child insulation worker exit code: %u (0 == insulated).", exitCode));
}

// Runs only inside the child spawned by ChildProcessIsInsulatedFromInheritedBaseDirectory (gated on
// the MRM_TEST_CHILD_WORKER sentinel). It is skipped during a normal test pass.
TEST_METHOD(ChildProcessInsulationWorker)
{
wchar_t sentinel[8]{};
if ((GetEnvironmentVariableW(L"MRM_TEST_CHILD_WORKER", sentinel, ARRAYSIZE(sentinel)) == 0) ||
(wcscmp(sentinel, L"1") != 0))
{
Log::Comment(L"Skipping: this worker runs only when spawned by the parent insulation test.");
Log::Result(TestResults::Skipped);
return;
}

// This process inherited MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY (and its foreign PID stamp)
// from the parent. Confirm MRTCore does not resolve resources under that inherited directory.
wchar_t inheritedBaseDir[MAX_PATH]{};
GetEnvironmentVariableW(L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY",
inheritedBaseDir, ARRAYSIZE(inheritedBaseDir));
const std::wstring moduleDir{ GetCurrentProcessModuleDirectory() };

wchar_t* path{};
VERIFY_ARE_EQUAL(S_OK, MrmGetFilePathFromName(nullptr, &path));
Log::Comment(String().Format(
L"Child resolved '%s' (inherited base directory '%s', module directory '%s').",
path, inheritedBaseDir, moduleDir.c_str()));

VERIFY_IS_TRUE(IsUnderDirectory(path, moduleDir),
String().Format(L"Child was not insulated: '%s' is not under its module directory.", path));
if (inheritedBaseDir[0] != L'\0')
{
VERIFY_IS_FALSE(IsUnderDirectory(path, inheritedBaseDir),
String().Format(L"Child was not insulated: '%s' is under the inherited base directory.", path));
}
MrmFreeResource(path);
}

private:
static void SetBaseDirectoryPid(DWORD pid)
{
wchar_t pidText[16]{};
VERIFY_ARE_EQUAL(0, _ultow_s(pid, pidText, ARRAYSIZE(pidText), 10));
VERIFY_WIN32_BOOL_SUCCEEDED(SetEnvironmentVariableW(
L"MICROSOFT_WINDOWSAPPRUNTIME_BASE_DIRECTORY_PID", pidText));
}

static bool IsUnderDirectory(PCWSTR path, const std::wstring& directoryWithSeparator)
{
return (directoryWithSeparator.size() > 0) &&
(_wcsnicmp(path, directoryWithSeparator.c_str(), directoryWithSeparator.size()) == 0);
}

static std::wstring GetCurrentProcessModuleDirectory()
{
wchar_t modulePath[MAX_PATH]{};
VERIFY_ARE_NOT_EQUAL(0u, GetModuleFileNameW(nullptr, modulePath, ARRAYSIZE(modulePath)));
std::wstring directory{ modulePath };
directory.resize(directory.find_last_of(L'\\') + 1); // keep the trailing separator
return directory;
}

static std::wstring CreateTempDirWithResourcesPri()
{
wchar_t tempPath[MAX_PATH]{};
const DWORD tempLength{ GetTempPathW(ARRAYSIZE(tempPath), tempPath) };
VERIFY_IS_TRUE((tempLength > 0) && (tempLength < ARRAYSIZE(tempPath)));

const std::wstring directory{ std::wstring(tempPath) + L"MrmBaseDirTest_" +
std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(GetTickCount64()) };
VERIFY_IS_TRUE(CreateDirectoryW(directory.c_str(), nullptr) ||
(GetLastError() == ERROR_ALREADY_EXISTS));

const std::wstring resourcesPri{ directory + L"\\resources.pri" };
const HANDLE file{ CreateFileW(resourcesPri.c_str(), GENERIC_WRITE, 0, nullptr,
CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr) };
VERIFY_ARE_NOT_EQUAL(INVALID_HANDLE_VALUE, file);
CloseHandle(file);
return directory;
}

static void RemoveTempDirectory(const std::wstring& directory)
{
DeleteFileW((directory + L"\\resources.pri").c_str());
RemoveDirectoryW(directory.c_str());
}

static std::wstring BuildChildWorkerCommandLine()
{
// Prefer the TAEF console runner (te.exe) sitting next to whatever process is hosting this test
// (te.exe or TE.ProcessHost.exe); fall back to the current host if it isn't found.
wchar_t hostPath[MAX_PATH]{};
VERIFY_ARE_NOT_EQUAL(0u, GetModuleFileNameW(nullptr, hostPath, ARRAYSIZE(hostPath)));
const std::wstring hostDirectory{ GetCurrentProcessModuleDirectory() };
std::wstring runnerPath{ hostDirectory + L"te.exe" };
if (GetFileAttributesW(runnerPath.c_str()) == INVALID_FILE_ATTRIBUTES)
{
runnerPath = hostPath;
}

// Resolve this test binary's own path so the child loads the same DLL.
HMODULE selfModule{};
VERIFY_WIN32_BOOL_SUCCEEDED(GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
reinterpret_cast<LPCWSTR>(&EnvironmentVariableIsolationTests::BuildChildWorkerCommandLine),
&selfModule));
wchar_t selfPath[MAX_PATH]{};
VERIFY_ARE_NOT_EQUAL(0u, GetModuleFileNameW(selfModule, selfPath, ARRAYSIZE(selfPath)));

// Run only the worker, in-process, so the child's module identity is the runner.
return L"\"" + runnerPath + L"\" \"" + std::wstring(selfPath) +
L"\" /inproc /name:*ChildProcessInsulationWorker";
}
};
} // namespace UnitTest
Loading
Loading