Skip to content

Commit e021a10

Browse files
authored
Rollup merge of #89472 - nagisa:nagisa/wsa-cleanup, r=dtolnay
Only register `WSACleanup` if `WSAStartup` is actually ever called See #85595 Fixes #85441
2 parents 8c7c689 + 5b4873a commit e021a10

File tree

3 files changed

+21
-6
lines changed

3 files changed

+21
-6
lines changed

library/std/src/sys/windows/net.rs

+11-6
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22

33
use crate::cmp;
44
use crate::io::{self, IoSlice, IoSliceMut, Read};
5+
use crate::lazy::SyncOnceCell;
56
use crate::mem;
67
use crate::net::{Shutdown, SocketAddr};
78
use crate::os::windows::io::{
89
AsRawSocket, AsSocket, BorrowedSocket, FromRawSocket, IntoRawSocket, OwnedSocket, RawSocket,
910
};
1011
use crate::ptr;
11-
use crate::sync::Once;
1212
use crate::sys;
1313
use crate::sys::c;
1414
use crate::sys_common::net;
@@ -29,26 +29,31 @@ pub mod netc {
2929

3030
pub struct Socket(OwnedSocket);
3131

32-
static INIT: Once = Once::new();
32+
static WSA_CLEANUP: SyncOnceCell<unsafe extern "system" fn() -> i32> = SyncOnceCell::new();
3333

3434
/// Checks whether the Windows socket interface has been started already, and
3535
/// if not, starts it.
3636
pub fn init() {
37-
INIT.call_once(|| unsafe {
37+
let _ = WSA_CLEANUP.get_or_init(|| unsafe {
3838
let mut data: c::WSADATA = mem::zeroed();
3939
let ret = c::WSAStartup(
4040
0x202, // version 2.2
4141
&mut data,
4242
);
4343
assert_eq!(ret, 0);
44+
45+
// Only register `WSACleanup` if `WSAStartup` is actually ever called.
46+
// Workaround to prevent linking to `WS2_32.dll` when no network functionality is used.
47+
// See issue #85441.
48+
c::WSACleanup
4449
});
4550
}
4651

4752
pub fn cleanup() {
48-
if INIT.is_completed() {
49-
// only close the socket interface if it has actually been started
53+
// only perform cleanup if network functionality was actually initialized
54+
if let Some(cleanup) = WSA_CLEANUP.get() {
5055
unsafe {
51-
c::WSACleanup();
56+
cleanup();
5257
}
5358
}
5459
}
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# only-windows-msvc
2+
3+
-include ../../run-make-fulldeps/tools.mk
4+
5+
# Tests that WS2_32.dll is not unnecessarily linked, see issue #85441
6+
7+
all:
8+
$(RUSTC) empty.rs
9+
objdump -p $(TMPDIR)/empty.exe | $(CGREP) -v -i "WS2_32.dll"
+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
fn main() {}

0 commit comments

Comments
 (0)