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

Co-authored-by: Ben Hillis <benhill@ntdev.microsoft.com>

Ben Hillis committed Nov 14, 2025 at 16:12 UTC 87c110062013ccfbad878eecc11842c70d111dfa
16 files changed +130 -30
.clang-format
+1
@@ -58,6 +58,7 @@ IncludeCategories:
58 - Regex: '^"(stdafx.h|pch.h|precomp.h)"$'
59 Priority: -1
60 IndentCaseLabels: false
61 +InsertBraces: true
62 IndentWidth: 4
63 IndentWrappedFunctionNames: false
64 KeepEmptyLinesAtTheStartOfBlocks: true
src/linux/init/SecCompDispatcher.cpp
+2
@@ -77,7 +77,9 @@ void SecCompDispatcher::Run()
77 for (;;)
78 {
79 if (!wait_for_fd(m_notifyFd.get(), POLLIN))
80 + {
81 break;
82 + }
83
84 // Clear the buffers to make the 5.15 kernel happy.
85 notification_buffer.clear();
src/linux/init/config.cpp
+3 -1
@@ -955,6 +955,7 @@ try
955 //
956
957 if (Config.InitPid.has_value())
958 + {
959 try
960 {
961 std::string LinkPath = std::format(WSL_INTEROP_SOCKET_FORMAT, WSL_TEMP_FOLDER, 1, WSL_INTEROP_SOCKET);
@@ -963,7 +964,8 @@ try
964 LOG_ERROR("symlink({}, {}) failed {}", InteropServer.Path(), LinkPath.c_str(), errno);
965 }
966 }
966 - CATCH_LOG()
967 + CATCH_LOG()
968 + }
969
970 UtilCreateWorkerThread(
971 "Interop", [InteropChannel = std::move(InteropChannel), InteropServer = std::move(InteropServer), Elevated, &Config]() mutable {
src/linux/init/init.cpp
+3 -1
@@ -221,6 +221,7 @@ int WslEntryPoint(int Argc, char* Argv[])
221 {
222 // Handle the special case for import result messages, everything else is sent to the binfmt interpreter.
223 if (Pid == 1 && strcmp(BaseName, "init") == 0 && Argc == 3 && strcmp(Argv[1], LX_INIT_IMPORT_MESSAGE_ARG) == 0)
224 + {
225 try
226 {
227 wsl::shared::MessageWriter<LX_MINI_INIT_IMPORT_RESULT> message;
@@ -230,7 +231,8 @@ int WslEntryPoint(int Argc, char* Argv[])
231 read(STDIN_FILENO, buffer, sizeof(buffer));
232 exit(0);
233 }
233 - CATCH_RETURN_ERRNO()
234 + CATCH_RETURN_ERRNO()
235 + }
236
237 ExitCode = CreateNtProcess(Argc - 1, &Argv[1]);
238 }
src/linux/init/waitablevalue.h
+8
@@ -25,7 +25,9 @@ public:
25 {
26 std::unique_lock lck(m_mtx);
27 while (m_value.has_value())
28 + {
29 m_cv.wait(lck);
30 + }
31 m_value = value;
32 m_cv.notify_all();
33 }
@@ -39,7 +41,9 @@ public:
41 {
42 std::unique_lock lck(m_mtx);
43 while (!m_value.has_value())
44 + {
45 m_cv.wait(lck);
46 + }
47 auto return_value = m_value.value();
48 m_value.reset();
49 m_cv.notify_all();
@@ -57,8 +61,12 @@ public:
61 {
62 std::unique_lock lck(m_mtx);
63 while (!m_value.has_value())
64 + {
65 if (m_cv.wait_for(lck, timeout) == std::cv_status::timeout)
66 + {
67 return std::nullopt;
68 + }
69 + }
70 auto return_value = m_value.value();
71 m_value.reset();
72 m_cv.notify_all();
src/linux/netlinkutil/IpNeighborManager.cpp
+24
@@ -65,23 +65,41 @@ bool ParseArpReply(const T& ArpReply, uint16_t ProtocolType, const Neighbor& Sou
65 Target.ipAddress.ConvertToBytes(TargetIp.data());
66
67 if (ArpReply.Destination != Source.macAddress)
68 + {
69 return false;
70 + }
71 if (ArpReply.EthernetType != htons(ETH_P_ARP))
72 + {
73 return false;
74 + }
75 if (ArpReply.HardwareType != htons(ARPHRD_ETHER))
76 + {
77 return false;
78 + }
79 if (ArpReply.ProtocolType != htons(ProtocolType))
80 + {
81 return false;
82 + }
83 if (ArpReply.HardwareAddressLength != sizeof(ArpReply.SenderHardwareAddress))
84 + {
85 return false;
86 + }
87 if (ArpReply.ProtocolAddressLength != sizeof(ArpReply.SenderIpAddress))
88 + {
89 return false;
90 + }
91 if (ArpReply.Operation != htons(ARPOP_REPLY))
92 + {
93 return false;
94 + }
95 if (ArpReply.TargetHardwareAddress != Source.macAddress)
96 + {
97 return false;
98 + }
99 if (ArpReply.TargetIpAddress != SourceIp)
100 + {
101 return false;
102 + }
103
104 Target.macAddress = ArpReply.SenderHardwareAddress;
105 return true;
@@ -129,7 +147,9 @@ bool IpNeighborManager::PerformNeighborDiscovery(Neighbor& Local, Neighbor& Neig
147 while (std::chrono::steady_clock::now() < expiry)
148 {
149 if (!wait_for_read(packet_socket.get(), std::chrono::duration_cast<std::chrono::milliseconds>(expiry - std::chrono::steady_clock::now())))
150 + {
151 continue;
152 + }
153 int bytes_read = Syscall(read, packet_socket.get(), &ArpReply, ArpPacketSize);
154 if (bytes_read != ArpPacketSize)
155 {
@@ -138,12 +158,16 @@ bool IpNeighborManager::PerformNeighborDiscovery(Neighbor& Local, Neighbor& Neig
158 if (Local.getFamily() == AF_INET)
159 {
160 if (ParseArpReply(ArpReply.IPv4, ETH_P_IP, Local, Neighbor))
161 + {
162 return true;
163 + }
164 }
165 else
166 {
167 if (ParseArpReply(ArpReply.IPv6, ETH_P_IPV6, Local, Neighbor))
168 + {
169 return true;
170 + }
171 }
172 }
173 }
src/linux/netlinkutil/Packet.h
+8
@@ -31,10 +31,14 @@ public:
31 bool adjust_head(long count)
32 {
33 if ((count + data_offset) < 0)
34 + {
35 return false;
36 + }
37
38 if ((count + data_offset) > data_end_offset)
39 + {
40 return false;
41 + }
42
43 data_offset += count;
44 return true;
@@ -43,9 +47,13 @@ public:
47 bool adjust_tail(long count)
48 {
49 if ((count + data_end_offset) < data_offset)
50 + {
51 return false;
52 + }
53 if ((count + data_end_offset) > Buffer.size())
54 + {
55 Buffer.resize(count + data_end_offset);
56 + }
57
58 data_end_offset += count;
59 return true;
src/windows/common/WslClient.cpp
+3 -1
@@ -1896,6 +1896,7 @@ int wsl::windows::common::WslClient::Main(_In_ LPCWSTR commandLine)
1896
1897 // Print error messages for failures.
1898 if (FAILED(result))
1899 + {
1900 try
1901 {
1902 std::wstring errorString{};
@@ -1949,7 +1950,8 @@ int wsl::windows::common::WslClient::Main(_In_ LPCWSTR commandLine)
1950 }
1951 }
1952 }
1952 - CATCH_LOG()
1953 + CATCH_LOG()
1954 + }
1955
1956 if (g_promptBeforeExit)
1957 {
src/windows/common/WslCoreConfig.cpp
+6 -2
@@ -400,6 +400,7 @@ void wsl::core::Config::Initialize(_In_opt_ HANDLE UserToken)
400
401 // Load NAT configuration from the registry.
402 if (NetworkingMode == wsl::core::NetworkingMode::Nat)
403 + {
404 try
405 {
406 const auto machineKey = wsl::windows::common::registry::OpenLxssMachineKey();
@@ -410,10 +411,12 @@ void wsl::core::Config::Initialize(_In_opt_ HANDLE UserToken)
411 const auto userKey = wsl::windows::common::registry::OpenLxssUserKey();
412 NatIpAddress = wsl::windows::common::registry::ReadString(userKey.get(), nullptr, c_natIpAddress, L"");
413 }
413 - CATCH_LOG()
414 + CATCH_LOG()
415 + }
416
417 // Due to an issue with Global Secure Access Client, do not use DNS tunneling if the service is present.
418 if (EnableDnsTunneling)
419 + {
420 try
421 {
422 // 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)
441 }
442 }
443 }
441 - CATCH_LOG()
444 + CATCH_LOG()
445 + }
446
447 // Ensure that settings are consistent (disable features that require other features that are not present).
448 if (EnableSafeMode)
src/windows/common/socket.cpp
+2
@@ -105,6 +105,7 @@ int wsl::windows::common::socket::ReceiveNoThrow(
105 Overlapped.hEvent = OverlappedEvent.get();
106 DWORD BytesReturned{};
107 if (WSARecv(Socket, &VectorBuffer, 1, &BytesReturned, &Flags, &Overlapped, nullptr) != 0)
108 + {
109 try
110 {
111 BytesReturned = SOCKET_ERROR;
@@ -117,6 +118,7 @@ int wsl::windows::common::socket::ReceiveNoThrow(
118 // Receive will call GetLastError to look for the error code
119 SetLastError(wil::ResultFromCaughtException());
120 }
121 + }
122
123 return BytesReturned;
124 }
src/windows/common/svccomm.cpp
+6 -2
@@ -751,11 +751,13 @@ wsl::windows::common::SvcComm::LaunchProcess(
751 //
752
753 if ((WI_IsFlagSet(LaunchFlags, LXSS_LAUNCH_FLAG_ENABLE_INTEROP)) && (ServerPortHandle))
754 + {
755 try
756 {
757 InitializeInterop(ServerPortHandle.get(), DistributionId);
758 }
758 - CATCH_LOG()
759 + CATCH_LOG()
760 + }
761
762 ServerPortHandle.reset();
763
@@ -823,11 +825,13 @@ wsl::windows::common::SvcComm::LaunchProcess(
825 //
826
827 if (WI_IsFlagSet(LaunchFlags, LXSS_LAUNCH_FLAG_ENABLE_INTEROP))
828 + {
829 try
830 {
831 SpawnWslHost(InteropSocket.get(), DistributionId, &InstanceId);
832 }
830 - CATCH_LOG()
833 + CATCH_LOG()
834 + }
835
836 //
837 // Begin reading messages from the utility vm.
src/windows/service/exe/LxssInstance.cpp
+3 -1
@@ -346,6 +346,7 @@ bool LxssInstance::RequestStop(_In_ bool Force)
346 // Send the message to the init daemon to check if the instance can be terminated.
347 bool shutdown = true;
348 if (m_InitMessagePort)
349 + {
350 try
351 {
352 auto lock = m_InitMessagePort->Lock();
@@ -358,7 +359,8 @@ bool LxssInstance::RequestStop(_In_ bool Force)
359 m_InitMessagePort->Receive(&terminateResponse, sizeof(terminateResponse));
360 shutdown = terminateResponse.Result;
361 }
361 - CATCH_LOG()
362 + CATCH_LOG()
363 + }
364
365 return shutdown;
366 }
src/windows/service/exe/LxssUserSession.cpp
+9 -3
@@ -2952,11 +2952,13 @@ void LxssUserSessionImpl::_DeleteDistributionLockHeld(_In_ const LXSS_DISTRO_CON
2952 if (PathFileExistsW(Configuration.VhdFilePath.c_str()))
2953 {
2954 if (m_utilityVm)
2955 + {
2956 try
2957 {
2958 m_utilityVm->EjectVhd(Configuration.VhdFilePath.c_str());
2959 }
2959 - CATCH_LOG()
2960 + CATCH_LOG()
2961 + }
2962
2963 if (WI_IsFlagSet(Flags, LXSS_DELETE_DISTRO_FLAGS_VHD))
2964 {
@@ -2997,13 +2999,15 @@ void LxssUserSessionImpl::_DeleteDistributionLockHeld(_In_ const LXSS_DISTRO_CON
2999
3000 // Remove start menu shortcuts for WSLg applications.
3001 if (WI_IsFlagSet(Flags, LXSS_DELETE_DISTRO_FLAGS_WSLG_SHORTCUTS))
3002 + {
3003 try
3004 {
3005 const auto dllPath = wsl::windows::common::wslutil::GetBasePath() / WSLG_TS_PLUGIN_DLL;
3006 static LxssDynamicFunction<decltype(RemoveAppProvider)> removeAppProvider(dllPath.c_str(), "RemoveAppProvider");
3007 LOG_IF_FAILED(removeAppProvider(Configuration.Name.c_str()));
3008 }
3006 - CATCH_LOG()
3009 + CATCH_LOG()
3010 + }
3011
3012 // If the basepath is empty, delete it.
3013 try
@@ -3059,11 +3063,13 @@ std::vector<DistributionRegistration> LxssUserSessionImpl::_EnumerateDistributio
3063
3064 // Ensure that the default distribution is still valid.
3065 if (!orphanedDistributions.empty())
3066 + {
3067 try
3068 {
3069 _GetDefaultDistro(LxssKey);
3070 }
3066 - CATCH_LOG()
3071 + CATCH_LOG()
3072 + }
3073
3074 return distributions;
3075 }
src/windows/service/exe/WslCoreInstance.cpp
+6 -2
@@ -412,13 +412,15 @@ void WslCoreInstance::Initialize()
412
413 // Launch the interop server with the user's token.
414 if (response.InteropPort != LX_INIT_UTILITY_VM_INVALID_PORT)
415 + {
416 try
417 {
418 const wil::unique_socket socket{wsl::windows::common::hvsocket::Connect(m_runtimeId, response.InteropPort)};
419 wil::unique_handle info{wsl::windows::common::helpers::LaunchInteropServer(
420 nullptr, reinterpret_cast<HANDLE>(socket.get()), nullptr, nullptr, &m_runtimeId, m_userToken.get())};
421 }
421 - CATCH_LOG()
422 + CATCH_LOG()
423 + }
424
425 // Initialization was successful.
426 m_initialized = true;
@@ -463,6 +465,7 @@ bool WslCoreInstance::RequestStop(_In_ bool Force)
465 bool shutdown = true;
466 std::lock_guard lock(m_lock);
467 if (m_initChannel)
468 + {
469 try
470 {
471 LX_INIT_TERMINATE_INSTANCE terminateMessage{};
@@ -477,7 +480,8 @@ bool WslCoreInstance::RequestStop(_In_ bool Force)
480 shutdown = message->Result;
481 }
482 }
480 - CATCH_LOG()
483 + CATCH_LOG()
484 + }
485
486 return shutdown;
487 }
src/windows/service/exe/WslCoreVm.cpp
+36 -12
@@ -282,17 +282,20 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
282 // N.B. wslhost.exe is launched at medium integrity level and its lifetime
283 // is tied to the lifetime of the utility VM.
284 if (m_vmConfig.EnableDebugConsole || !m_vmConfig.DebugConsoleLogFile.empty())
285 + {
286 try
287 {
288 m_vmConfig.EnableDebugConsole = true;
289 m_comPipe0 = wsl::windows::common::helpers::GetUniquePipeName();
290 }
290 - CATCH_LOG()
291 + CATCH_LOG()
292 + }
293
294 // If the system supports virtio console serial ports, use dmesg capture for telemetry and/or debug output.
295 // Legacy serial is much slower, so this is not enabled without virtio console support.
296 m_vmConfig.EnableDebugShell &= IsVirtioSerialConsoleSupported();
297 if (IsVirtioSerialConsoleSupported())
298 + {
299 try
300 {
301 bool enableTelemetry = TraceLoggingProviderEnabled(g_hTraceLoggingProvider, WINEVENT_LEVEL_INFO, 0);
@@ -309,9 +312,11 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
312 // Initialize the guest telemetry logger.
313 m_gnsTelemetryLogger = GuestTelemetryLogger::Create(VmId, m_vmExitEvent);
314 }
312 - CATCH_LOG()
315 + CATCH_LOG()
316 + }
317
318 if (m_vmConfig.EnableDebugConsole)
319 + {
320 try
321 {
322 // 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
333 wsl::windows::common::helpers::LaunchDebugConsole(
334 m_comPipe0.c_str(), !!m_dmesgCollector, m_restrictedToken.get(), logFile ? logFile.get() : nullptr, !m_vmConfig.EnableTelemetry);
335 }
331 - CATCH_LOG()
336 + CATCH_LOG()
337 + }
338
339 // Create the utility VM and store the runtime ID.
340 std::wstring json = GenerateConfigJson();
@@ -400,12 +406,14 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
406 THROW_IF_FAILED(wil::ExpandEnvironmentStringsW(L"%SystemRoot%\\System32\\lxss\\lib", path));
407
408 if (wsl::windows::common::filesystem::FileExists(path.c_str()))
409 + {
410 try
411 {
412 addShare(TEXT(LXSS_GPU_INBOX_LIB_SHARE), path.c_str());
413 m_enableInboxGpuLibs = true;
414 }
408 - CATCH_LOG()
415 + CATCH_LOG()
416 + }
417
418 #ifdef WSL_GPU_LIB_PATH
419
@@ -482,6 +490,7 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
490 // the user does not have write access.
491 ULONG swapLun = ULONG_MAX;
492 if ((m_systemDistroDeviceId != ULONG_MAX) && (m_vmConfig.SwapSizeBytes > 0))
493 + {
494 try
495 {
496 {
@@ -524,7 +533,8 @@ void WslCoreVm::Initialize(const GUID& VmId, const wil::shared_handle& UserToken
533
534 swapLun = AttachDiskLockHeld(m_vmConfig.SwapFilePath.c_str(), DiskType::VHD, MountFlags::None, {}, false, m_userToken.get());
535 }
527 - CATCH_LOG()
536 + CATCH_LOG()
537 + }
538
539 // Validate that the requesting network mode is supported.
540 //
@@ -777,11 +787,13 @@ WslCoreVm::~WslCoreVm() noexcept
787 // If the notification did not arrive within the timeout, the VM is
788 // forcefully terminated.
789 if (forcedTerminate)
790 + {
791 try
792 {
793 wsl::windows::common::hcs::TerminateComputeSystem(m_system.get());
794 }
784 - CATCH_LOG()
795 + CATCH_LOG()
796 + }
797 }
798
799 m_vmExitEvent.wait(UTILITY_VM_TERMINATE_TIMEOUT);
@@ -840,33 +852,40 @@ WslCoreVm::~WslCoreVm() noexcept
852 }
853
854 if (WI_IsFlagSet(Entry.second.Flags, DiskStateFlags::AccessGranted))
855 + {
856 try
857 {
858 wsl::windows::common::hcs::RevokeVmAccess(m_machineId.c_str(), Entry.first.Path.c_str());
859 }
847 - CATCH_LOG()
860 + CATCH_LOG()
861 + }
862 });
863
864 // Delete the swap vhd if one was created.
865 if (m_swapFileCreated)
866 + {
867 try
868 {
869 const auto runAsUser = wil::impersonate_token(m_userToken.get());
870 LOG_IF_WIN32_BOOL_FALSE(DeleteFileW(m_vmConfig.SwapFilePath.c_str()));
871 }
857 - CATCH_LOG()
872 + CATCH_LOG()
873 + }
874
875 // Delete the temp folder if it was created.
876 if (m_tempDirectoryCreated)
877 + {
878 try
879 {
880 const auto runAsUser = wil::impersonate_token(m_userToken.get());
881 wil::RemoveDirectoryRecursive(m_tempPath.c_str());
882 }
866 - CATCH_LOG()
883 + CATCH_LOG()
884 + }
885
886 // Delete the mstsc.exe local devices key if one was created.
887 if (m_localDevicesKeyCreated)
888 + {
889 try
890 {
891 const auto runAsUser = wil::impersonate_token(m_userToken.get());
@@ -874,7 +893,8 @@ WslCoreVm::~WslCoreVm() noexcept
893 const auto key = wsl::windows::common::registry::CreateKey(userKey.get(), c_localDevicesKey, KEY_SET_VALUE);
894 THROW_IF_WIN32_ERROR(::RegDeleteKeyValueW(key.get(), nullptr, m_machineId.c_str()));
895 }
877 - CATCH_LOG()
896 + CATCH_LOG()
897 + }
898
899 WSL_LOG("TerminateVmStop");
900 }
@@ -1621,6 +1641,7 @@ std::wstring WslCoreVm::GenerateConfigJson()
1641 // N.B. This is done because arm64 and some older amd64 processors do not support nested virtualization.
1642 // Nested virtualization not supported on Windows 10.
1643 if (m_vmConfig.EnableNestedVirtualization)
1644 + {
1645 try
1646 {
1647 std::vector<std::string> processorFeatures{};
@@ -1638,7 +1659,8 @@ std::wstring WslCoreVm::GenerateConfigJson()
1659 EMIT_USER_WARNING(wsl::shared::Localization::MessageNestedVirtualizationNotSupported());
1660 }
1661 }
1641 - CATCH_LOG()
1662 + CATCH_LOG()
1663 + }
1664
1665 #ifdef _AMD64_
1666
@@ -1881,12 +1903,14 @@ void WslCoreVm::InitializeGuest()
1903 if (LXSS_ENABLE_GUI_APPS())
1904 {
1905 if (m_vmConfig.EnableVirtio)
1906 + {
1907 try
1908 {
1909 MountSharedMemoryDevice(c_virtiofsClassId, L"wslg", L"wslg", WSLG_SHARED_MEMORY_SIZE_MB);
1910 m_sharedMemoryRoot = std::format(L"WSL\\{}\\wslg", m_machineId);
1911 }
1889 - CATCH_LOG()
1912 + CATCH_LOG()
1913 + }
1914
1915 try
1916 {
tools/FormatSource.ps1.in
+10 -5
@@ -40,7 +40,12 @@ $FilePatterns = "\.(h|cpp|hpp|c|hxx)$"
40
41 $IgnoreFolders = "(out|.git|.vs|.vscode|bin|CMakeFiles|generated|debug|x64|packages|_deps)$"
42
43 -$RepoRoot = (Resolve-Path "$PSScriptRoot")
43 +# Handle both execution methods: direct PowerShell and powershell.exe script invocation
44 +if ([string]::IsNullOrEmpty($PSScriptRoot)) {
45 + $RepoRoot = (Get-Location).Path
46 +} else {
47 + $RepoRoot = (Resolve-Path "$PSScriptRoot")
48 +}
49
50 <#
51 .SYNOPSIS
@@ -170,9 +175,9 @@ function Format-Directory {
175 $FilesToFormat = @()
176 if ((Get-Item -Path $Path) -is [System.IO.DirectoryInfo]) {
177 Get-ChildItem -Path $Path -File `
173 - | Where-Object { $_ -match $FilePatterns } `
178 + | Where-Object { $_.Name -match $FilePatterns } `
179 | ForEach-Object {
175 - $FilePath = "$Path\$_"
180 + $FilePath = "$Path\$($_.Name)"
181 if (($null -eq $ModifiedFiles) -or ($ModifiedFiles -contains $FilePath)) {
182 if (!($FilePath -match "Intermediate")) {
183 $FilesToFormat += $FilePath
@@ -180,9 +185,9 @@ function Format-Directory {
185 }
186 }
187 Get-ChildItem -Path $Path -Directory `
183 - | Where-Object { $_ -notmatch $IgnoreFolders } `
188 + | Where-Object { $_.Name -notmatch $IgnoreFolders } `
189 | ForEach-Object {
185 - $SubResult = (Format-Directory -Path "$Path\$_" `
190 + $SubResult = (Format-Directory -Path "$Path\$($_.Name)" `
191 -ClangFormat $ClangFormat `
192 -RepoRoot $RepoRoot `
193 -FilePatterns $FilePatterns `