.clang-format: add InsertBraces: true and minor fix to FormatSource.ps1 (#13712)

Co-authored-by: Ben Hillis <benhill@ntdev.microsoft.com>
This commit is contained in:
Ben Hillis 2025-11-14 16:12:02 -08:00 committed by GitHub
parent 7c010a1e93
commit 87c1100620
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 130 additions and 30 deletions

View File

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

View File

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

View File

@ -955,6 +955,7 @@ try
//
if (Config.InitPid.has_value())
{
try
{
std::string LinkPath = std::format(WSL_INTEROP_SOCKET_FORMAT, WSL_TEMP_FOLDER, 1, WSL_INTEROP_SOCKET);
@ -963,7 +964,8 @@ try
LOG_ERROR("symlink({}, {}) failed {}", InteropServer.Path(), LinkPath.c_str(), errno);
}
}
CATCH_LOG()
CATCH_LOG()
}
UtilCreateWorkerThread(
"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.
if (Pid == 1 && strcmp(BaseName, "init") == 0 && Argc == 3 && strcmp(Argv[1], LX_INIT_IMPORT_MESSAGE_ARG) == 0)
{
try
{
wsl::shared::MessageWriter<LX_MINI_INIT_IMPORT_RESULT> message;
@ -230,7 +231,8 @@ int WslEntryPoint(int Argc, char* Argv[])
read(STDIN_FILENO, buffer, sizeof(buffer));
exit(0);
}
CATCH_RETURN_ERRNO()
CATCH_RETURN_ERRNO()
}
ExitCode = CreateNtProcess(Argc - 1, &Argv[1]);
}

View File

@ -25,7 +25,9 @@ public:
{
std::unique_lock lck(m_mtx);
while (m_value.has_value())
{
m_cv.wait(lck);
}
m_value = value;
m_cv.notify_all();
}
@ -39,7 +41,9 @@ public:
{
std::unique_lock lck(m_mtx);
while (!m_value.has_value())
{
m_cv.wait(lck);
}
auto return_value = m_value.value();
m_value.reset();
m_cv.notify_all();
@ -57,8 +61,12 @@ public:
{
std::unique_lock lck(m_mtx);
while (!m_value.has_value())
{
if (m_cv.wait_for(lck, timeout) == std::cv_status::timeout)
{
return std::nullopt;
}
}
auto return_value = m_value.value();
m_value.reset();
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());
if (ArpReply.Destination != Source.macAddress)
{
return false;
}
if (ArpReply.EthernetType != htons(ETH_P_ARP))
{
return false;
}
if (ArpReply.HardwareType != htons(ARPHRD_ETHER))
{
return false;
}
if (ArpReply.ProtocolType != htons(ProtocolType))
{
return false;
}
if (ArpReply.HardwareAddressLength != sizeof(ArpReply.SenderHardwareAddress))
{
return false;
}
if (ArpReply.ProtocolAddressLength != sizeof(ArpReply.SenderIpAddress))
{
return false;
}
if (ArpReply.Operation != htons(ARPOP_REPLY))
{
return false;
}
if (ArpReply.TargetHardwareAddress != Source.macAddress)
{
return false;
}
if (ArpReply.TargetIpAddress != SourceIp)
{
return false;
}
Target.macAddress = ArpReply.SenderHardwareAddress;
return true;
@ -129,7 +147,9 @@ bool IpNeighborManager::PerformNeighborDiscovery(Neighbor& Local, Neighbor& Neig
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())))
{
continue;
}
int bytes_read = Syscall(read, packet_socket.get(), &ArpReply, ArpPacketSize);
if (bytes_read != ArpPacketSize)
{
@ -138,12 +158,16 @@ bool IpNeighborManager::PerformNeighborDiscovery(Neighbor& Local, Neighbor& Neig
if (Local.getFamily() == AF_INET)
{
if (ParseArpReply(ArpReply.IPv4, ETH_P_IP, Local, Neighbor))
{
return true;
}
}
else
{
if (ParseArpReply(ArpReply.IPv6, ETH_P_IPV6, Local, Neighbor))
{
return true;
}
}
}
}

View File

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

View File

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

View File

