Skip to content

Don't call WSACleanup on process exit #141809

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 18 additions & 16 deletions library/std/src/sys/net/connection/socket/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ use crate::net::{Shutdown, SocketAddr};
use crate::os::windows::io::{
AsRawSocket, AsSocket, BorrowedSocket, FromRawSocket, IntoRawSocket, OwnedSocket, RawSocket,
};
use crate::sync::OnceLock;
use crate::sync::atomic::Atomic;
use crate::sync::atomic::Ordering::{AcqRel, Relaxed};
use crate::sys::c;
use crate::sys_common::{AsInner, FromInner, IntoInner};
use crate::time::Duration;
Expand Down Expand Up @@ -114,35 +115,36 @@ pub(super) mod netc {
#[expect(missing_debug_implementations)]
pub struct Socket(OwnedSocket);

static WSA_CLEANUP: OnceLock<unsafe extern "system" fn() -> i32> = OnceLock::new();
static WSA_INITIALIZED: Atomic<bool> = Atomic::<bool>::new(false);

/// Checks whether the Windows socket interface has been started already, and
/// if not, starts it.
#[inline]
pub fn init() {
let _ = WSA_CLEANUP.get_or_init(|| unsafe {
if !WSA_INITIALIZED.load(Relaxed) {
wsa_startup();
}
}

#[cold]
fn wsa_startup() {
unsafe {
let mut data: c::WSADATA = mem::zeroed();
let ret = c::WSAStartup(
0x202, // version 2.2
&mut data,
);
assert_eq!(ret, 0);

// Only register `WSACleanup` if `WSAStartup` is actually ever called.
// Workaround to prevent linking to `WS2_32.dll` when no network functionality is used.
// See issue #85441.
c::WSACleanup
});
}

pub fn cleanup() {
// only perform cleanup if network functionality was actually initialized
if let Some(cleanup) = WSA_CLEANUP.get() {
unsafe {
cleanup();
if WSA_INITIALIZED.swap(true, AcqRel) {
// If another thread raced with us and called WSAStartup first then call
// WSACleanup so it's as though WSAStartup was only called once.
c::WSACleanup();
}
}
}

pub fn cleanup() {}

/// Returns the last error from the Windows socket interface.
fn last_error() -> io::Error {
io::Error::from_raw_os_error(unsafe { c::WSAGetLastError() })
Expand Down
Loading