[libc-commits] [libc] c400d53 - [libc] Implement getifaddrs for link-level (AF_PACKET) entries (#246355)

via libc-commits libc-commits at lists.llvm.org
Fri Nov 27 00:25:21 PST 2026


Author: Pavel Labath
Date: 2026-11-27T09:25:15+01:00
New Revision: c400d53b8dcbcc22090f92b5779a0f0b29f93068

URL: https://github.com/llvm/llvm-project/commit/c400d53b8dcbcc22090f92b5779a0f0b29f93068
DIFF: https://github.com/llvm/llvm-project/commit/c400d53b8dcbcc22090f92b5779a0f0b29f93068.diff

LOG: [libc] Implement getifaddrs for link-level (AF_PACKET) entries (#246355)

This is the first part of the real getifaddrs implementation. It dumps
the network interfaces (RTM_GETLINK) using the netlink code shared with
if_nameindex, and creates an AF_PACKET entry for each of them. The
entries contain the interface name and flags, and the hardware and
broadcast addresses (as struct sockaddr_ll). IPv4 and IPv6 addresses and
ifa_data will come in follow-up patches.

Like in if_nameindex, the entries are collected in a BlockStore while we
parse the messages, and then copied into a single allocation, which also
holds the names and addresses they point to. This makes freeifaddrs a
single delete[] (glibc does the same thing). Unlike if_nameindex, we
report allocation failures as ENOMEM, as that's what other getifaddrs
implementations do.

struct sockaddr_ll only has room for 8 bytes of hardware address, which
is not enough for e.g. InfiniBand (20 bytes). Like glibc and musl, I'm
using a version of the struct with a larger (MAX_ADDR_LEN = 32 byte)
buffer, and skipping addresses which still don't fit.

This also adds the AF_PACKET and PF_PACKET constants, which getifaddrs
users need for recognizing these entries.

Assisted-by: Claude

Added: 
    libc/src/ifaddrs/linux/getifaddrs_impl.h

Modified: 
    libc/include/llvm-libc-macros/linux/sys-socket-macros.h
    libc/src/ifaddrs/linux/CMakeLists.txt
    libc/src/ifaddrs/linux/freeifaddrs.cpp
    libc/src/ifaddrs/linux/getifaddrs.cpp
    libc/test/src/__support/net/linux/netlink_test_support.h
    libc/test/src/ifaddrs/linux/CMakeLists.txt
    libc/test/src/ifaddrs/linux/getifaddrs_test.cpp

Removed: 
    


################################################################################
diff  --git a/libc/include/llvm-libc-macros/linux/sys-socket-macros.h b/libc/include/llvm-libc-macros/linux/sys-socket-macros.h
index 0ee66284427d88..402c19d24b041e 100644
--- a/libc/include/llvm-libc-macros/linux/sys-socket-macros.h
+++ b/libc/include/llvm-libc-macros/linux/sys-socket-macros.h
@@ -18,6 +18,7 @@
 #define AF_INET 2     // Internet IPv4 Protocol
 #define AF_INET6 10   // IP version 6
 #define AF_NETLINK 16 // Netlink sockets
+#define AF_PACKET 17  // Low-level packet interface
 
 // 4.2BSD protocol families
 #define PF_UNSPEC AF_UNSPEC
@@ -26,6 +27,7 @@
 #define PF_INET AF_INET
 #define PF_INET6 AF_INET6
 #define PF_NETLINK AF_NETLINK
+#define PF_PACKET AF_PACKET
 
 #define SOCK_STREAM 1
 #define SOCK_DGRAM 2

diff  --git a/libc/src/ifaddrs/linux/CMakeLists.txt b/libc/src/ifaddrs/linux/CMakeLists.txt
index c370308e459eaf..f7cbd0ff84b33b 100644
--- a/libc/src/ifaddrs/linux/CMakeLists.txt
+++ b/libc/src/ifaddrs/linux/CMakeLists.txt
@@ -1,3 +1,29 @@
+add_header_library(
+  getifaddrs_impl
+  HDRS
+    getifaddrs_impl.h
+  DEPENDS
+    libc.hdr.errno_macros
+    libc.hdr.net_if_macros
+    libc.hdr.offsetof_macros
+    libc.hdr.stdint_proxy
+    libc.hdr.sys_socket_macros
+    libc.hdr.types.sa_family_t
+    libc.hdr.types.struct_ifaddrs
+    libc.hdr.types.struct_sockaddr
+    libc.include.sys_socket
+    libc.src.__support.CPP.scope
+    libc.src.__support.CPP.span
+    libc.src.__support.CPP.string_view
+    libc.src.__support.blockstore
+    libc.src.__support.checked_ptr
+    libc.src.__support.common
+    libc.src.__support.error_or
+    libc.src.__support.math_extras
+    libc.src.__support.net.linux.netlink
+    libc.src.string.memory_utils.inline_memcpy
+)
+
 add_entrypoint_object(
   freeifaddrs
   SRCS
@@ -5,7 +31,9 @@ add_entrypoint_object(
   HDRS
     ../freeifaddrs.h
   DEPENDS
+    libc.hdr.stdint_proxy
     libc.hdr.types.struct_ifaddrs
+    libc.src.__support.CPP.new
     libc.src.__support.common
     libc.src.__support.macros.config
 )
@@ -17,10 +45,13 @@ add_entrypoint_object(
   HDRS
     ../getifaddrs.h
   DEPENDS
-    libc.hdr.errno_macros
+    .getifaddrs_impl
     libc.hdr.types.struct_ifaddrs
+    libc.src.__support.OSUtil.linux.network_syscall_policy
     libc.src.__support.common
+    libc.src.__support.error_or
     libc.src.__support.libc_errno
     libc.src.__support.macros.config
+    libc.src.__support.macros.null_check
     libc.src.errno.errno
 )

diff  --git a/libc/src/ifaddrs/linux/freeifaddrs.cpp b/libc/src/ifaddrs/linux/freeifaddrs.cpp
index 81ebf2f26f63d7..ca1bd6df683224 100644
--- a/libc/src/ifaddrs/linux/freeifaddrs.cpp
+++ b/libc/src/ifaddrs/linux/freeifaddrs.cpp
@@ -12,15 +12,18 @@
 //===----------------------------------------------------------------------===//
 
 #include "src/ifaddrs/freeifaddrs.h"
+#include "hdr/stdint_proxy.h"
 #include "hdr/types/struct_ifaddrs.h"
+#include "src/__support/CPP/new.h"
 #include "src/__support/common.h"
 #include "src/__support/macros/config.h"
 
 namespace LIBC_NAMESPACE_DECL {
 
-LLVM_LIBC_FUNCTION(void, freeifaddrs, ([[maybe_unused]] struct ifaddrs * ifa)) {
-  // TODO: Implement freeifaddrs.
-  return;
+LLVM_LIBC_FUNCTION(void, freeifaddrs, (struct ifaddrs * ifa)) {
+  // ifa was allocated in net::getifaddrs() as a single contiguous uint8_t[]
+  // buffer holding all the list elements and the data they point to.
+  delete[] reinterpret_cast<uint8_t *>(ifa);
 }
 
 } // namespace LIBC_NAMESPACE_DECL

diff  --git a/libc/src/ifaddrs/linux/getifaddrs.cpp b/libc/src/ifaddrs/linux/getifaddrs.cpp
index e1f2ccb804e3a3..65742a9f1eea95 100644
--- a/libc/src/ifaddrs/linux/getifaddrs.cpp
+++ b/libc/src/ifaddrs/linux/getifaddrs.cpp
@@ -12,18 +12,27 @@
 //===----------------------------------------------------------------------===//
 
 #include "src/ifaddrs/getifaddrs.h"
-#include "hdr/errno_macros.h"
 #include "hdr/types/struct_ifaddrs.h"
+#include "src/__support/OSUtil/linux/network_syscall_policy.h"
 #include "src/__support/common.h"
+#include "src/__support/error_or.h"
 #include "src/__support/libc_errno.h"
 #include "src/__support/macros/config.h"
+#include "src/__support/macros/null_check.h"
+#include "src/ifaddrs/linux/getifaddrs_impl.h"
 
 namespace LIBC_NAMESPACE_DECL {
 
-LLVM_LIBC_FUNCTION(int, getifaddrs, ([[maybe_unused]] struct ifaddrs * *ifap)) {
-  // TODO: Implement getifaddrs.
-  libc_errno = ENOSYS;
-  return -1;
+LLVM_LIBC_FUNCTION(int, getifaddrs, (struct ifaddrs * *ifap)) {
+  LIBC_CRASH_ON_NULLPTR(ifap);
+  ErrorOr<struct ifaddrs *> result =
+      net::getifaddrs<net::DefaultNetworkSyscallPolicy>();
+  if (!result.has_value()) {
+    libc_errno = result.error();
+    return -1;
+  }
+  *ifap = *result;
+  return 0;
 }
 
 } // namespace LIBC_NAMESPACE_DECL

diff  --git a/libc/src/ifaddrs/linux/getifaddrs_impl.h b/libc/src/ifaddrs/linux/getifaddrs_impl.h
new file mode 100644
index 00000000000000..6a3d8795407cc4
--- /dev/null
+++ b/libc/src/ifaddrs/linux/getifaddrs_impl.h
@@ -0,0 +1,232 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Internal templatized implementation of getifaddrs for Linux.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_IFADDRS_LINUX_GETIFADDRS_IMPL_H
+#define LLVM_LIBC_SRC_IFADDRS_LINUX_GETIFADDRS_IMPL_H
+
+#include "hdr/errno_macros.h"
+#include "hdr/net_if_macros.h"
+#include "hdr/offsetof_macros.h"
+#include "hdr/stdint_proxy.h"
+#include "hdr/sys_socket_macros.h"
+#include "hdr/types/sa_family_t.h"
+#include "hdr/types/struct_ifaddrs.h"
+#include "hdr/types/struct_sockaddr.h"
+#include "src/__support/CPP/scope.h"
+#include "src/__support/CPP/span.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/blockstore.h"
+#include "src/__support/checked_ptr.h"
+#include "src/__support/common.h"
+#include "src/__support/error_or.h"
+#include "src/__support/math_extras.h"
+#include "src/__support/net/linux/netlink.h"
+#include "src/string/memory_utils/inline_memcpy.h"
+
+#include <linux/if_link.h>
+#include <linux/if_packet.h>
+#include <linux/netdevice.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+
+namespace LIBC_NAMESPACE_DECL {
+namespace net {
+
+namespace detail {
+
+/// Like struct sockaddr_ll, but with room for the largest hardware address
+/// supported by the kernel (MAX_ADDR_LEN = 32), rather than the eight bytes in
+/// sockaddr_ll (e.g. InfiniBand addresses have 20).
+struct __attribute__((may_alias)) SockAddrLL {
+  sa_family_t sll_family;
+  uint16_t sll_protocol;
+  int sll_ifindex;
+  unsigned short sll_hatype;
+  unsigned char sll_pkttype;
+  unsigned char sll_halen;
+  unsigned char sll_addr[MAX_ADDR_LEN];
+};
+static_assert(offsetof(SockAddrLL, sll_family) ==
+              offsetof(struct sockaddr_ll, sll_family));
+static_assert(offsetof(SockAddrLL, sll_ifindex) ==
+              offsetof(struct sockaddr_ll, sll_ifindex));
+static_assert(offsetof(SockAddrLL, sll_hatype) ==
+              offsetof(struct sockaddr_ll, sll_hatype));
+static_assert(offsetof(SockAddrLL, sll_halen) ==
+              offsetof(struct sockaddr_ll, sll_halen));
+static_assert(offsetof(SockAddrLL, sll_addr) ==
+              offsetof(struct sockaddr_ll, sll_addr));
+
+/// Storage for the addresses we return.
+union SockAddrStorage {
+  struct sockaddr sa;
+  SockAddrLL ll;
+};
+
+/// The data of a single element of the list. Addresses with sa_family ==
+/// AF_UNSPEC are not present.
+struct IfAddrsEntry {
+  unsigned int index;
+  unsigned int flags;
+  SockAddrStorage addr;
+  SockAddrStorage netmask;
+  SockAddrStorage ifu; // The broadcast or point-to-point destination address.
+  char name[IF_NAMESIZE];
+};
+
+using IfAddrsStore = BlockStore<IfAddrsEntry, 4>;
+
+/// A single element of the list we return. The pointers in `ifa` point into
+/// `entry`. `ifa` must be the first member so `&nodes[0].ifa` points to the
+/// start of the uint8_t[] buffer freed by freeifaddrs.
+struct IfAddrsNode {
+  struct ifaddrs ifa;
+  IfAddrsEntry entry;
+};
+static_assert(offsetof(IfAddrsNode, ifa) == 0);
+static_assert(alignof(IfAddrsNode) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__);
+
+/// Stores the hardware address from an IFLA_ADDRESS or IFLA_BROADCAST
+/// attribute in `dst`, unless it is too long.
+LIBC_INLINE void set_link_address(SockAddrStorage &dst,
+                                  const struct ifinfomsg &ifm,
+                                  cpp::span<const uint8_t> addr) {
+  if (addr.size() > sizeof(dst.ll.sll_addr))
+    return;
+  dst.ll = {};
+  dst.ll.sll_family = AF_PACKET;
+  dst.ll.sll_ifindex = ifm.ifi_index;
+  dst.ll.sll_hatype = ifm.ifi_type;
+  dst.ll.sll_halen = static_cast<unsigned char>(addr.size());
+  if (!addr.empty())
+    inline_memcpy(dst.ll.sll_addr, addr.data(), addr.size());
+}
+
+/// Adds an (AF_PACKET) entry for the interface described by an RTM_NEWLINK
+/// message.
+LIBC_INLINE ErrorOr<void> add_link(struct nlmsghdr &nh, IfAddrsStore &store) {
+  auto *ifm = get_nlmsg_header<struct ifinfomsg>(nh);
+  if (!ifm)
+    return {};
+
+  IfAddrsEntry entry = {};
+  entry.index = static_cast<unsigned int>(ifm->ifi_index);
+  entry.flags = ifm->ifi_flags;
+  bool has_name = false;
+  for_each_rtattr(IFLA_RTA(ifm), IFLA_PAYLOAD(&nh),
+                  [&](unsigned short type, cpp::span<const uint8_t> payload) {
+                    switch (type) {
+                    case IFLA_IFNAME: {
+                      cpp::string_view name = parse_ifname(payload);
+                      inline_memcpy(entry.name, name.data(), name.size());
+                      entry.name[name.size()] = '\0';
+                      has_name = true;
+                      break;
+                    }
+                    case IFLA_ADDRESS:
+                      set_link_address(entry.addr, *ifm, payload);
+                      break;
+                    case IFLA_BROADCAST:
+                      set_link_address(entry.ifu, *ifm, payload);
+                      break;
+                    }
+                  });
+  // The kernel always sends the name, but if it didn't, we would have nothing
+  // to put into ifa_name.
+  if (!has_name)
+    return {};
+
+  if (!store.push_back(entry))
+    return Error(ENOMEM);
+  return {};
+}
+
+LIBC_INLINE struct sockaddr *get_sockaddr(SockAddrStorage &addr) {
+  return addr.sa.sa_family == AF_UNSPEC ? nullptr : &addr.sa;
+}
+
+/// Copies the entries into a single allocation, which freeifaddrs can free
+/// with a single delete[].
+LIBC_INLINE ErrorOr<struct ifaddrs *> build_ifaddrs_list(IfAddrsStore &store) {
+  size_t count = 0;
+  for ([[maybe_unused]] const IfAddrsEntry &entry : store)
+    ++count;
+  if (count == 0)
+    return nullptr;
+
+  size_t alloc_size;
+  if (mul_overflow(count, sizeof(IfAddrsNode), alloc_size))
+    return Error(ENOMEM);
+
+  // Allocate as uint8_t[] rather than IfAddrsNode[] to match the
+  // delete[] reinterpret_cast<uint8_t *>(ifa) in freeifaddrs.
+  CheckedPtr<uint8_t[]> buffer =
+      make_unique_for_overwrite<uint8_t[]>(alloc_size);
+  if (!buffer)
+    return Error(ENOMEM);
+
+  uint8_t *raw_nodes = buffer.get();
+  IfAddrsNode *prev_node = nullptr;
+  for (const IfAddrsEntry &entry : store) {
+    auto *node = ::new (raw_nodes) IfAddrsNode;
+    raw_nodes += sizeof(IfAddrsNode);
+
+    if (prev_node)
+      prev_node->ifa.ifa_next = &node->ifa;
+    prev_node = node;
+
+    node->entry = entry;
+    node->ifa.ifa_next = nullptr;
+    node->ifa.ifa_name = node->entry.name;
+    node->ifa.ifa_flags = entry.flags;
+    node->ifa.ifa_addr = get_sockaddr(node->entry.addr);
+    node->ifa.ifa_netmask = get_sockaddr(node->entry.netmask);
+    node->ifa.ifa_broadaddr = get_sockaddr(node->entry.ifu);
+    node->ifa.ifa_data = nullptr;
+  }
+  return reinterpret_cast<struct ifaddrs *>(buffer.release());
+}
+
+} // namespace detail
+
+template <typename Policy> LIBC_INLINE ErrorOr<struct ifaddrs *> getifaddrs() {
+  NetlinkSocket<Policy> sock;
+  if (ErrorOr<void> res = sock.open(); !res.has_value())
+    return Error(res.error());
+
+  // If the data changes while the kernel is sending it to us, the result may
+  // be inconsistent. In that case, we throw it away and try again.
+  for (size_t attempt = 0; attempt < MAX_DUMP_ATTEMPTS; ++attempt) {
+    detail::IfAddrsStore store;
+    cpp::scope_exit destroy_store(
+        [&store]() { detail::IfAddrsStore::destroy(&store); });
+
+    ErrorOr<DumpResult> res = sock.dump(
+        RTM_GETLINK, ifinfomsg{}, RTM_NEWLINK,
+        [&store](struct nlmsghdr &nh) { return detail::add_link(nh, store); });
+    if (!res.has_value())
+      return Error(res.error());
+    if (*res == DumpResult::Interrupted)
+      continue;
+
+    if (ErrorOr<void> close_res = sock.close(); !close_res.has_value())
+      return Error(close_res.error());
+    return detail::build_ifaddrs_list(store);
+  }
+  return Error(EAGAIN);
+}
+
+} // namespace net
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC_IFADDRS_LINUX_GETIFADDRS_IMPL_H

diff  --git a/libc/test/src/__support/net/linux/netlink_test_support.h b/libc/test/src/__support/net/linux/netlink_test_support.h
index 0bd42b3013c9a3..076935fed045e3 100644
--- a/libc/test/src/__support/net/linux/netlink_test_support.h
+++ b/libc/test/src/__support/net/linux/netlink_test_support.h
@@ -123,6 +123,16 @@ template <uint16_t ATTR_TYPE> struct AttrInt {
   static constexpr uint16_t TYPE = ATTR_TYPE;
 };
 
+template <uint16_t ATTR_TYPE> struct AttrBytes {
+  cpp::span<const uint8_t> value;
+  size_t payload_len() const { return value.size(); }
+  void write(uint8_t *dest) const {
+    if (!value.empty())
+      inline_memcpy(dest, value.data(), value.size());
+  }
+  static constexpr uint16_t TYPE = ATTR_TYPE;
+};
+
 /// Writes a netlink message of the given type, consisting of the fixed-size
 /// header (e.g. struct ifinfomsg) followed by the attributes, into the buffer.
 /// Returns the length of the message.

diff  --git a/libc/test/src/ifaddrs/linux/CMakeLists.txt b/libc/test/src/ifaddrs/linux/CMakeLists.txt
index c5dfc051d4c278..c08f79d50e694a 100644
--- a/libc/test/src/ifaddrs/linux/CMakeLists.txt
+++ b/libc/test/src/ifaddrs/linux/CMakeLists.txt
@@ -6,10 +6,25 @@ add_libc_test(
     getifaddrs_test.cpp
   DEPENDS
     libc.hdr.errno_macros
+    libc.hdr.stdint_proxy
+    libc.hdr.sys_resource_macros
+    libc.hdr.sys_socket_macros
+    libc.hdr.types.sa_family_t
     libc.hdr.types.struct_ifaddrs
+    libc.hdr.types.struct_rlimit
     libc.hdr.types.struct_sockaddr
+    libc.src.__support.CPP.scope
+    libc.src.__support.CPP.span
+    libc.src.__support.CPP.string_view
+    libc.src.__support.CPP.tuple
+    libc.src.__support.error_or
+    libc.src.__support.net.linux.netlink
     libc.src.ifaddrs.freeifaddrs
     libc.src.ifaddrs.getifaddrs
+    libc.src.ifaddrs.linux.getifaddrs_impl
+    libc.src.sys.resource.getrlimit
+    libc.src.sys.resource.setrlimit
+    libc.test.src.__support.net.linux.netlink_test_support
     libc.test.UnitTest.ErrnoCheckingTest
     libc.test.UnitTest.ErrnoSetterMatcher
 )

diff  --git a/libc/test/src/ifaddrs/linux/getifaddrs_test.cpp b/libc/test/src/ifaddrs/linux/getifaddrs_test.cpp
index b65b3aef8d012d..83246e3e997490 100644
--- a/libc/test/src/ifaddrs/linux/getifaddrs_test.cpp
+++ b/libc/test/src/ifaddrs/linux/getifaddrs_test.cpp
@@ -12,22 +12,440 @@
 //===----------------------------------------------------------------------===//
 
 #include "hdr/errno_macros.h"
+#include "hdr/stdint_proxy.h"
+#include "hdr/sys_resource_macros.h"
+#include "hdr/sys_socket_macros.h"
+#include "hdr/types/sa_family_t.h"
 #include "hdr/types/struct_ifaddrs.h"
+#include "hdr/types/struct_rlimit.h"
 #include "hdr/types/struct_sockaddr.h"
+#include "src/__support/CPP/scope.h"
+#include "src/__support/CPP/span.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/CPP/tuple.h"
+#include "src/__support/error_or.h"
+#include "src/__support/net/linux/netlink.h"
 #include "src/ifaddrs/freeifaddrs.h"
 #include "src/ifaddrs/getifaddrs.h"
+#include "src/ifaddrs/linux/getifaddrs_impl.h"
+#include "src/sys/resource/getrlimit.h"
+#include "src/sys/resource/setrlimit.h"
 #include "test/UnitTest/ErrnoCheckingTest.h"
 #include "test/UnitTest/ErrnoSetterMatcher.h"
 #include "test/UnitTest/Test.h"
+#include "test/src/__support/net/linux/netlink_test_support.h"
+
+#include <linux/if_link.h>
+#include <linux/if_packet.h>
+#include <linux/netdevice.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
 
 using namespace LIBC_NAMESPACE::testing::ErrnoSetterMatcher;
-using LlvmLibcGetifaddrsTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;
+using LIBC_NAMESPACE::Error;
+using LIBC_NAMESPACE::cpp::get;
+using LIBC_NAMESPACE::cpp::span;
+using LIBC_NAMESPACE::cpp::string_view;
+using LIBC_NAMESPACE::net::MAX_DUMP_ATTEMPTS;
+using LIBC_NAMESPACE::net::detail::SockAddrLL;
+using LIBC_NAMESPACE::testing::AttrBytes;
+using LIBC_NAMESPACE::testing::AttrString;
+using LIBC_NAMESPACE::testing::build_generic_nlmsg_packet;
+using LIBC_NAMESPACE::testing::build_nlmsg_done_packet;
+using LIBC_NAMESPACE::testing::build_nlmsg_packet;
+using LIBC_NAMESPACE::testing::FakeNetworkSyscallPolicy;
+using LIBC_NAMESPACE::testing::FakeNetworkSyscallPolicyData;
+using LIBC_NAMESPACE::testing::mark_interrupted;
+
+namespace {
+
+// Hardware types (ARPHRD_*) and interface flags (IFF_*). We just check that
+// these get passed through, so their meaning is not important.
+constexpr unsigned short HW_TYPE_ETHER = 1;
+constexpr unsigned short HW_TYPE_INFINIBAND = 32;
+constexpr unsigned short HW_TYPE_NONE = 65534;
+constexpr unsigned int FLAGS_ETH = 0x11043;
+constexpr unsigned int FLAGS_LO = 0x10049;
+constexpr unsigned int FLAGS_WG = 0x91;
+
+using AttrName = AttrString<IFLA_IFNAME>;
+using AttrAddress = AttrBytes<IFLA_ADDRESS>;
+using AttrBroadcast = AttrBytes<IFLA_BROADCAST>;
+
+constexpr uint8_t ETH0_ADDR[] = {0x02, 0x42, 0xac, 0x11, 0x00, 0x02};
+constexpr uint8_t ETH_BROADCAST[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
+constexpr uint8_t LO_ADDR[] = {0, 0, 0, 0, 0, 0};
+
+struct LlvmLibcGetIfAddrsTest
+    : public LIBC_NAMESPACE::testing::ErrnoCheckingTest {
+  static constexpr int FAKE_SOCKET = 47;
+  static FakeNetworkSyscallPolicyData policy_data;
+  using Policy = FakeNetworkSyscallPolicy<&policy_data>;
+
+  void SetUp() override {
+    ErrnoCheckingTest::SetUp();
+    policy_data = {};
+  }
+};
+
+struct LlvmLibcGetIfAddrsSocketTest : public LlvmLibcGetIfAddrsTest {
+  void SetUp() override {
+    LlvmLibcGetIfAddrsTest::SetUp();
+    policy_data.socket_results.push_back(FAKE_SOCKET);
+  }
+
+  void TearDown() override {
+    ASSERT_EQ(policy_data.socket_calls.size(), size_t(1));
+    ASSERT_EQ(get<0>(policy_data.socket_calls[0]), AF_NETLINK);
+    ASSERT_EQ(get<1>(policy_data.socket_calls[0]), SOCK_RAW | SOCK_CLOEXEC);
+    ASSERT_EQ(get<2>(policy_data.socket_calls[0]), NETLINK_ROUTE);
+
+    ASSERT_EQ(policy_data.close_calls.size(), size_t(1));
+    ASSERT_EQ(policy_data.close_calls[0], FAKE_SOCKET);
+    ASSERT_TRUE(policy_data.sendto_results.empty());
+    ASSERT_TRUE(policy_data.recv_results.empty());
+    LlvmLibcGetIfAddrsTest::TearDown();
+  }
+
+  /// Checks that we sent the expected number of RTM_GETLINK requests.
+  void validate_link_requests(size_t num_requests = 1) {
+    constexpr size_t REQUEST_LEN =
+        static_cast<size_t>(NLMSG_LENGTH(sizeof(ifinfomsg)));
+    ASSERT_EQ(policy_data.sendto_calls.size(), num_requests);
+    ASSERT_EQ(policy_data.sendto_data.size(), num_requests * REQUEST_LEN);
+    for (size_t i = 0; i < num_requests; ++i) {
+      ASSERT_EQ(get<0>(policy_data.sendto_calls[i]), FAKE_SOCKET);
+      auto *nlh = reinterpret_cast<struct nlmsghdr *>(
+          policy_data.sendto_data.data() + i * REQUEST_LEN);
+      ASSERT_EQ(nlh->nlmsg_len, static_cast<uint32_t>(REQUEST_LEN));
+      ASSERT_EQ(nlh->nlmsg_type, static_cast<uint16_t>(RTM_GETLINK));
+      ASSERT_EQ(nlh->nlmsg_flags,
+                static_cast<uint16_t>(NLM_F_REQUEST | NLM_F_DUMP));
+      auto *ifm = reinterpret_cast<struct ifinfomsg *>(NLMSG_DATA(nlh));
+      ASSERT_EQ(ifm->ifi_family, static_cast<unsigned char>(AF_UNSPEC));
+    }
+  }
+};
+
+} // namespace
+
+FakeNetworkSyscallPolicyData LlvmLibcGetIfAddrsTest::policy_data;
+
+template <typename... Attrs>
+static size_t build_link_packet(uint8_t *buf, int index, unsigned int flags,
+                                unsigned short type, const Attrs &...attrs) {
+  struct ifinfomsg ifm = {};
+  ifm.ifi_family = AF_UNSPEC;
+  ifm.ifi_type = type;
+  ifm.ifi_index = index;
+  ifm.ifi_flags = flags;
+  return build_nlmsg_packet(buf, RTM_NEWLINK, ifm, attrs...);
+}
+
+static string_view as_string_view(span<const uint8_t> bytes) {
+  return string_view(reinterpret_cast<const char *>(bytes.data()),
+                     bytes.size());
+}
+
+/// Returns the hardware address stored in an AF_PACKET address.
+static string_view get_link_address(const struct sockaddr *addr) {
+  auto *ll = reinterpret_cast<const SockAddrLL *>(addr);
+  return string_view(reinterpret_cast<const char *>(ll->sll_addr),
+                     ll->sll_halen);
+}
+
+TEST_F(LlvmLibcGetIfAddrsTest, SocketCreationFailure) {
+  policy_data.socket_results.push_back(Error(EMFILE));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_FALSE(res.has_value());
+  ASSERT_EQ(res.error(), EMFILE);
+  ASSERT_EQ(policy_data.close_calls.size(), size_t(0));
+}
+
+TEST_F(LlvmLibcGetIfAddrsSocketTest, SendFailure) {
+  policy_data.sendto_results.push_back(Error(ENOBUFS));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_FALSE(res.has_value());
+  ASSERT_EQ(res.error(), ENOBUFS);
+  validate_link_requests();
+}
+
+TEST_F(LlvmLibcGetIfAddrsSocketTest, RecvFailure) {
+  policy_data.recv_results.push_back(Error(EINTR));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_FALSE(res.has_value());
+  ASSERT_EQ(res.error(), EINTR);
+  validate_link_requests();
+}
+
+TEST_F(LlvmLibcGetIfAddrsSocketTest, CloseFailure) {
+  alignas(struct nlmsghdr) uint8_t pkt_buf[1024];
+  size_t len =
+      build_link_packet(pkt_buf, 1, FLAGS_LO, HW_TYPE_ETHER, AttrName{"lo"});
+  len += build_nlmsg_done_packet(pkt_buf + len);
+  policy_data.recv_results.push_back(span<const uint8_t>(pkt_buf, len));
+  policy_data.close_results.push_back(Error(EIO));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_FALSE(res.has_value());
+  ASSERT_EQ(res.error(), EIO);
+  validate_link_requests();
+}
+
+TEST_F(LlvmLibcGetIfAddrsSocketTest, NoInterfaces) {
+  alignas(struct nlmsghdr) uint8_t pkt_buf[128];
+  size_t len = build_nlmsg_done_packet(pkt_buf);
+  policy_data.recv_results.push_back(span<const uint8_t>(pkt_buf, len));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_TRUE(res.has_value());
+  ASSERT_EQ(*res, static_cast<struct ifaddrs *>(nullptr));
+  validate_link_requests();
+}
+
+TEST_F(LlvmLibcGetIfAddrsSocketTest, SingleInterface) {
+  alignas(struct nlmsghdr) uint8_t pkt_buf[1024];
+  size_t len =
+      build_link_packet(pkt_buf, 2, FLAGS_ETH, HW_TYPE_ETHER, AttrName{"eth0"},
+                        AttrAddress{ETH0_ADDR}, AttrBroadcast{ETH_BROADCAST});
+  len += build_nlmsg_done_packet(pkt_buf + len);
+  policy_data.recv_results.push_back(span<const uint8_t>(pkt_buf, len));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_TRUE(res.has_value());
+  struct ifaddrs *list = *res;
+  ASSERT_NE(list, static_cast<struct ifaddrs *>(nullptr));
+
+  ASSERT_STREQ(list->ifa_name, "eth0");
+  ASSERT_EQ(list->ifa_flags, FLAGS_ETH);
+  ASSERT_NE(list->ifa_addr, static_cast<struct sockaddr *>(nullptr));
+  auto *ll = reinterpret_cast<struct sockaddr_ll *>(list->ifa_addr);
+  ASSERT_EQ(ll->sll_family, static_cast<unsigned short>(AF_PACKET));
+  ASSERT_EQ(ll->sll_ifindex, 2);
+  ASSERT_EQ(ll->sll_hatype, HW_TYPE_ETHER);
+  ASSERT_EQ(get_link_address(list->ifa_addr), as_string_view(ETH0_ADDR));
+  ASSERT_EQ(list->ifa_netmask, static_cast<struct sockaddr *>(nullptr));
+  ASSERT_NE(list->ifa_broadaddr, static_cast<struct sockaddr *>(nullptr));
+  ASSERT_EQ(list->ifa_broadaddr->sa_family,
+            static_cast<sa_family_t>(AF_PACKET));
+  ASSERT_EQ(get_link_address(list->ifa_broadaddr),
+            as_string_view(ETH_BROADCAST));
+  ASSERT_EQ(list->ifa_data, static_cast<void *>(nullptr));
+  ASSERT_EQ(list->ifa_next, static_cast<struct ifaddrs *>(nullptr));
+
+  validate_link_requests();
+  LIBC_NAMESPACE::freeifaddrs(list);
+}
+
+TEST_F(LlvmLibcGetIfAddrsSocketTest, MultipleInterfaces) {
+  alignas(struct nlmsghdr) uint8_t pkt_buf[2048];
+  size_t len1 =
+      build_link_packet(pkt_buf, 1, FLAGS_LO, HW_TYPE_ETHER, AttrName{"lo"},
+                        AttrAddress{LO_ADDR}, AttrBroadcast{LO_ADDR});
+  len1 += build_link_packet(pkt_buf + len1, 2, FLAGS_ETH, HW_TYPE_ETHER,
+                            AttrName{"eth0"}, AttrAddress{ETH0_ADDR},
+                            AttrBroadcast{ETH_BROADCAST});
+  // Interfaces without a hardware address (e.g. wireguard) don't get the
+  // address attributes.
+  size_t len2 = build_link_packet(pkt_buf + len1, 3, FLAGS_WG, HW_TYPE_NONE,
+                                  AttrName{"wg0"});
+  len2 += build_nlmsg_done_packet(pkt_buf + len1 + len2);
 
-TEST_F(LlvmLibcGetifaddrsTest, GetIfAddrsReturnsEnosys) {
-  struct ifaddrs *ifap = nullptr;
-  ASSERT_THAT(LIBC_NAMESPACE::getifaddrs(&ifap), Fails(ENOSYS));
-  EXPECT_EQ(ifap, nullptr);
+  policy_data.recv_results.push_back(span<const uint8_t>(pkt_buf, len1));
+  policy_data.recv_results.push_back(span<const uint8_t>(pkt_buf + len1, len2));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_TRUE(res.has_value());
+  struct ifaddrs *list = *res;
+
+  struct ifaddrs *ifa = list;
+  ASSERT_NE(ifa, static_cast<struct ifaddrs *>(nullptr));
+  ASSERT_STREQ(ifa->ifa_name, "lo");
+  ASSERT_EQ(ifa->ifa_flags, FLAGS_LO);
+  ASSERT_NE(ifa->ifa_addr, static_cast<struct sockaddr *>(nullptr));
+  ASSERT_EQ(get_link_address(ifa->ifa_addr), as_string_view(LO_ADDR));
+
+  ifa = ifa->ifa_next;
+  ASSERT_NE(ifa, static_cast<struct ifaddrs *>(nullptr));
+  ASSERT_STREQ(ifa->ifa_name, "eth0");
+  ASSERT_EQ(ifa->ifa_flags, FLAGS_ETH);
+  ASSERT_NE(ifa->ifa_addr, static_cast<struct sockaddr *>(nullptr));
+  ASSERT_EQ(get_link_address(ifa->ifa_addr), as_string_view(ETH0_ADDR));
+
+  ifa = ifa->ifa_next;
+  ASSERT_NE(ifa, static_cast<struct ifaddrs *>(nullptr));
+  ASSERT_STREQ(ifa->ifa_name, "wg0");
+  ASSERT_EQ(ifa->ifa_flags, FLAGS_WG);
+  ASSERT_EQ(ifa->ifa_addr, static_cast<struct sockaddr *>(nullptr));
+  ASSERT_EQ(ifa->ifa_broadaddr, static_cast<struct sockaddr *>(nullptr));
+
+  ASSERT_EQ(ifa->ifa_next, static_cast<struct ifaddrs *>(nullptr));
+
+  validate_link_requests();
+  ASSERT_EQ(policy_data.recv_calls.size(), size_t(2));
+  LIBC_NAMESPACE::freeifaddrs(list);
+}
+
+TEST_F(LlvmLibcGetIfAddrsSocketTest, LongHardwareAddresses) {
+  // SockAddrLL has room for up to MAX_ADDR_LEN (32) bytes (covering e.g.
+  // 20-byte InfiniBand addresses), which doesn't fit into sockaddr_ll. Anything
+  // longer is ignored.
+  uint8_t max_addr[MAX_ADDR_LEN];
+  uint8_t too_long_addr[MAX_ADDR_LEN + 1];
+  for (size_t i = 0; i < sizeof(too_long_addr); ++i) {
+    too_long_addr[i] = static_cast<uint8_t>(i);
+    if (i < sizeof(max_addr))
+      max_addr[i] = static_cast<uint8_t>(0x80 + i);
+  }
+  alignas(struct nlmsghdr) uint8_t pkt_buf[1024];
+  size_t len = build_link_packet(pkt_buf, 4, FLAGS_ETH, HW_TYPE_INFINIBAND,
+                                 AttrName{"ib0"}, AttrAddress{max_addr},
+                                 AttrBroadcast{too_long_addr});
+  len += build_nlmsg_done_packet(pkt_buf + len);
+  policy_data.recv_results.push_back(span<const uint8_t>(pkt_buf, len));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_TRUE(res.has_value());
+  struct ifaddrs *list = *res;
+  ASSERT_NE(list, static_cast<struct ifaddrs *>(nullptr));
+
+  ASSERT_STREQ(list->ifa_name, "ib0");
+  ASSERT_NE(list->ifa_addr, static_cast<struct sockaddr *>(nullptr));
+  auto *ll = reinterpret_cast<const SockAddrLL *>(list->ifa_addr);
+  ASSERT_EQ(ll->sll_hatype, HW_TYPE_INFINIBAND);
+  ASSERT_EQ(get_link_address(list->ifa_addr), as_string_view(max_addr));
+  ASSERT_EQ(list->ifa_broadaddr, static_cast<struct sockaddr *>(nullptr));
+
+  validate_link_requests();
+  LIBC_NAMESPACE::freeifaddrs(list);
+}
+
+TEST_F(LlvmLibcGetIfAddrsSocketTest, InterfaceWithoutName) {
+  alignas(struct nlmsghdr) uint8_t pkt_buf[1024];
+  size_t len = build_link_packet(pkt_buf, 1, FLAGS_ETH, HW_TYPE_ETHER,
+                                 AttrAddress{ETH0_ADDR});
+  len += build_link_packet(pkt_buf + len, 2, FLAGS_ETH, HW_TYPE_ETHER,
+                           AttrName{"eth1"});
+  len += build_nlmsg_done_packet(pkt_buf + len);
+  policy_data.recv_results.push_back(span<const uint8_t>(pkt_buf, len));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_TRUE(res.has_value());
+  struct ifaddrs *list = *res;
+  ASSERT_NE(list, static_cast<struct ifaddrs *>(nullptr));
+  ASSERT_STREQ(list->ifa_name, "eth1");
+  ASSERT_EQ(list->ifa_next, static_cast<struct ifaddrs *>(nullptr));
+
+  validate_link_requests();
+  LIBC_NAMESPACE::freeifaddrs(list);
+}
+
+TEST_F(LlvmLibcGetIfAddrsSocketTest, TruncatedIfInfoMsgPacket) {
+  alignas(struct nlmsghdr) uint8_t pkt_buf[1024];
+  size_t len = build_generic_nlmsg_packet(pkt_buf, RTM_NEWLINK);
+  len += build_link_packet(pkt_buf + len, 2, FLAGS_ETH, HW_TYPE_ETHER,
+                           AttrName{"eth0"});
+  len += build_nlmsg_done_packet(pkt_buf + len);
+  policy_data.recv_results.push_back(span<const uint8_t>(pkt_buf, len));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_TRUE(res.has_value());
+  struct ifaddrs *list = *res;
+  ASSERT_NE(list, static_cast<struct ifaddrs *>(nullptr));
+  ASSERT_STREQ(list->ifa_name, "eth0");
+  ASSERT_EQ(list->ifa_next, static_cast<struct ifaddrs *>(nullptr));
+
+  validate_link_requests();
+  LIBC_NAMESPACE::freeifaddrs(list);
+}
+
+TEST_F(LlvmLibcGetIfAddrsSocketTest, InterruptedDump) {
+  alignas(struct nlmsghdr) uint8_t pkt_buf1[1024];
+  size_t len1 = build_link_packet(pkt_buf1, 2, FLAGS_ETH, HW_TYPE_ETHER,
+                                  AttrName{"old0"});
+  mark_interrupted(pkt_buf1);
+  len1 += build_nlmsg_done_packet(pkt_buf1 + len1);
+  alignas(struct nlmsghdr) uint8_t pkt_buf2[1024];
+  size_t len2 = build_link_packet(pkt_buf2, 3, FLAGS_ETH, HW_TYPE_ETHER,
+                                  AttrName{"new0"});
+  len2 += build_nlmsg_done_packet(pkt_buf2 + len2);
+
+  policy_data.recv_results.push_back(span<const uint8_t>(pkt_buf1, len1));
+  policy_data.recv_results.push_back(span<const uint8_t>(pkt_buf2, len2));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_TRUE(res.has_value());
+  struct ifaddrs *list = *res;
+  ASSERT_NE(list, static_cast<struct ifaddrs *>(nullptr));
+  ASSERT_STREQ(list->ifa_name, "new0");
+  ASSERT_EQ(list->ifa_next, static_cast<struct ifaddrs *>(nullptr));
+
+  validate_link_requests(2);
+  LIBC_NAMESPACE::freeifaddrs(list);
+}
+
+TEST_F(LlvmLibcGetIfAddrsSocketTest, TooManyInterruptions) {
+  alignas(struct nlmsghdr) uint8_t pkt_buf[1024];
+  size_t len =
+      build_link_packet(pkt_buf, 1, FLAGS_LO, HW_TYPE_ETHER, AttrName{"lo"});
+  mark_interrupted(pkt_buf);
+  len += build_nlmsg_done_packet(pkt_buf + len);
+  for (size_t i = 0; i < MAX_DUMP_ATTEMPTS; ++i)
+    policy_data.recv_results.push_back(span<const uint8_t>(pkt_buf, len));
+
+  auto res = LIBC_NAMESPACE::net::getifaddrs<Policy>();
+  ASSERT_FALSE(res.has_value());
+  ASSERT_EQ(res.error(), EAGAIN);
+  validate_link_requests(MAX_DUMP_ATTEMPTS);
+}
+
+using LlvmLibcGetIfAddrsLiveTest = LIBC_NAMESPACE::testing::ErrnoCheckingTest;
+
+TEST_F(LlvmLibcGetIfAddrsLiveTest, LiveOSIntegration) {
+  struct ifaddrs *list = nullptr;
+  ASSERT_THAT(LIBC_NAMESPACE::getifaddrs(&list), Succeeds(0));
+
+  bool found_lo = false;
+  for (struct ifaddrs *ifa = list; ifa; ifa = ifa->ifa_next) {
+    ASSERT_NE(ifa->ifa_name, static_cast<char *>(nullptr));
+    if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_PACKET &&
+        string_view(ifa->ifa_name) == "lo")
+      found_lo = true;
+  }
+  // Every network namespace has a loopback interface.
+  ASSERT_TRUE(found_lo);
+
+  LIBC_NAMESPACE::freeifaddrs(list);
+}
+
+TEST_F(LlvmLibcGetIfAddrsLiveTest, EntrypointFailure) {
+  struct rlimit orig_limits;
+  ASSERT_THAT(LIBC_NAMESPACE::getrlimit(RLIMIT_NOFILE, &orig_limits),
+              Succeeds(0));
+  LIBC_NAMESPACE::cpp::scope_exit restore_limits([&] {
+    EXPECT_THAT(LIBC_NAMESPACE::setrlimit(RLIMIT_NOFILE, &orig_limits),
+                Succeeds(0));
+  });
+
+  struct rlimit zero_limits = {0, orig_limits.rlim_max};
+  ASSERT_THAT(LIBC_NAMESPACE::setrlimit(RLIMIT_NOFILE, &zero_limits),
+              Succeeds(0));
+
+  struct ifaddrs sentinel = {};
+  struct ifaddrs *list = &sentinel;
+  ASSERT_THAT(LIBC_NAMESPACE::getifaddrs(&list), Fails(EMFILE));
+  ASSERT_EQ(list, &sentinel);
+}
+
+TEST_F(LlvmLibcGetIfAddrsLiveTest, FreeNullptr) {
+  LIBC_NAMESPACE::freeifaddrs(nullptr);
+}
 
-  // freeifaddrs should do nothing and not crash.
-  LIBC_NAMESPACE::freeifaddrs(ifap);
+#if defined(LIBC_ADD_NULL_CHECKS)
+TEST_F(LlvmLibcGetIfAddrsLiveTest, NullPtrDeath) {
+  ASSERT_DEATH([]() { LIBC_NAMESPACE::getifaddrs(nullptr); }, WITH_SIGNAL(-1));
 }
+#endif // defined(LIBC_ADD_NULL_CHECKS)


        


More information about the libc-commits mailing list