| 1 | // Copyright 2021 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "Common/SocketContext.h" |
| 5 | #ifdef _WIN32 |
| 6 | #include "Common/Logging/Log.h" |
| 7 | #include "Common/Network.h" |
| 8 | #endif |
| 9 | |
| 10 | namespace Common |
| 11 | { |
| 12 | #ifdef _WIN32 |
| 13 | SocketContext::SocketContext() |
| 14 | { |
| 15 | std::lock_guard<std::mutex> g(s_lock); |
| 16 | if (s_num_objects == 0) |
| 17 | { |
| 18 | const int ret = WSAStartup(MAKEWORD(2, 2), &s_data); |
| 19 | if (ret == 0) |
| 20 | { |
| 21 | INFO_LOG_FMT(COMMON, "WSAStartup succeeded, wVersion={}.{}, wHighVersion={}.{}", |
| 22 | int(LOBYTE(s_data.wVersion)), int(HIBYTE(s_data.wVersion)), |
| 23 | int(LOBYTE(s_data.wHighVersion)), int(HIBYTE(s_data.wHighVersion))); |
| 24 | } |
| 25 | else |
| 26 | { |
| 27 | // The WSAStartup function directly returns the extended error code in the return value. |
| 28 | // A call to the WSAGetLastError function is not needed and should not be used. |
| 29 | // |
| 30 | // Source: |
| 31 | // https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsastartup |
| 32 | ERROR_LOG_FMT(COMMON, "WSAStartup failed with error {}: {}", ret, |
| 33 | Common::DecodeNetworkError(ret)); |
| 34 | } |
| 35 | } |
| 36 | s_num_objects++; |
| 37 | } |
| 38 | SocketContext::~SocketContext() |
| 39 | { |
| 40 | std::lock_guard<std::mutex> g(s_lock); |
| 41 | s_num_objects--; |
| 42 | if (s_num_objects == 0) |
| 43 | { |
| 44 | WSACleanup(); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | std::mutex SocketContext::s_lock; |
| 49 | size_t SocketContext::s_num_objects = 0; |
| 50 | WSADATA SocketContext::s_data; |
| 51 | |
| 52 | #else |
| 53 | SocketContext::SocketContext() = default; |
| 54 | SocketContext::~SocketContext() = default; |
| 55 | #endif |
| 56 | } // namespace Common |