Fix batch of minor bugs (#40197)

Fix ~40 minor bugs / issues.
This commit is contained in:
Feng Wang
2026-04-22 10:03:16 +08:00
committed by GitHub
parent e6a5a465d7
commit 58bd525afe
33 changed files with 62 additions and 64 deletions

View File

@@ -223,7 +223,7 @@ inline int ResultFromCaughtException()
#define THROW_LAST_ERROR() THROW_ERRNO(errno);
#define THROW_INVALID() THROW_ERRNO(EINVAL)
#define THROW_UNEXCEPTED() THROW_ERRNO(EINVAL)
#define THROW_UNEXPECTED() THROW_ERRNO(EINVAL)
#define THROW_INVALID_IF(Condition) THROW_ERRNO_IF(EINVAL, (Condition))
#define THROW_UNEXPECTED_IF(Condition) THROW_ERRNO_IF(EINVAL, (Condition))
@@ -437,7 +437,7 @@ public:
static unique_pipe create(int flags)
{
int pipe[2] = {-1, -1};
if (pipe2(pipe, flags) < -1)
if (pipe2(pipe, flags) < 0)
{
THROW_ERRNO(errno);
}

View File

@@ -193,7 +193,6 @@ try
// whenever there is new data on the TCP connection.
epoll_event event{};
event.events = EPOLLIN;
event.data.fd = localContext->m_tcpConnection.get();
event.data.ptr = localContext.get();
Syscall(epoll_ctl, m_epollFd.get(), EPOLL_CTL_ADD, localContext->m_tcpConnection.get(), &event);

View File

@@ -104,8 +104,8 @@ void SecCompDispatcher::Run()
}
int result = 0;
GNS_LOG_INFO(
"Notified for arch {:X} syscall {} with id {}lu for pid {} with args ({}lX, {}lX, {}lX, {}lX, {}lX, "
"{}lX)",
"Notified for arch {:X} syscall {} with id {} for pid {} with args ({:X}, {:X}, {:X}, {:X}, {:X}, "
"{:X})",
callInfo->data.arch,
callInfo->data.nr,
callInfo->id,
@@ -140,14 +140,14 @@ void SecCompDispatcher::Run()
resultInfo->val = 0;
resultInfo->flags = result == 0 ? SECCOMP_USER_NOTIF_FLAG_CONTINUE : 0;
GNS_LOG_INFO("Responding to notification with id {}lu for pid {}, result {}", callInfo->id, callInfo->pid, result);
GNS_LOG_INFO("Responding to notification with id {} for pid {}, result {}", callInfo->id, callInfo->pid, result);
try
{
Syscall(ioctl, m_notifyFd.get(), SECCOMP_IOCTL_NOTIF_SEND, resultInfo);
}
catch (std::exception& e)
{
GNS_LOG_ERROR("Failed to respond to notification with id {}lu for pid {}, {}", callInfo->id, callInfo->pid, e.what());
GNS_LOG_ERROR("Failed to respond to notification with id {} for pid {}, {}", callInfo->id, callInfo->pid, e.what());
}
}
}
@@ -211,7 +211,7 @@ std::optional<std::vector<gsl::byte>> SecCompDispatcher::ReadProcessMemory(uint6
}
catch (std::exception& e)
{
GNS_LOG_ERROR("Failed to read process memory for pid {}, cookie {}u, {}", Pid, Cookie, e.what());
GNS_LOG_ERROR("Failed to read process memory for pid {}, cookie {}, {}", Pid, Cookie, e.what());
return std::nullopt;
}
}

View File

@@ -2247,7 +2247,7 @@ try
const auto* Message = gslhelpers::try_get_struct<LX_INIT_MOUNT_DRVFS>(Buffer);
if (!Message)
{
LOG_ERROR("Unexpected sizeof for LX_INIT_MOUNT_DRVFS: {}u", Buffer.size());
LOG_ERROR("Unexpected sizeof for LX_INIT_MOUNT_DRVFS: {}", Buffer.size());
return -1;
}

