.clang-format: add InsertBraces: true and minor fix to FormatSource.ps1

This commit is contained in:
Ben Hillis 2025-11-12 13:37:33 -08:00
parent b2c28b92fe
commit fe3d2f5472
16 changed files with 130 additions and 30 deletions

View File

@ -58,6 +58,7 @@ IncludeCategories:
- Regex: '^"(stdafx.h|pch.h|precomp.h)"$' - Regex: '^"(stdafx.h|pch.h|precomp.h)"$'
Priority: -1 Priority: -1
IndentCaseLabels: false IndentCaseLabels: false
InsertBraces: true
IndentWidth: 4 IndentWidth: 4
IndentWrappedFunctionNames: false IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: true KeepEmptyLinesAtTheStartOfBlocks: true

View File

@ -77,7 +77,9 @@ void SecCompDispatcher::Run()
for (;;) for (;;)
{ {
if (!wait_for_fd(m_notifyFd.get(), POLLIN)) if (!wait_for_fd(m_notifyFd.get(), POLLIN))
{
break; break;
}
// Clear the buffers to make the 5.15 kernel happy. // Clear the buffers to make the 5.15 kernel happy.
notification_buffer.clear(); notification_buffer.clear();

View File

@ -955,6 +955,7 @@ try
// //
if (Config.InitPid.has_value()) if (Config.InitPid.has_value())
{
try try
{ {
std::string LinkPath = std::format(WSL_INTEROP_SOCKET_FORMAT, WSL_TEMP_FOLDER, 1, WSL_INTEROP_SOCKET); std::string LinkPath = std::format(WSL_INTEROP_SOCKET_FORMAT, WSL_TEMP_FOLDER, 1, WSL_INTEROP_SOCKET);
@ -964,6 +965,7 @@ try
} }
} }
CATCH_LOG() CATCH_LOG()
}
UtilCreateWorkerThread( UtilCreateWorkerThread(
"Interop", [InteropChannel = std::move(InteropChannel), InteropServer = std::move(InteropServer), Elevated, &Config]() mutable { "Interop", [InteropChannel = std::move(InteropChannel), InteropServer = std::move(InteropServer), Elevated, &Config]() mutable {

View File

@ -221,6 +221,7 @@ int WslEntryPoint(int Argc, char* Argv[])
{ {
// Handle the special case for import result messages, everything else is sent to the binfmt interpreter. // Handle the special case for import result messages, everything else is sent to the binfmt interpreter.
if (Pid == 1 && strcmp(BaseName, "init") == 0 && Argc == 3 && strcmp(Argv[1], LX_INIT_IMPORT_MESSAGE_ARG) == 0) if (Pid == 1 && strcmp(BaseName, "init") == 0 && Argc == 3 && strcmp(Argv[1], LX_INIT_IMPORT_MESSAGE_ARG) == 0)
{
try try
{ {
wsl::shared::MessageWriter<LX_MINI_INIT_IMPORT_RESULT> message; wsl::shared::MessageWriter<LX_MINI_INIT_IMPORT_RESULT> message;
@ -231,6 +232,7 @@ int WslEntryPoint(int Argc, char* Argv[])
exit(0); exit(0);
} }
CATCH_RETURN_ERRNO() CATCH_RETURN_ERRNO()
}
ExitCode = CreateNtProcess(Argc - 1, &Argv[1]); ExitCode = CreateNtProcess(Argc - 1, &Argv[1]);
} }

View File

@ -25,7 +25,9 @@ public:
{ {
std::unique_lock lck(m_mtx); std::unique_lock lck(m_mtx);
while (m_value.has_value()) while (m_value.has_value())
{
m_cv.wait(lck); m_cv.wait(lck);
}
m_value = value; m_value = value;
m_cv.notify_all(); m_cv.notify_all();
} }
@ -39,7 +41,9 @@ public:
{ {
std::unique_lock lck(m_mtx); std::unique_lock lck(m_mtx);
while (!m_value.has_value()) while (!m_value.has_value())
{
m_cv.wait(lck); m_cv.wait(lck);
}
auto return_value = m_value.value(); auto return_value = m_value.value();
m_value.reset(); m_value.reset();
m_cv.notify_all(); m_cv.notify_all();
@ -57,8 +61,12 @@ public:
{ {
std::unique_lock lck(m_mtx); std::unique_lock lck(m_mtx);
while (!m_value.has_value()) while (!m_value.has_value())
{
if (m_cv.wait_for(lck, timeout) == std::cv_status::timeout) if (m_cv.wait_for(lck, timeout) == std::cv_status::timeout)
{
return std::nullopt; return std::nullopt;
}
}
auto return_value = m_value.value(); auto return_value = m_value.value();
m_value.reset(); m_value.reset();
m_cv.notify_all(); m_cv.notify_all();

View File

@ -65,23 +65,41 @@ bool ParseArpReply(const T& ArpReply, uint16_t ProtocolType, const Neighbor& Sou
Target.ipAddress.ConvertToBytes(TargetIp.data()); Target.ipAddress.ConvertToBytes(TargetIp.data());
if (ArpReply.Destination != Source.macAddress) if (ArpReply.Destination != Source.macAddress)
{
return false; return false;
}
if (ArpReply.EthernetType != htons(ETH_P_ARP)) if (ArpReply.EthernetType != htons(ETH_P_ARP))
{
return false; return false;
}
if (ArpReply.HardwareType != htons(ARPHRD_ETHER)) if (ArpReply.HardwareType != htons(ARPHRD_ETHER))
{
return false; return false;
}
if (ArpReply.ProtocolType != htons(ProtocolType)) if (ArpReply.ProtocolType != htons(ProtocolType))
{
return false; return false;
}
if (ArpReply.HardwareAddressLength != sizeof(ArpReply.SenderHardwareAddress)) if (ArpReply.HardwareAddressLength != sizeof(ArpReply.SenderHardwareAddress))
{
return false; return false;
}
if (ArpReply.ProtocolAddressLength != sizeof(ArpReply.SenderIpAddress)) if (ArpReply.ProtocolAddressLength != sizeof(ArpReply.SenderIpAddress))
{
return false; return false;
}
if (ArpReply.Operation != htons(ARPOP_REPLY)) if (ArpReply.Operation != htons(ARPOP_REPLY))
{
return false; return false;
}
if (ArpReply.TargetHardwareAddress != Source.macAddress) if (ArpReply.TargetHardwareAddress != Source.macAddress)
{
return false; return false;
}
if (ArpReply.TargetIpAddress != SourceIp) if (ArpReply.TargetIpAddress != SourceIp)
{
return false; return false;
}
Target.macAddress = ArpReply.SenderHardwareAddress; Target.macAddress = ArpReply.SenderHardwareAddress;
return true; return true;
@ -129,7 +147,9 @@ bool IpNeighborManager::PerformNeighborDiscovery(Neighbor& Local, Neighbor& Neig
while (std::chrono::steady_clock::now() < expiry) while (std::chrono::steady_clock::now() < expiry)
{ {
if (!wait_for_read(packet_socket.get(), std::chrono::duration_cast<std::chrono::milliseconds>(expiry - std::chrono::steady_clock::now()))) if (!wait_for_read(packet_socket.get(), std::chrono::duration_cast<std::chrono::milliseconds>(expiry - std::chrono::steady_clock::now())))
{
continue; continue;
}
int bytes_read = Syscall(read, packet_socket.get(), &ArpReply, ArpPacketSize); int bytes_read = Syscall(read, packet_socket.get(), &ArpReply, ArpPacketSize);
if (bytes_read != ArpPacketSize) if (bytes_read != ArpPacketSize)
{ {
@ -138,15 +158,19 @@ bool IpNeighborManager::PerformNeighborDiscovery(Neighbor& Local, Neighbor& Neig
if (Local.getFamily() == AF_INET) if (Local.getFamily() == AF_INET)
{ {
if (ParseArpReply(ArpReply.IPv4, ETH_P_IP, Local, Neighbor)) if (ParseArpReply(ArpReply.IPv4, ETH_P_IP, Local, Neighbor))
{
return true; return true;
} }
}
else else
{ {
if (ParseArpReply(ArpReply.IPv6, ETH_P_IPV6, Local, Neighbor)) if (ParseArpReply(ArpReply.IPv6, ETH_P_IPV6, Local, Neighbor))
{
return true; return true;
} }
} }
} }
}
return false; return false;
} }

View File

@ -31,10 +31,14 @@ public:
bool adjust_head(long count) bool adjust_head(long count)
{ {
if ((count + data_offset) < 0) if ((count + data_offset) < 0)
{
return false; return false;
}
if ((count + data_offset) > data_end_offset) if ((count + data_offset) > data_end_offset)
{
return false; return false;
}
data_offset += count; data_offset += count;
return true; return true;
@ -43,9 +47,13 @@ public:
bool adjust_tail(long count) bool adjust_tail(long count)
{ {
if ((count + data_end_offset) < data_offset) if ((count + data_end_offset) < data_offset)
{
return false; return false;
}
if ((count + data_end_offset) > Buffer.size()) if ((count + data_end_offset) > Buffer.size())
{
Buffer.resize(count + data_end_offset); Buffer.resize(count + data_end_offset);
}
data_end_offset += count; data_end_offset += count;
return true; return true;

View File

@ -1896,6 +1896,7 @@ int wsl::windows::common::WslClient::Main(_In_ LPCWSTR commandLine)
// Print error messages for failures. // Print error messages for failures.
if (FAILED(result)) if (FAILED(result))
{
try try
{ {
std::wstring errorString{}; std::wstring errorString{};
@ -1950,6 +1951,7 @@ int wsl::windows::common::WslClient::Main(_In_ LPCWSTR commandLine)
} }
} }
CATCH_LOG() CATCH_LOG()
}
if (g_promptBeforeExit) if (g_promptBeforeExit)
{ {

View File

@ -400,6 +400,7 @@ void wsl::core::Config::Initialize(_In_opt_ HANDLE UserToken)
// Load NAT configuration from the registry. // Load NAT configuration from the registry.
if (NetworkingMode == wsl::core::NetworkingMode::Nat) if (NetworkingMode == wsl::core::NetworkingMode::Nat)
{
try try
{ {
const auto machineKey = wsl::windows::common::registry::OpenLxssMachineKey(); const auto machineKey = wsl::windows::common::registry::OpenLxssMachineKey();
@ -411,9 +412,11 @@ void wsl::core::Config::Initialize(_In_opt_ HANDLE UserToken)
NatIpAddress = wsl::windows::common::registry::ReadString(userKey.get(), nullptr, c_natIpAddress, L""); NatIpAddress = wsl::windows::common::registry::ReadString(userKey.get(), nullptr, c_natIpAddress, L"");
} }
CATCH_LOG() CATCH_LOG()
}
// Due to an issue with Global Secure Access Client, do not use DNS tunneling if the service is present. // Due to an issue with Global Secure Access Client, do not use DNS tunneling if the service is present.
if (EnableDnsTunneling) if (EnableDnsTunneling)
{
try try
{ {
// Open a handle to the service control manager and check if the inbox service is registered. // Open a handle to the service control manager and check if the inbox service is registered.
@ -439,6 +442,7 @@ void wsl::core::Config::Initialize(_In_opt_ HANDLE UserToken)
} }
} }
CATCH_LOG() CATCH_LOG()
}
// Ensure that settings are consistent (disable features that require other features that are not present). // Ensure that settings are consistent (disable features that require other features that are not present).
if (EnableSafeMode) if (EnableSafeMode)

View File

@ -105,6 +105,7 @@ int wsl::windows::common::socket::ReceiveNoThrow(
Overlapped.hEvent = OverlappedEvent.get(); Overlapped.hEvent = OverlappedEvent.get();
DWORD BytesReturned{}; DWORD BytesReturned{};
if (WSARecv(Socket, &VectorBuffer, 1, &BytesReturned, &Flags, &Overlapped, nullptr) != 0) if (WSARecv(Socket, &VectorBuffer, 1, &BytesReturned, &Flags, &Overlapped, nullptr) != 0)
{
try try
{ {
BytesReturned = SOCKET_ERROR; BytesReturned = SOCKET_ERROR;
@ -117,6 +118,7 @@ int wsl::windows::common::socket::ReceiveNoThrow(
// Receive will call GetLastError to look for the error code // Receive will call GetLastError to look for the error code
SetLastError(wil::ResultFromCaughtException()); SetLastError(wil::ResultFromCaughtException());
} }
}
return BytesReturned; return BytesReturned;
} }

View File

@ -751,11 +751,13 @@ wsl::windows::common::SvcComm::LaunchProcess(
// //
if ((WI_IsFlagSet(LaunchFlags, LXSS_LAUNCH_FLAG_ENABLE_INTEROP)) && (ServerPortHandle)) if ((WI_IsFlagSet(LaunchFlags, LXSS_LAUNCH_FLAG_ENABLE_INTEROP)) && (ServerPortHandle))
{
try try
{ {
InitializeInterop(ServerPortHandle.get(), DistributionId); InitializeInterop(ServerPortHandle.get(), DistributionId);
} }
CATCH_LOG() CATCH_LOG()
}
ServerPortHandle.reset(); ServerPortHandle.reset();
@ -823,11 +825,13 @@ wsl::windows::common::SvcComm::LaunchProcess(
// //
if (WI_IsFlagSet(LaunchFlags, LXSS_LAUNCH_FLAG_ENABLE_INTEROP)) if (WI_IsFlagSet(LaunchFlags, LXSS_LAUNCH_FLAG_ENABLE_INTEROP))
{
try try
{ {
SpawnWslHost(InteropSocket.get(), DistributionId, &InstanceId); SpawnWslHost(InteropSocket.get(), DistributionId, &InstanceId);
} }
CATCH_LOG() CATCH_LOG()
}
// //
// Begin reading messages from the utility vm. // Begin reading messages from the utility vm.

View File

@ -346,6 +346,7 @@ bool LxssInstance::RequestStop(_In_ bool Force)
// Send the message to the init daemon to check if the instance can be terminated. // Send the message to the init daemon to check if the instance can be terminated.
bool shutdown = true; bool shutdown = true;
if (m_InitMessagePort) if (m_InitMessagePort)
{
try try
{ {
auto lock = m_InitMessagePort->Lock(); auto lock = m_InitMessagePort->Lock();
@ -359,6 +360,7 @@ bool LxssInstance::RequestStop(_In_ bool Force)
shutdown = terminateResponse.Result; shutdown = terminateResponse.Result;
} }
CATCH_LOG() CATCH_LOG()
}
return shutdown; return shutdown;
} }

View File

@ -2952,11 +2952,13 @@ void LxssUserSessionImpl::_DeleteDistributionLockHeld(_In_ const LXSS_DISTRO_CON
if (PathFileExistsW(Configuration.VhdFilePath.c_str())) if (PathFileExistsW(Configuration.VhdFilePath.c_str()))
{ {
if (m_utilityVm) if (m_utilityVm)
{
try try
{ {
m_utilityVm->EjectVhd(Configuration.VhdFilePath.c_str()); m_utilityVm->EjectVhd(Configuration.VhdFilePath.c_str());
} }
CATCH_LOG() CATCH_LOG()
}
if (WI_IsFlagSet(Flags, LXSS_DELETE_DISTRO_FLAGS_VHD)) if (WI_IsFlagSet(Flags, LXSS_DELETE_DISTRO_FLAGS_VHD))
{ {
@ -2997,6 +2999,7 @@ void LxssUserSessionImpl::_DeleteDistributionLockHeld(_In_ const LXSS_DISTRO_CON
// Remove start menu shortcuts for WSLg applications. // Remove start menu shortcuts for WSLg applications.
if (WI_IsFlagSet(Flags, LXSS_DELETE_DISTRO_FLAGS_WSLG_SHORTCUTS)) if (WI_IsFlagSet(Flags, LXSS_DELETE_DISTRO_FLAGS_WSLG_SHORTCUTS))
{
try try
{ {
const auto dllPath = wsl::windows::common::wslutil::GetBasePath() / WSLG_TS_PLUGIN_DLL; const auto dllPath = wsl::windows::common::wslutil::GetBasePath() / WSLG_TS_PLUGIN_DLL;
@ -3004,6 +3007,7 @@ void LxssUserSessionImpl::_DeleteDistributionLockHeld(_In_ const LXSS_DISTRO_CON
LOG_IF_FAILED(removeAppProvider(Configuration.Name.c_str())); LOG_IF_FAILED(removeAppProvider(Configuration.Name.c_str()));
} }
CATCH_LOG() CATCH_LOG()
}
// If the basepath is empty, delete it. // If the basepath is empty, delete it.
try try
@ -3059,11 +3063,13 @@ std::vector<DistributionRegistration> LxssUserSessionImpl::_EnumerateDistributio
// Ensure that the default distribution is still valid. // Ensure that the default distribution is still valid.
if (!orphanedDistributions.empty()) if (!orphanedDistributions.empty())
{
try try
{ {
_GetDefaultDistro(LxssKey); _GetDefaultDistro(LxssKey);
} }
CATCH_LOG() CATCH_LOG()
}
return distributions; return distributions;
} }

View File

@ -412,6 +412,7 @@ void WslCoreInstance::Initialize()
// Launch the interop server with the user's token. // Launch the interop server with the user's token.
if (response.InteropPort != LX_INIT_UTILITY_VM_INVALID_PORT) if (response.InteropPort != LX_INIT_UTILITY_VM_INVALID_PORT)
{
try try
{ {
const wil::unique_socket socket{wsl::windows::common::hvsocket::Connect(m_runtimeId, response.InteropPort)}; const wil::unique_socket socket{wsl::windows::common::hvsocket::Connect(m_runtimeId, response.InteropPort)};
@ -419,6 +420,7 @@ void WslCoreInstance::Initialize()
nullptr, reinterpret_cast<HANDLE>(socket.get()), nullptr, nullptr, &m_runtimeId, m_userToken.get())}; nullptr, reinterpret_cast<HANDLE>(socket.get()), nullptr, nullptr, &m_runtimeId, m_userToken.get())};
} }
CATCH_LOG() CATCH_LOG()
}
// Initialization was successful. // Initialization was successful.
m_initialized = true; m_initialized = true;
@ -463,6 +465,7 @@ bool WslCoreInstance::RequestStop(_In_ bool Force)
bool shutdown = true; bool shutdown = true;
std::lock_guard lock(m_lock); std::lock_guard lock(m_lock);
if (m_initChannel) if (m_initChannel)
{
try try
{ {
LX_INIT_TERMINATE_INSTANCE terminateMessage{}; LX_INIT_TERMINATE_INSTANCE terminateMessage{};
@ -478,6 +481,7 @@ bool WslCoreInstance::RequestStop(_In_ bool Force)
} }
} }
CATCH_LOG() CATCH_LOG()
}
return shutdown; return shutdown;
} }

View File

@ -282,17 +282,20 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
// N.B. wslhost.exe is launched at medium integrity level and its lifetime // N.B. wslhost.exe is launched at medium integrity level and its lifetime
// is tied to the lifetime of the utility VM. // is tied to the lifetime of the utility VM.
if (m_vmConfig.EnableDebugConsole || !m_vmConfig.DebugConsoleLogFile.empty()) if (m_vmConfig.EnableDebugConsole || !m_vmConfig.DebugConsoleLogFile.empty())
{
try try
{ {
m_vmConfig.EnableDebugConsole = true; m_vmConfig.EnableDebugConsole = true;
m_comPipe0 = wsl::windows::common::helpers::GetUniquePipeName(); m_comPipe0 = wsl::windows::common::helpers::GetUniquePipeName();
} }
CATCH_LOG() CATCH_LOG()
}
// If the system supports virtio console serial ports, use dmesg capture for telemetry and/or debug output. // If the system supports virtio console serial ports, use dmesg capture for telemetry and/or debug output.
// Legacy serial is much slower, so this is not enabled without virtio console support. // Legacy serial is much slower, so this is not enabled without virtio console support.
m_vmConfig.EnableDebugShell &= IsVirtioSerialConsoleSupported(); m_vmConfig.EnableDebugShell &= IsVirtioSerialConsoleSupported();
if (IsVirtioSerialConsoleSupported()) if (IsVirtioSerialConsoleSupported())
{
try try
{ {
bool enableTelemetry = TraceLoggingProviderEnabled(g_hTraceLoggingProvider, WINEVENT_LEVEL_INFO, 0); bool enableTelemetry = TraceLoggingProviderEnabled(g_hTraceLoggingProvider, WINEVENT_LEVEL_INFO, 0);
@ -310,8 +313,10 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
m_gnsTelemetryLogger = GuestTelemetryLogger::Create(VmId, m_vmExitEvent); m_gnsTelemetryLogger = GuestTelemetryLogger::Create(VmId, m_vmExitEvent);
} }
CATCH_LOG() CATCH_LOG()
}
if (m_vmConfig.EnableDebugConsole) if (m_vmConfig.EnableDebugConsole)
{
try try
{ {
// If specified, create a file to log the debug console output. // If specified, create a file to log the debug console output.
@ -329,6 +334,7 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
m_comPipe0.c_str(), !!m_dmesgCollector, m_restrictedToken.get(), logFile ? logFile.get() : nullptr, !m_vmConfig.EnableTelemetry); m_comPipe0.c_str(), !!m_dmesgCollector, m_restrictedToken.get(), logFile ? logFile.get() : nullptr, !m_vmConfig.EnableTelemetry);
} }
CATCH_LOG() CATCH_LOG()
}
// Create the utility VM and store the runtime ID. // Create the utility VM and store the runtime ID.
std::wstring json = GenerateConfigJson(); std::wstring json = GenerateConfigJson();
@ -400,12 +406,14 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
THROW_IF_FAILED(wil::ExpandEnvironmentStringsW(L"%SystemRoot%\\System32\\lxss\\lib", path)); THROW_IF_FAILED(wil::ExpandEnvironmentStringsW(L"%SystemRoot%\\System32\\lxss\\lib", path));
if (wsl::windows::common::filesystem::FileExists(path.c_str())) if (wsl::windows::common::filesystem::FileExists(path.c_str()))
{
try try
{ {
addShare(TEXT(LXSS_GPU_INBOX_LIB_SHARE), path.c_str()); addShare(TEXT(LXSS_GPU_INBOX_LIB_SHARE), path.c_str());
m_enableInboxGpuLibs = true; m_enableInboxGpuLibs = true;
} }
CATCH_LOG() CATCH_LOG()
}
#ifdef WSL_GPU_LIB_PATH #ifdef WSL_GPU_LIB_PATH
@ -482,6 +490,7 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
// the user does not have write access. // the user does not have write access.
ULONG swapLun = ULONG_MAX; ULONG swapLun = ULONG_MAX;
if ((m_systemDistroDeviceId != ULONG_MAX) && (m_vmConfig.SwapSizeBytes > 0)) if ((m_systemDistroDeviceId != ULONG_MAX) && (m_vmConfig.SwapSizeBytes > 0))
{
try try
{ {
{ {
@ -525,6 +534,7 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
swapLun = AttachDiskLockHeld(m_vmConfig.SwapFilePath.c_str(), DiskType::VHD, MountFlags::None, {}, false, m_userToken.get()); swapLun = AttachDiskLockHeld(m_vmConfig.SwapFilePath.c_str(), DiskType::VHD, MountFlags::None, {}, false, m_userToken.get());
} }
CATCH_LOG() CATCH_LOG()
}
// Validate that the requesting network mode is supported. // Validate that the requesting network mode is supported.
// //
@ -777,12 +787,14 @@ WslCoreVm::~WslCoreVm() noexcept
// If the notification did not arrive within the timeout, the VM is // If the notification did not arrive within the timeout, the VM is
// forcefully terminated. // forcefully terminated.
if (forcedTerminate) if (forcedTerminate)
{
try try
{ {
wsl::windows::common::hcs::TerminateComputeSystem(m_system.get()); wsl::windows::common::hcs::TerminateComputeSystem(m_system.get());
} }
CATCH_LOG() CATCH_LOG()
} }
}
m_vmExitEvent.wait(UTILITY_VM_TERMINATE_TIMEOUT); m_vmExitEvent.wait(UTILITY_VM_TERMINATE_TIMEOUT);
@ -840,33 +852,40 @@ WslCoreVm::~WslCoreVm() noexcept
} }
if (WI_IsFlagSet(Entry.second.Flags, DiskStateFlags::AccessGranted)) if (WI_IsFlagSet(Entry.second.Flags, DiskStateFlags::AccessGranted))
{
try try
{ {
wsl::windows::common::hcs::RevokeVmAccess(m_machineId.c_str(), Entry.first.Path.c_str()); wsl::windows::common::hcs::RevokeVmAccess(m_machineId.c_str(), Entry.first.Path.c_str());
} }
CATCH_LOG() CATCH_LOG()
}
}); });
// Delete the swap vhd if one was created. // Delete the swap vhd if one was created.
if (m_swapFileCreated) if (m_swapFileCreated)
{
try try
{ {
const auto runAsUser = wil::impersonate_token(m_userToken.get()); const auto runAsUser = wil::impersonate_token(m_userToken.get());
LOG_IF_WIN32_BOOL_FALSE(DeleteFileW(m_vmConfig.SwapFilePath.c_str())); LOG_IF_WIN32_BOOL_FALSE(DeleteFileW(m_vmConfig.SwapFilePath.c_str()));
} }
CATCH_LOG() CATCH_LOG()
}
// Delete the temp folder if it was created. // Delete the temp folder if it was created.
if (m_tempDirectoryCreated) if (m_tempDirectoryCreated)
{
try try
{ {
const auto runAsUser = wil::impersonate_token(m_userToken.get()); const auto runAsUser = wil::impersonate_token(m_userToken.get());
wil::RemoveDirectoryRecursive(m_tempPath.c_str()); wil::RemoveDirectoryRecursive(m_tempPath.c_str());
} }
CATCH_LOG() CATCH_LOG()
}
// Delete the mstsc.exe local devices key if one was created. // Delete the mstsc.exe local devices key if one was created.
if (m_localDevicesKeyCreated) if (m_localDevicesKeyCreated)
{
try try
{ {
const auto runAsUser = wil::impersonate_token(m_userToken.get()); const auto runAsUser = wil::impersonate_token(m_userToken.get());
@ -875,6 +894,7 @@ WslCoreVm::~WslCoreVm() noexcept
THROW_IF_WIN32_ERROR(::RegDeleteKeyValueW(key.get(), nullptr, m_machineId.c_str())); THROW_IF_WIN32_ERROR(::RegDeleteKeyValueW(key.get(), nullptr, m_machineId.c_str()));
} }
CATCH_LOG() CATCH_LOG()
}
WSL_LOG("TerminateVmStop"); WSL_LOG("TerminateVmStop");
} }
@ -1621,6 +1641,7 @@ std::wstring WslCoreVm::GenerateConfigJson()
// N.B. This is done because arm64 and some older amd64 processors do not support nested virtualization. // N.B. This is done because arm64 and some older amd64 processors do not support nested virtualization.
// Nested virtualization not supported on Windows 10. // Nested virtualization not supported on Windows 10.
if (m_vmConfig.EnableNestedVirtualization) if (m_vmConfig.EnableNestedVirtualization)
{
try try
{ {
std::vector<std::string> processorFeatures{}; std::vector<std::string> processorFeatures{};
@ -1639,6 +1660,7 @@ std::wstring WslCoreVm::GenerateConfigJson()
} }
} }
CATCH_LOG() CATCH_LOG()
}
#ifdef _AMD64_ #ifdef _AMD64_
@ -1881,12 +1903,14 @@ void WslCoreVm::InitializeGuest()
if (LXSS_ENABLE_GUI_APPS()) if (LXSS_ENABLE_GUI_APPS())
{ {
if (m_vmConfig.EnableVirtio) if (m_vmConfig.EnableVirtio)
{
try try
{ {
MountSharedMemoryDevice(c_virtiofsClassId, L"wslg", L"wslg", WSLG_SHARED_MEMORY_SIZE_MB); MountSharedMemoryDevice(c_virtiofsClassId, L"wslg", L"wslg", WSLG_SHARED_MEMORY_SIZE_MB);
m_sharedMemoryRoot = std::format(L"WSL\\{}\\wslg", m_machineId); m_sharedMemoryRoot = std::format(L"WSL\\{}\\wslg", m_machineId);
} }
CATCH_LOG() CATCH_LOG()
}
try try
{ {

View File

@ -40,7 +40,12 @@ $FilePatterns = "\.(h|cpp|hpp|c|hxx)$"
$IgnoreFolders = "(out|.git|.vs|.vscode|bin|CMakeFiles|generated|debug|x64|packages|_deps)$" $IgnoreFolders = "(out|.git|.vs|.vscode|bin|CMakeFiles|generated|debug|x64|packages|_deps)$"
# Handle both execution methods: direct PowerShell and powershell.exe script invocation
if ([string]::IsNullOrEmpty($PSScriptRoot)) {
$RepoRoot = (Get-Location).Path
} else {
$RepoRoot = (Resolve-Path "$PSScriptRoot") $RepoRoot = (Resolve-Path "$PSScriptRoot")
}
<# <#
.SYNOPSIS .SYNOPSIS
@ -170,9 +175,9 @@ function Format-Directory {
$FilesToFormat = @() $FilesToFormat = @()
if ((Get-Item -Path $Path) -is [System.IO.DirectoryInfo]) { if ((Get-Item -Path $Path) -is [System.IO.DirectoryInfo]) {
Get-ChildItem -Path $Path -File ` Get-ChildItem -Path $Path -File `
| Where-Object { $_ -match $FilePatterns } ` | Where-Object { $_.Name -match $FilePatterns } `
| ForEach-Object { | ForEach-Object {
$FilePath = "$Path\$_" $FilePath = "$Path\$($_.Name)"
if (($null -eq $ModifiedFiles) -or ($ModifiedFiles -contains $FilePath)) { if (($null -eq $ModifiedFiles) -or ($ModifiedFiles -contains $FilePath)) {
if (!($FilePath -match "Intermediate")) { if (!($FilePath -match "Intermediate")) {
$FilesToFormat += $FilePath $FilesToFormat += $FilePath
@ -180,9 +185,9 @@ function Format-Directory {
} }
} }
Get-ChildItem -Path $Path -Directory ` Get-ChildItem -Path $Path -Directory `
| Where-Object { $_ -notmatch $IgnoreFolders } ` | Where-Object { $_.Name -notmatch $IgnoreFolders } `
| ForEach-Object { | ForEach-Object {
$SubResult = (Format-Directory -Path "$Path\$_" ` $SubResult = (Format-Directory -Path "$Path\$($_.Name)" `
-ClangFormat $ClangFormat ` -ClangFormat $ClangFormat `
-RepoRoot $RepoRoot ` -RepoRoot $RepoRoot `
-FilePatterns $FilePatterns ` -FilePatterns $FilePatterns `