mirror of
https://github.com/espressif/openthread.git
synced 2026-10-07 08:17:40 +00:00
[posix] fix -Wstringop-truncation warning in IsLoopbackInterface (#13330)
Address a CI build failure caused by a compiler warning promoted to an
error (`-Werror=stringop-truncation`) in POSIX mDNS socket management.
In `IsLoopbackInterface(int aIfIndex)` in `mdns_socket.cpp`, the
interface name was retrieved via `if_indextoname()` into `char
ifName[IF_NAMESIZE]` and then copied into `ifr.ifr_name` using:
strncpy(ifr.ifr_name, ifName, sizeof(ifr.ifr_name) - 1);
Because both `ifName` and `ifr.ifr_name` are 16-byte arrays on Linux
(`IF_NAMESIZE == IFNAMSIZ`), calling `strncpy()` with a bound of 15
(`sizeof(ifr.ifr_name) - 1`) triggers `-Wstringop-truncation` on GCC
with fortified libc headers.
To resolve the warning and simplify the code, eliminate the temporary
`ifName` buffer and `strncpy()` copy by operating directly on `ifr`:
1. Zero-initialize `struct ifreq ifr` (`memset(&ifr, 0, sizeof(ifr))`)
before checking the interface name.
2. Pass `ifr.ifr_name` directly (`char[IFNAMSIZ]`) as the destination
buffer for `if_indextoname()`.
3. If `if_indextoname()` succeeds, `ifr.ifr_name` is NUL-terminated
and can be checked via `strcmp(ifr.ifr_name, "lo") == 0`.
4. When the interface is not `"lo"`, `ifr` is already populated with
the interface name and can be passed directly to `ioctl(fd,
SIOCGIFFLAGS, &ifr)` to query the `IFF_LOOPBACK` flag.
This commit is contained in:
@@ -462,10 +462,10 @@ exit:
|
||||
#ifdef __linux__
|
||||
static bool IsLoopbackInterface(int aIfIndex)
|
||||
{
|
||||
static int sLastIfIndex = -1;
|
||||
static bool sLastIsLoopback = false;
|
||||
bool isLoopback = false;
|
||||
char ifName[IF_NAMESIZE];
|
||||
static int sLastIfIndex = -1;
|
||||
static bool sLastIsLoopback = false;
|
||||
bool isLoopback = false;
|
||||
struct ifreq ifr;
|
||||
|
||||
VerifyOrExit(aIfIndex > 0);
|
||||
|
||||
@@ -475,9 +475,10 @@ static bool IsLoopbackInterface(int aIfIndex)
|
||||
ExitNow();
|
||||
}
|
||||
|
||||
VerifyOrExit(if_indextoname(static_cast<unsigned int>(aIfIndex), ifName) != nullptr);
|
||||
memset(&ifr, 0, sizeof(ifr));
|
||||
VerifyOrExit(if_indextoname(static_cast<unsigned int>(aIfIndex), ifr.ifr_name) != nullptr);
|
||||
|
||||
if (strcmp(ifName, "lo") == 0)
|
||||
if (strcmp(ifr.ifr_name, "lo") == 0)
|
||||
{
|
||||
isLoopback = true;
|
||||
}
|
||||
@@ -487,11 +488,6 @@ static bool IsLoopbackInterface(int aIfIndex)
|
||||
|
||||
if (fd >= 0)
|
||||
{
|
||||
struct ifreq ifr;
|
||||
|
||||
memset(&ifr, 0, sizeof(ifr));
|
||||
strncpy(ifr.ifr_name, ifName, sizeof(ifr.ifr_name) - 1);
|
||||
|
||||
if (ioctl(fd, SIOCGIFFLAGS, &ifr) == 0)
|
||||
{
|
||||
isLoopback = ((ifr.ifr_flags & IFF_LOOPBACK) != 0);
|
||||
|
||||
Reference in New Issue
Block a user