View File

@@ -324,7 +324,7 @@ try
sched_param Parameter{};
Parameter.sched_priority = 0;
THROW_LAST_ERROR_IF(pthread_setschedparam(pthread_self(), SCHED_IDLE, &Parameter) < 0);
THROW_LAST_ERROR_IF(pthread_setschedparam(pthread_self(), SCHED_IDLE, &Parameter) != 0);
//
// Periodically check if the machine is idle by querying procfs for CPU usage.
@@ -342,7 +342,7 @@ try
long long int const ReclaimThreshold = (get_nprocs() * sysconf(_SC_CLK_TCK) * SleepDuration / std::chrono::seconds(1)) / 200; // 0.5%
long long int ReclaimWindow[20] = {}; // 10 minutes
long long int ReclaimWindowLength = COUNT_OF(ReclaimWindow);
bool ReclaimIdling;
bool ReclaimIdling = false;
//
// Fall back to drop cache if the required cgroup path is not present.
@@ -429,7 +429,7 @@ try
if (PageReportingOrder != 0 && (Start - Stop) > IdleThreshold)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
const long long int Stop = GetUserCpuTime();
Stop = GetUserCpuTime();
THROW_LAST_ERROR_IF(Stop == -1);
if ((Stop - Start) < IdleThreshold)
{
@@ -471,7 +471,7 @@ Return Value:
return {};
}
struct sockaddr_nl Address;
struct sockaddr_nl Address{};
Address.nl_family = AF_NETLINK;
if (bind(Fd.get(), (struct sockaddr*)&Address, sizeof(Address)) < 0)
{
@@ -587,7 +587,7 @@ Return Value:
std::string content = wsl::shared::string::ReadFile<char, char>(std::format("/sys/block/{}/dev", BlockDeviceName).c_str());
auto separator = content.find(':');
if (separator == 0 || separator - 1 >= content.size() || separator == std::string::npos)
if (separator == std::string::npos || separator == 0 || separator + 1 == content.size())
{
LOG_ERROR("Failed to parse device number '{}' for device '{}'", content.c_str(), BlockDeviceName.c_str());
THROW_ERRNO(EINVAL);

View File

@@ -184,7 +184,7 @@ void RunPlan9Server(const char* socketPath, const char* logFile, int logLevel, b
limit.rlim_cur = limit.rlim_max;
if (setrlimit(RLIMIT_NOFILE, &limit) < 0)
{
LOG_ERROR("setrlimit(RLIMIT_NOFILE, {}lu, {}lu) failed {}", limit.rlim_cur, limit.rlim_max, errno);
LOG_ERROR("setrlimit(RLIMIT_NOFILE, {}, {}) failed {}", limit.rlim_cur, limit.rlim_max, errno);
}
// Open the root.

View File

@@ -172,6 +172,7 @@ Return Value:
if (!InteropConnection)
{
LOG_ERROR("accept4 failed {}", errno);
return {};
}
timeval Timeout{};
@@ -784,10 +785,6 @@ Return Value:
if (Output)
{
(*Output) += Buffer.data();
if (Result < 0)
{
goto ErrorExit;
}
}
else
{

View File

@@ -8,7 +8,7 @@ Module Name:
Abstract:
This file wslpath function definitions.
This file contains wslinfo function definitions.
--*/

View File

@@ -232,6 +232,7 @@ int MountParseMountInfoLine(char* line, PMOUNT_ENTRY entry)
{
goto ParseMountInfoLineEnd;
}
break;
case MountFieldRoot:
entry->Root = current;

View File

@@ -356,7 +356,7 @@ void Interface::SetActiveChild(const Interface& child_interface)
void Interface::CreateTunTapAdapter(const std::string& name, bool TunAdapter)
{
wil::unique_fd fd;
if (name.size() > IFNAMSIZ)
if (name.size() >= IFNAMSIZ)
{
throw RuntimeErrorWithSourceLocation("Tun adapter name exceeds IFNAMSIZ");
}
@@ -644,7 +644,7 @@ void Interface::EnableNetworkSetting(const char* settingName, int addressFamily)
wil::unique_fd fd(Syscall(open, settingFilePath.c_str(), (O_WRONLY | O_CLOEXEC)));
Syscall(write, fd.get(), c_value1, sizeof(c_value1));
Syscall(write, fd.get(), c_value1, sizeof(c_value1) - 1);
}
void Interface::DisableNetworkSetting(const char* settingName, int addressFamily)
@@ -654,7 +654,7 @@ void Interface::DisableNetworkSetting(const char* settingName, int addressFamily
wil::unique_fd fd(Syscall(open, settingFilePath.c_str(), (O_WRONLY | O_CLOEXEC)));
Syscall(write, fd.get(), c_value0, sizeof(c_value0));
Syscall(write, fd.get(), c_value0, sizeof(c_value0) - 1);
}
void Interface::ResetIpv6State()

View File

@@ -70,7 +70,7 @@ std::vector<const TAttribute*> NetlinkMessage<TMessage>::Attributes(int type) co
std::format(
"Attribute at offset {}: attempted to access beyond attribute offset ({} > {})",
(reinterpret_cast<const char*>(e) - &*m_responseBegin),
sizeof(TMessage),
sizeof(TAttribute),
e->rta_len));
}

View File

@@ -1060,7 +1060,7 @@ LX_INT File::Access(AccessFlags flags)
}
std::string parentPath;
const int index = name.find_last_of('/');
const auto index = name.find_last_of('/');
if (index != std::string::npos)
{
parentPath = name.substr(0, index);

View File

@@ -33,7 +33,7 @@ struct Root final : public IRoot
std::vector<char> buffer(bufsize);
passwd pwd{};
passwd* result = nullptr;
if (getpwuid_r(uid, &pwd, buffer.data(), buffer.size(), &result) < 0 || result == nullptr)
if (getpwuid_r(uid, &pwd, buffer.data(), buffer.size(), &result) != 0 || result == nullptr)
{
Plan9TraceLoggingProvider::LogMessage(std::format("getpwuid_r failed for uid: {}, errno={}", uid, errno));
return;

View File

@@ -24,14 +24,14 @@ CoroutineIoIssuer::CoroutineIoIssuer(int fd) : m_FileDescriptor(fd)
void CoroutineIoIssuer::Callback(sigval value)
{
const auto operation = static_cast<CoroutineIoOperation*>(value.sival_ptr);
auto bytesTransferred = aio_return(&operation->ControlBlock);
int error = 0;
if (bytesTransferred < 0)
auto error = aio_error(&operation->ControlBlock);
if (error == EINPROGRESS)
{
error = aio_error(&operation->ControlBlock);
return;
}
auto bytesTransferred = aio_return(&operation->ControlBlock);
operation->Result = {error, static_cast<size_t>(bytesTransferred)};
operation->Result = {-error, error == 0 ? static_cast<size_t>(bytesTransferred) : 0};
if (!operation->DoneOrCoroutine.exchange(true))
{
return;
@@ -55,7 +55,7 @@ bool CoroutineIoIssuer::PreIssue(CoroutineIoOperation& operation, CancelToken& t
}
// The operation has already been cancelled. Don't even issue the IO.
operation.Result = {ECANCELED, 0};
operation.Result = {-ECANCELED, 0};
operation.DoneOrCoroutine = true;
return false;
}
@@ -286,7 +286,7 @@ Task<IoResult> WriteAsync(CoroutineIoIssuer& file, std::uint64_t offset, gsl::sp
cb.aio_offset = offset;
if (aio_write(&cb) < 0)
{
return {errno, 0};
return {-errno, 0};
}
return {};

View File

@@ -27,7 +27,7 @@ struct dirent* DirectoryEnumerator::Next()
if (result == nullptr)
{
// If errno is still 0, it means EOF is reached which is not an error.
THROW_LAST_ERROR_IF(errno != 0)
THROW_LAST_ERROR_IF(errno != 0);
}
else
{

View File

@@ -162,7 +162,7 @@ gid_t GetUserGroupId(uid_t uid)
for (;;)
{
buffer.resize(size);
if (getpwuid_r(uid, &pwd, buffer.data(), size, &result) < 0)
if (getpwuid_r(uid, &pwd, buffer.data(), size, &result) != 0)
{
if (errno != ERANGE)
{
@@ -198,7 +198,7 @@ gid_t GetGroupIdByName(const char* name)
for (;;)
{
buffer.resize(size);
if (getgrnam_r(name, &grp, buffer.data(), size, &result) < 0)
if (getgrnam_r(name, &grp, buffer.data(), size, &result) != 0)
{
if (errno != ERANGE)
{

View File

@@ -768,11 +768,11 @@ ValueDone:
fprintf(stderr, "expected \"\n");
}
EMIT_USER_WARNING(Localization::MessageConfigExpected("'", filePath, line));
EMIT_USER_WARNING(Localization::MessageConfigExpected("\"", filePath, line));
// This key value will be overwritten, so we can ignore any malformed values.
// However, we can still inform the user of the issue per warning above.
if (!firstMatchedKey || !matchedKey)
if (!firstMatchedKey && !matchedKey)
{
goto InvalidLine;
}

View File

@@ -167,12 +167,13 @@ private:
size_t GetRelativeIndex(unsigned int& Index)
{
const size_t Offset = reinterpret_cast<char*>(&Index) - reinterpret_cast<char*>(m_buffer.data());
const auto* indexPtr = reinterpret_cast<char*>(&Index);
const auto* bufferStart = reinterpret_cast<char*>(m_buffer.data());
// Validate that 'Index' is actually within the bounds of our buffer
assert(Offset >= 0 && Offset < m_buffer.size());
assert(indexPtr >= bufferStart && indexPtr + sizeof(index) <= bufferStart + m_buffer.size());
return Offset;
return static_cast<size_t>(indexPtr - bufferStart);
}
void WriteRelativeIndex(size_t Offset, unsigned int Value)
@@ -181,6 +182,5 @@ private:
}
std::vector<std::byte> m_buffer;
size_t m_offset = 0;
};
} // namespace wsl::shared

View File

@@ -85,7 +85,7 @@ inline void PrettyPrint(std::stringstream& Out, const T (&Value)[Size])
Out << "[";
for (auto i = 0; i < Size; i++)
{
if (i > 0 && i < Size - 1)
if (i > 0 && i < Size)
{
Out << ",";
}

View File

@@ -49,7 +49,7 @@ try
#if defined(_MSC_VER)
THROW_HR(E_UNEXPECTED);
#elif defined(__GNUC__)
THROW_UNEXCEPTED();
THROW_UNEXPECTED();
#endif
}
@@ -60,7 +60,7 @@ try
#if defined(_MSC_VER)
THROW_HR_MSG(E_UNEXPECTED, "Unexpected message size: %llu", MessageSize);
#elif defined(__GNUC__)
THROW_UNEXCEPTED();
THROW_UNEXPECTED();
#endif
}
@@ -69,7 +69,7 @@ try
#if defined(_MSC_VER)
THROW_HR_MSG(E_UNEXPECTED, "Message size too large: %llu", MessageSize);
#elif defined(__GNUC__)
THROW_UNEXCEPTED();
THROW_UNEXPECTED();
#endif
}

View File

@@ -181,6 +181,11 @@ inline std::string CleanHostname(const std::string_view Hostname)
}
}
if (result.size() > 64)
{
result.resize(64);
}
while (!result.empty() && (result.back() == '.' || result.back() == '-'))
{
result.pop_back();
@@ -190,10 +195,6 @@ inline std::string CleanHostname(const std::string_view Hostname)
{
result = c_defaultHostName;
}
else if (result.size() > 64)
{
result.resize(64);
}
return result;
}

View File

@@ -22,7 +22,7 @@ HandleConsoleProgressBar::HandleConsoleProgressBar(HANDLE handle, std::wstring&&
{
// If this file isn't a disk file, we can't show actual progress. Just show an indicator in that case
LARGE_INTEGER fileSize{};
if (GetFileType(handle) != FILE_TYPE_DISK || FAILED(GetFileSizeEx(handle, &fileSize)))
if (GetFileType(handle) != FILE_TYPE_DISK || !GetFileSizeEx(handle, &fileSize))
{
m_progressBar.emplace<ConsoleProgressIndicator>(std::move(message));
}

View File

@@ -117,11 +117,11 @@ bool wsl::core::networking::IsFlowSteeringSupportedByHns() noexcept
allocatePortRange.load(c_computeNetworkModuleName, "HcnReserveGuestNetworkServicePortRange"));
static LxssDynamicFunction<decltype(HcnReserveGuestNetworkServicePort)> allocatePort{DynamicFunctionErrorLogs::None};
RETURN_IF_FAILED_EXPECTED(allocatePortRange.load(c_computeNetworkModuleName, "HcnReserveGuestNetworkServicePort"));
RETURN_IF_FAILED_EXPECTED(allocatePort.load(c_computeNetworkModuleName, "HcnReserveGuestNetworkServicePort"));
static LxssDynamicFunction<decltype(HcnReleaseGuestNetworkServicePortReservationHandle)> releasePort{DynamicFunctionErrorLogs::None};
RETURN_IF_FAILED_EXPECTED(
allocatePortRange.load(c_computeNetworkModuleName, "HcnReleaseGuestNetworkServicePortReservationHandle"));
releasePort.load(c_computeNetworkModuleName, "HcnReleaseGuestNetworkServicePortReservationHandle"));
supported = true;
}

View File

@@ -70,7 +70,7 @@ std::vector<BYTE> ParseHex(const std::wstring& input)
for (auto i = 0; i < input.size(); i += 2)
{
// Skip '0x', if any
if (i == 0 && input[0] == '0' && tolower(input[1]) == 'x')
if (i == 0 && input.size() >= 2 && input[0] == '0' && tolower(input[1]) == 'x')
{
continue;
}

View File

@@ -838,10 +838,10 @@ std::string wsl::windows::common::filesystem::GetLinuxHostName()
{
DWORD size = 0;
WI_VERIFY(GetComputerNameExA(ComputerNamePhysicalDnsHostname, nullptr, &size) == FALSE);
std::string hostName(size, '\0');
std::string hostName(size - 1, '\0');
THROW_LAST_ERROR_IF(!GetComputerNameExA(ComputerNamePhysicalDnsHostname, hostName.data(), &size));
WI_ASSERT((size <= LX_HOST_NAME_MAX) && (hostName.size() == size + 1));
WI_ASSERT((size <= LX_HOST_NAME_MAX) && (hostName.size() == size));
return wsl::shared::string::CleanHostname(hostName);
}

View File

@@ -215,7 +215,7 @@ void wsl::windows::common::helpers::ConnectPipe(_In_ HANDLE Pipe, _In_ DWORD Tim
}
const auto Result = WaitForMultipleObjects(gsl::narrow_cast<DWORD>(WaitHandles.size()), WaitHandles.data(), FALSE, Timeout);
if (!ExitEvents.empty() && Result > WAIT_OBJECT_0 && Result <= WAIT_OBJECT_0 + WaitHandles.size())
if (!ExitEvents.empty() && Result > WAIT_OBJECT_0 && Result < WAIT_OBJECT_0 + WaitHandles.size())
{
THROW_HR(E_ABORT);
}
@@ -372,7 +372,7 @@ std::string wsl::windows::common::helpers::GetLinuxTimezone(_In_opt_ HANDLE User
THROW_HR_IF_MSG(E_FAIL, (U_FAILURE(status) != false), "%hs", u_errorName(status));
timezone.resize(buffer.size());
timezone.resize(size);
u_UCharsToChars(buffer.data(), timezone.data(), static_cast<int32_t>(timezone.size()));
}
CATCH_LOG()

View File

@@ -207,7 +207,7 @@ bool wsl::windows::common::relay::InterruptableWait(_In_ HANDLE WaitObject, _In_
const DWORD waitResult = WaitForMultipleObjects(gsl::narrow_cast<DWORD>(waitObjects.size()), waitObjects.data(), FALSE, INFINITE);
if (waitResult != WAIT_OBJECT_0)
{
if (waitResult > WAIT_OBJECT_0 && waitResult <= WAIT_OBJECT_0 + waitObjects.size())
if (waitResult > WAIT_OBJECT_0 && waitResult < WAIT_OBJECT_0 + waitObjects.size())
{
return false;
}

View File

@@ -177,7 +177,7 @@ int wsl::windows::common::socket::Send(
Offset += BytesWritten;
if (Offset < Buffer.size())
{
WSL_LOG("PartialSocketWrite", TraceLoggingValue(Buffer.size(), "MessagSize"), TraceLoggingValue(Offset, "Offset"));
WSL_LOG("PartialSocketWrite", TraceLoggingValue(Buffer.size(), "MessageSize"), TraceLoggingValue(Offset, "Offset"));
}
}

View File

@@ -77,7 +77,7 @@ void BridgedNetworking::FillInitialConfiguration(LX_MINI_INIT_NETWORKING_CONFIGU
message.NetworkingMode = LxMiniInitNetworkingModeBridged;
message.DisableIpv6 = !m_config.EnableIpv6;
message.EnableDhcpClient = m_config.EnableDhcp;
message.DhcpTimeout = static_cast<int>(std::round(m_config.DhcpTimeout / 1000));
message.DhcpTimeout = static_cast<int>(std::round(m_config.DhcpTimeout / 1000.0));
message.PortTrackerType = m_config.EnableLocalhostRelay ? LxMiniInitPortTrackerTypeRelay : LxMiniInitPortTrackerTypeNone;
}

View File

@@ -96,7 +96,6 @@ DistributionRegistration DistributionRegistration::Create(
distribution.Write(Property::Version, Version);
distribution.Write(Property::BasePath, BasePath);
distribution.Write(Property::Flags, Flags);
distribution.Write(Property::Flags, Flags);
distribution.Write(Property::DefaultUid, DefaultUID);
distribution.Write(Property::RunOOBE, EnableOobe);

View File

@@ -891,7 +891,7 @@ HRESULT LxssUserSessionImpl::MountDisk(
_Out_ int* Step,
_Out_ LPWSTR* MountName)
{
ExecutionContext context(Context::DetachDisk);
ExecutionContext context(Context::MountDisk);
std::lock_guard lock(m_instanceLock);
return wil::ResultFromException([&]() {

View File

@@ -1874,6 +1874,7 @@ void WslCoreVm::InitializeGuest()
const auto errorString = wsl::windows::common::wslutil::GetSystemErrorString(result);
EMIT_USER_WARNING(wsl::shared::Localization::MessageLocalhostRelayFailed(errorString));
}
break;
}
default:

View File

@@ -33,7 +33,7 @@ struct in6_addr_linux
} u;
};
const uint16_t ADDR6_MASK3 = ~in6_addr_linux(IN6ADDR_LOOPBACK_INIT).u.addr32[3];
const uint32_t ADDR6_MASK3 = ~in6_addr_linux(IN6ADDR_LOOPBACK_INIT).u.addr32[3];
const uint32_t N_ADDR_LOOPBACK = ntohl(INADDR_LOOPBACK);
const uint32_t N_ADDR_ANY = ntohl(INADDR_ANY);