System.Net.Sockets, System.Net.NameResolution, System.Net.NetworkInformation
A library served from the framework’s IL: its row of the per-library table of ADR 0023 (columns explained there, under “Measurements”).
| Library (switch) | Correctness (samples from IL) | Binary size, IL / shadow | Compile cpu, IL / shadow | Speed, IL / shadow (time) | Lines removed on a flip | Decision | NativeAOT on the same host, csharpc / NativeAOT (tools/il-first/measure-aot.sh: stripped size; compile cpu; run, median of 7; instructions) |
|---|---|---|---|---|---|---|---|
System.Net.Sockets, System.Net.NameResolution (Linux, macOS), System.Net.NetworkInformation (Linux): Socket, NetworkStream, TcpClient, TcpListener, UdpClient, SocketAsyncEventArgs, SafeSocketHandle, UnixDomainSocketEndPoint, Dns, SocketException, NetworkInterface, NetworkChange and the framework’s SocketAsyncEngine (whole assemblies from the shared framework, ADR 0013; no CoreLib slice) |
the 47 networking samples (sockets, async sockets and cancellation, NetworkStream timeouts, Dns, HttpClient over loopback, SslStream, IP addresses and endpoints, network interfaces, SocketException codes and texts, socket stack traces) and the interface samples byte-identical to real .NET at -O0 and -O2 (148 runs), 13 via IL, the address and 1460 samples on wasm32 (the socket ones stay skipped there: WASI preview 1 has no sockets, the contract throws .NET’s PlatformNotSupportedException); tests/slicer.sh 10 of 10. New sample 1460 (interface re-implementation through ((I)this).M()), failing at -O0 and -O2 without the general fix below; 881 failed on the flip until the PAL’s non-errno errors were fixed in the contract |
tests/size/net.cs (no sockets) 330 784 to 332 248 B (+1 464, budget 331 776 to 339 968); the throughput program 933 328 to 1 533 936 B (1.64x: the framework’s socket engine, SocketAsyncEventArgs machinery and the IL’s error and option paths; NativeAOT 2 184 312) |
the throughput program 17.7 to 28.1 s user (NativeAOT publish 18.6 s cpu) | tools/il-first/bench/net_sockets_throughput.cs (100 000 async 64-byte round trips, 512 MiB through NetworkStream, 50 000 sync round trips, 2 000 Dns.GetHostAddresses), median of 9 interleaved runs on a loaded shared host: shadow 21 195 ms, IL 17 353 ms (0.82x); checksum equals real .NET |
on Linux and macOS the socket shadows (about 3 650 lines with their Linux/macOS/WASI branches) are no longer compiled; their non-Windows branches are deleted (737 lines) and the files kept for Windows only (2 915 lines, #441); 2 014 lines added for the contract (Net/SystemNative.Net.cs, Net/SystemNative.NetworkInformation.cs) |
Flipped on Linux and macOS (macOS: CI confirms; NetworkInformation stays the corelib’s there); Windows keeps the shadows (#441); System.Uri stays the corelib’s (#442). General fixes on the way: interface calls on a non-sealed class receiver are not devirtualized when a subclass re-implements the interface (sample 1460; the framework’s SocketAsyncContext relies on it); Thread.UnsafeStart, Environment.HasShutdownStarted; ConvertErrorPalToPlatform/StrErrorR for EHOSTNOTFOUND/ESOCKETERROR and Marshal.GetPInvokeErrorMessage as Interop.Sys.StrError (thread-safe strerror_r); FrameworkIl takes an assembly calling libSystem.Native when the contract exports all it imports. Security: below |
net_sockets_throughput: 1 533 784 / 2 184 312 B; compile cpu 32.7 / 18.6 s; run 17 786 / 29 498 ms (0.60x) |
The socket engine below the framework’s IL (security review)
On Linux and macOS, Socket, NetworkStream, TcpClient, TcpListener, UdpClient, SocketAsyncEventArgs, SafeSocketHandle,
UnixDomainSocketEndPoint, Dns, IPHostEntry and SocketException are the framework’s IL, and so is the framework’s own asynchronous
engine (SocketAsyncEngine, SocketAsyncContext: one event thread, completions on the thread pool, as in .NET). On Linux
NetworkInterface, NetworkChange and the rest of System.Net.NetworkInformation are too. Their Interop.Sys P/Invokes into
libSystem.Native bind to csharpc’s C# contract, corelib/Net/SystemNative.Net.cs and (Linux) corelib/Net/SystemNative.NetworkInformation.cs
(option (b) of 21-ownership.md: csharpc’s own libc layer, not the pack’s shim; the same mechanism as the file system’s
corelib/IO/SystemNative.cs). That contract is csharpc’s socket engine now: epoll on Linux, kqueue on macOS, behind the PAL’s
CreateSocketEventPort/TryChangeSocketEventRegistration/WaitForSocketEvents. It is pal_networking.c, pal_networking_common.h,
pal_io_common.h, pal_interfaceaddresses.c, pal_networkchange.c, pal_maphardwaretype.c and pal_tcpstate.c (dotnet/runtime
release/11.0), function by function. A framework assembly is compiled from IL only when the contract exports every libSystem.Native entry
point it imports (FrameworkIl.ServedByNativeContract): a new one in a later .NET is an explicit “can’t be compiled from IL” diagnostic,
never a silent fallback. What was checked:
- Descriptors are close-on-exec.
socketgetsSOCK_CLOEXEC(Linux) orFD_CLOEXECright after (macOS, as there);acceptisaccept4(SOCK_CLOEXEC)on Linux, and on macOSacceptfollowed byFD_CLOEXECand blocking mode, closing the new descriptor if either fails, as there; the epoll instance isepoll_create1(EPOLL_CLOEXEC). Stronger thanpal_*.cand not observable: the interface list’s helper datagram socket and the netlink change listener getSOCK_CLOEXECtoo (upstream creates them without), and the kqueue getsFD_CLOEXEC. - Bounds on every native write. Socket-address accessors check the length the caller passed against the field they touch (family,
port, IPv4 and IPv6 address, scope) and return
EFAULTotherwise, as there;accept,getsockname,getpeernameand the option getters pass the caller’s length to the kernel and report at most that much back (the kernel reports the untruncated length; the contract clamps it, wherepal_networking.conly asserts);ReceiveMessage/SendMessagereject negative lengths and counts and give a stream socket at mostIOV_MAXvectors;ReceiveSocketErrorcopies the offender’s address bounded by both the caller’s length andsockaddr_storage(upstream bounds it by the caller’s only); the control-message walk is glibc’s/Darwin’sCMSG_NXTHDR, which stops before a header or its data would leave the buffer, andTryGetIPPacketInformationchecks each message’s length before readingin_pktinfo/in6_pktinfo;WaitForSocketEventswrites at most*countevents into the bufferCreateSocketEventBuffersized forcountof the larger of the kernel’s and the PAL’s event (converting backwards on x86-64, whereepoll_eventis the smaller);Pollfills apollfdarray of exactlyeventCount; the host entry is sized by a counting pass and the copy pass writes at most that many addresses (upstream decrements the count instead);GetNetworkInterfacesallocates one slot pergetifaddrsentry plus one per address, as there, copies interface names up to their NUL within the 16-byte field (upstream copies 16 bytes whatever the name’s length), reads netmasks from a copy (upstream’smask2prefixshifts them in place) and treats a missing netmask as a full prefix (upstream dereferences it);ReadEventsreads at most 4 KiB and walks netlink messages within the lengthrecvmsgreturned, checking each message is long enough for the field it reads. - EINTR is retried exactly where
pal_networking.cretries it:accept,connect,connectx,recv,send,recvmsg,sendmsg,sendfile,poll,epoll_wait,kevent, theFIONREAD/SIOCATMARKioctls; not aroundbind,listen,shutdown,getsockopt,setsockoptorclose(an interruptedcloseof the event port is success, as there). macOS also retriessend/sendmsga few times onEPROTOTYPE, as there. - No new attack surface. Names reach
getaddrinfo/getnameinfoas the framework’s NUL-terminated UTF-8; nothing parses untrusted text in the contract (the framework’s IL parses endpoints, URIs and HTTP); the only callbacks are the framework’s ownUnmanagedCallersOnlyfunctions; SIGPIPE stays ignored by the runtime (csrt.c), as .NET does, so a write to a reset connection isEPIPE, not a signal. The Windows corelib keeps its Winsock shadows (below), so nothing changes there.
What libSystem.Native does that the contract does differently, by design: the clamps and NUL-bounded copies above; ReceiveSocketError
hands recvmsg the platform’s MSG_DONTWAIT | MSG_ERRQUEUE where pal_networking.c passes the PAL values unconverted (0x3000; on Linux
the error queue never blocks either way); GetSocketType on macOS reads proc_pidfdinfo into a 1 KiB buffer and requires only the
fields it reads, instead of comparing with the full socket_fdinfo size.
Windows
The Windows build of System.Net.Sockets is overlapped I/O over an I/O completion port (ThreadPoolBoundHandle, NativeOverlapped),
which csharpc’s thread pool does not implement yet: Windows keeps the corelib’s Winsock shadows (Net/Sockets.cs, SocketEngine.cs,
NetNative.cs, SocketAsyncEventArgs.cs, SocketAddressPal.cs, UnixDomainSocketEndPoint.cs, NetworkInterfaces.cs, NetworkChange.cs,
now compiled into the Windows corelib only; FrameworkIl ignores a shadow file whose whole content is for other targets).