@ -400,6 +400,7 @@ void wsl::core::Config::Initialize(_In_opt_ HANDLE UserToken)
// Load NAT configuration from the registry.
if (NetworkingMode == wsl::core::NetworkingMode::Nat)
{
try
{
const auto machineKey = wsl::windows::common::registry::OpenLxssMachineKey();
@ -410,10 +411,12 @@ void wsl::core::Config::Initialize(_In_opt_ HANDLE UserToken)
const auto userKey = wsl::windows::common::registry::OpenLxssUserKey();
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.
if (EnableDnsTunneling)
{
try
{
// Open a handle to the service control manager and check if the inbox service is registered.
@ -438,7 +441,8 @@ 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).
if (EnableSafeMode)

View File

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

View File

@ -751,11 +751,13 @@ wsl::windows::common::SvcComm::LaunchProcess(
//
if ((WI_IsFlagSet(LaunchFlags, LXSS_LAUNCH_FLAG_ENABLE_INTEROP)) && (ServerPortHandle))
{
try
{
InitializeInterop(ServerPortHandle.get(), DistributionId);
}
CATCH_LOG()
CATCH_LOG()
}
ServerPortHandle.reset();
@ -823,11 +825,13 @@ wsl::windows::common::SvcComm::LaunchProcess(
//
if (WI_IsFlagSet(LaunchFlags, LXSS_LAUNCH_FLAG_ENABLE_INTEROP))
{
try
{
SpawnWslHost(InteropSocket.get(), DistributionId, &InstanceId);
}
CATCH_LOG()
CATCH_LOG()
}
//
// 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.
bool shutdown = true;
if (m_InitMessagePort)
{
try
{
auto lock = m_InitMessagePort->Lock();
@ -358,7 +359,8 @@ bool LxssInstance::RequestStop(_In_ bool Force)
m_InitMessagePort->Receive(&terminateResponse, sizeof(terminateResponse));
shutdown = terminateResponse.Result;
}
CATCH_LOG()
CATCH_LOG()
}
return shutdown;
}

View File

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

View File

@ -412,13 +412,15 @@ void WslCoreInstance::Initialize()
// Launch the interop server with the user's token.
if (response.InteropPort != LX_INIT_UTILITY_VM_INVALID_PORT)
{
try
{
const wil::unique_socket socket{wsl::windows::common::hvsocket::Connect(m_runtimeId, response.InteropPort)};
wil::unique_handle info{wsl::windows::common::helpers::LaunchInteropServer(
nullptr, reinterpret_cast<HANDLE>(socket.get()), nullptr, nullptr, &m_runtimeId, m_userToken.get())};
}
CATCH_LOG()
CATCH_LOG()
}
// Initialization was successful.
m_initialized = true;
@ -463,6 +465,7 @@ bool WslCoreInstance::RequestStop(_In_ bool Force)
bool shutdown = true;
std::lock_guard lock(m_lock);
if (m_initChannel)
{
try
{
LX_INIT_TERMINATE_INSTANCE terminateMessage{};
@ -477,7 +480,8 @@ bool WslCoreInstance::RequestStop(_In_ bool Force)
shutdown = message->Result;
}
}
CATCH_LOG()
CATCH_LOG()
}
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
// is tied to the lifetime of the utility VM.
if (m_vmConfig.EnableDebugConsole || !m_vmConfig.DebugConsoleLogFile.empty())
{
try
{
m_vmConfig.EnableDebugConsole = true;
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.
// Legacy serial is much slower, so this is not enabled without virtio console support.
m_vmConfig.EnableDebugShell &= IsVirtioSerialConsoleSupported();
if (IsVirtioSerialConsoleSupported())
{
try
{
bool enableTelemetry = TraceLoggingProviderEnabled(g_hTraceLoggingProvider, WINEVENT_LEVEL_INFO, 0);
@ -309,9 +312,11 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
// Initialize the guest telemetry logger.
m_gnsTelemetryLogger = GuestTelemetryLogger::Create(VmId, m_vmExitEvent);
}
CATCH_LOG()
CATCH_LOG()
}
if (m_vmConfig.EnableDebugConsole)
{
try
{
// If specified, create a file to log the debug console output.
@ -328,7 +333,8 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
wsl::windows::common::helpers::LaunchDebugConsole(
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.
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));
if (wsl::windows::common::filesystem::FileExists(path.c_str()))
{
try
{
addShare(TEXT(LXSS_GPU_INBOX_LIB_SHARE), path.c_str());
m_enableInboxGpuLibs = true;
}
CATCH_LOG()
CATCH_LOG()
}
#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.
ULONG swapLun = ULONG_MAX;
if ((m_systemDistroDeviceId != ULONG_MAX) && (m_vmConfig.SwapSizeBytes > 0))
{
try
{
{
@ -524,7 +533,8 @@ 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());
}
CATCH_LOG()
CATCH_LOG()
}
// Validate that the requesting network mode is supported.
//
@ -777,11 +787,13 @@ WslCoreVm::~WslCoreVm() noexcept
// If the notification did not arrive within the timeout, the VM is
// forcefully terminated.
if (forcedTerminate)
{
try
{
wsl::windows::common::hcs::TerminateComputeSystem(m_system.get());
}
CATCH_LOG()
CATCH_LOG()
}
}
m_vmExitEvent.wait(UTILITY_VM_TERMINATE_TIMEOUT);
@ -840,33 +852,40 @@ WslCoreVm::~WslCoreVm() noexcept
}
if (WI_IsFlagSet(Entry.second.Flags, DiskStateFlags::AccessGranted))
{
try
{
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.
if (m_swapFileCreated)
{
try
{
const auto runAsUser = wil::impersonate_token(m_userToken.get());
LOG_IF_WIN32_BOOL_FALSE(DeleteFileW(m_vmConfig.SwapFilePath.c_str()));
}
CATCH_LOG()
CATCH_LOG()
}
// Delete the temp folder if it was created.
if (m_tempDirectoryCreated)
{
try
{
const auto runAsUser = wil::impersonate_token(m_userToken.get());
wil::RemoveDirectoryRecursive(m_tempPath.c_str());
}
CATCH_LOG()
CATCH_LOG()
}
// Delete the mstsc.exe local devices key if one was created.
if (m_localDevicesKeyCreated)
{
try
{
const auto runAsUser = wil::impersonate_token(m_userToken.get());
@ -874,7 +893,8 @@ WslCoreVm::~WslCoreVm() noexcept
const auto key = wsl::windows::common::registry::CreateKey(userKey.get(), c_localDevicesKey, KEY_SET_VALUE);
THROW_IF_WIN32_ERROR(::RegDeleteKeyValueW(key.get(), nullptr, m_machineId.c_str()));
}
CATCH_LOG()
CATCH_LOG()
}
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.
// Nested virtualization not supported on Windows 10.
if (m_vmConfig.EnableNestedVirtualization)
{
try
{
std::vector<std::string> processorFeatures{};
@ -1638,7 +1659,8 @@ std::wstring WslCoreVm::GenerateConfigJson()
EMIT_USER_WARNING(wsl::shared::Localization::MessageNestedVirtualizationNotSupported());
}
}
CATCH_LOG()
CATCH_LOG()
}
#ifdef _AMD64_
@ -1881,12 +1903,14 @@ void WslCoreVm::InitializeGuest()
if (LXSS_ENABLE_GUI_APPS())
{
if (m_vmConfig.EnableVirtio)
{
try
{
MountSharedMemoryDevice(c_virtiofsClassId, L"wslg", L"wslg", WSLG_SHARED_MEMORY_SIZE_MB);
m_sharedMemoryRoot = std::format(L"WSL\\{}\\wslg", m_machineId);
}
CATCH_LOG()
CATCH_LOG()
}
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)$"
$RepoRoot = (Resolve-Path "$PSScriptRoot")
# Handle both execution methods: direct PowerShell and powershell.exe script invocation
if ([string]::IsNullOrEmpty($PSScriptRoot)) {
$RepoRoot = (Get-Location).Path
} else {
$RepoRoot = (Resolve-Path "$PSScriptRoot")
}
<#
.SYNOPSIS
@ -170,9 +175,9 @@ function Format-Directory {
$FilesToFormat = @()
if ((Get-Item -Path $Path) -is [System.IO.DirectoryInfo]) {
Get-ChildItem -Path $Path -File `
| Where-Object { $_ -match $FilePatterns } `
| Where-Object { $_.Name -match $FilePatterns } `
| ForEach-Object {
$FilePath = "$Path\$_"
$FilePath = "$Path\$($_.Name)"
if (($null -eq $ModifiedFiles) -or ($ModifiedFiles -contains $FilePath)) {
if (!($FilePath -match "Intermediate")) {
$FilesToFormat += $FilePath
@ -180,9 +185,9 @@ function Format-Directory {
}
}
Get-ChildItem -Path $Path -Directory `
| Where-Object { $_ -notmatch $IgnoreFolders } `
| Where-Object { $_.Name -notmatch $IgnoreFolders } `
| ForEach-Object {
$SubResult = (Format-Directory -Path "$Path\$_" `
$SubResult = (Format-Directory -Path "$Path\$($_.Name)" `
-ClangFormat $ClangFormat `
-RepoRoot $RepoRoot `
-FilePatterns $FilePatterns `