1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
|
// wait.cpp - written and placed in the public domain by Wei Dai
#include "pch.h"
#include "wait.h"
#include "misc.h"
#ifdef SOCKETS_AVAILABLE
#ifdef USE_BERKELEY_STYLE_SOCKETS
#include <errno.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#endif
#define TRACE_WAIT 0
#if TRACE_WAIT
#include "hrtimer.h"
#endif
NAMESPACE_BEGIN(CryptoPP)
unsigned int WaitObjectContainer::MaxWaitObjects()
{
#ifdef USE_WINDOWS_STYLE_SOCKETS
return MAXIMUM_WAIT_OBJECTS * (MAXIMUM_WAIT_OBJECTS-1);
#else
return FD_SETSIZE;
#endif
}
WaitObjectContainer::WaitObjectContainer()
#if CRYPTOPP_DETECT_NO_WAIT
: m_sameResultCount(0), m_timer(Timer::MILLISECONDS)
#endif
{
Clear();
}
void WaitObjectContainer::Clear()
{
#ifdef USE_WINDOWS_STYLE_SOCKETS
m_handles.clear();
#else
m_maxFd = 0;
FD_ZERO(&m_readfds);
FD_ZERO(&m_writefds);
#endif
m_noWait = false;
}
void WaitObjectContainer::SetNoWait()
{
#if CRYPTOPP_DETECT_NO_WAIT
if (-1 == m_lastResult && m_timer.ElapsedTime() > 1000)
{
if (m_sameResultCount > m_timer.ElapsedTime())
try {throw 0;} catch (...) {} // possible no-wait loop, break in debugger
m_timer.StartTimer();
}
#endif
m_noWait = true;
}
#ifdef USE_WINDOWS_STYLE_SOCKETS
struct WaitingThreadData
{
bool waitingToWait, terminate;
HANDLE startWaiting, stopWaiting;
const HANDLE *waitHandles;
unsigned int count;
HANDLE threadHandle;
DWORD threadId;
DWORD* error;
};
WaitObjectContainer::~WaitObjectContainer()
{
try // don't let exceptions escape destructor
{
if (!m_threads.empty())
{
HANDLE threadHandles[MAXIMUM_WAIT_OBJECTS];
unsigned int i;
for (i=0; i<m_threads.size(); i++)
{
WaitingThreadData &thread = *m_threads[i];
while (!thread.waitingToWait) // spin until thread is in the initial "waiting to wait" state
Sleep(0);
thread.terminate = true;
threadHandles[i] = thread.threadHandle;
}
PulseEvent(m_startWaiting);
::WaitForMultipleObjects(m_threads.size(), threadHandles, TRUE, INFINITE);
for (i=0; i<m_threads.size(); i++)
CloseHandle(threadHandles[i]);
CloseHandle(m_startWaiting);
CloseHandle(m_stopWaiting);
}
}
catch (...)
{
}
}
void WaitObjectContainer::AddHandle(HANDLE handle)
{
#if CRYPTOPP_DETECT_NO_WAIT
if (m_handles.size() == m_lastResult && m_timer.ElapsedTime() > 1000)
{
if (m_sameResultCount > m_timer.ElapsedTime())
try {throw 0;} catch (...) {} // possible no-wait loop, break in debugger
m_timer.StartTimer();
}
#endif
m_handles.push_back(handle);
}
DWORD WINAPI WaitingThread(LPVOID lParam)
{
std::auto_ptr<WaitingThreadData> pThread((WaitingThreadData *)lParam);
WaitingThreadData &thread = *pThread;
std::vector<HANDLE> handles;
while (true)
{
thread.waitingToWait = true;
::WaitForSingleObject(thread.startWaiting, INFINITE);
thread.waitingToWait = false;
if (thread.terminate)
break;
if (!thread.count)
continue;
handles.resize(thread.count + 1);
handles[0] = thread.stopWaiting;
std::copy(thread.waitHandles, thread.waitHandles+thread.count, handles.begin()+1);
DWORD result = ::WaitForMultipleObjects(handles.size(), &handles[0], FALSE, INFINITE);
if (result == WAIT_OBJECT_0)
continue; // another thread finished waiting first, so do nothing
SetEvent(thread.stopWaiting);
if (!(result > WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + handles.size()))
{
assert(!"error in WaitingThread"); // break here so we can see which thread has an error
*thread.error = ::GetLastError();
}
}
return S_OK; // return a value here to avoid compiler warning
}
void WaitObjectContainer::CreateThreads(unsigned int count)
{
unsigned int currentCount = m_threads.size();
if (currentCount == 0)
{
m_startWaiting = ::CreateEvent(NULL, TRUE, FALSE, NULL);
m_stopWaiting = ::CreateEvent(NULL, TRUE, FALSE, NULL);
}
if (currentCount < count)
{
m_threads.resize(count);
for (unsigned int i=currentCount; i<count; i++)
{
m_threads[i] = new WaitingThreadData;
WaitingThreadData &thread = *m_threads[i];
thread.terminate = false;
thread.startWaiting = m_startWaiting;
thread.stopWaiting = m_stopWaiting;
thread.waitingToWait = false;
thread.threadHandle = CreateThread(NULL, 0, &WaitingThread, &thread, 0, &thread.threadId);
}
}
}
bool WaitObjectContainer::Wait(unsigned long milliseconds)
{
if (m_noWait || m_handles.empty())
{
#if CRYPTOPP_DETECT_NO_WAIT
if (-1 == m_lastResult)
m_sameResultCount++;
else
{
m_lastResult = -1;
m_sameResultCount = 0;
}
#endif
return true;
}
if (m_handles.size() > MAXIMUM_WAIT_OBJECTS)
{
// too many wait objects for a single WaitForMultipleObjects call, so use multiple threads
static const unsigned int WAIT_OBJECTS_PER_THREAD = MAXIMUM_WAIT_OBJECTS-1;
unsigned int nThreads = (m_handles.size() + WAIT_OBJECTS_PER_THREAD - 1) / WAIT_OBJECTS_PER_THREAD;
if (nThreads > MAXIMUM_WAIT_OBJECTS) // still too many wait objects, maybe implement recursive threading later?
throw Err("WaitObjectContainer: number of wait objects exceeds limit");
CreateThreads(nThreads);
DWORD error = S_OK;
for (unsigned int i=0; i<m_threads.size(); i++)
{
WaitingThreadData &thread = *m_threads[i];
while (!thread.waitingToWait) // spin until thread is in the initial "waiting to wait" state
Sleep(0);
if (i<nThreads)
{
thread.waitHandles = &m_handles[i*WAIT_OBJECTS_PER_THREAD];
thread.count = STDMIN(WAIT_OBJECTS_PER_THREAD, m_handles.size() - i*WAIT_OBJECTS_PER_THREAD);
thread.error = &error;
}
else
thread.count = 0;
}
ResetEvent(m_stopWaiting);
PulseEvent(m_startWaiting);
DWORD result = ::WaitForSingleObject(m_stopWaiting, milliseconds);
if (result == WAIT_OBJECT_0)
{
if (error == S_OK)
return true;
else
throw Err("WaitObjectContainer: WaitForMultipleObjects failed with error " + IntToString(error));
}
SetEvent(m_stopWaiting);
if (result == WAIT_TIMEOUT)
return false;
else
throw Err("WaitObjectContainer: WaitForSingleObject failed with error " + IntToString(::GetLastError()));
}
else
{
#if TRACE_WAIT
static Timer t(Timer::MICROSECONDS);
static unsigned long lastTime = 0;
unsigned long timeBeforeWait = t.ElapsedTime();
#endif
DWORD result = ::WaitForMultipleObjects(m_handles.size(), &m_handles[0], FALSE, milliseconds);
#if TRACE_WAIT
if (milliseconds > 0)
{
unsigned long timeAfterWait = t.ElapsedTime();
OutputDebugString(("Handles " + IntToString(m_handles.size()) + ", Woke up by " + IntToString(result-WAIT_OBJECT_0) + ", Busied for " + IntToString(timeBeforeWait-lastTime) + " us, Waited for " + IntToString(timeAfterWait-timeBeforeWait) + " us, max " + IntToString(milliseconds) + "ms\n").c_str());
lastTime = timeAfterWait;
}
#endif
if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + m_handles.size())
{
#if CRYPTOPP_DETECT_NO_WAIT
if (result == m_lastResult)
m_sameResultCount++;
else
{
m_lastResult = result;
m_sameResultCount = 0;
}
#endif
return true;
}
else if (result == WAIT_TIMEOUT)
return false;
else
throw Err("WaitObjectContainer: WaitForMultipleObjects failed with error " + IntToString(::GetLastError()));
}
}
#else
void WaitObjectContainer::AddReadFd(int fd)
{
FD_SET(fd, &m_readfds);
m_maxFd = STDMAX(m_maxFd, fd);
}
void WaitObjectContainer::AddWriteFd(int fd)
{
FD_SET(fd, &m_writefds);
m_maxFd = STDMAX(m_maxFd, fd);
}
bool WaitObjectContainer::Wait(unsigned long milliseconds)
{
if (m_noWait || m_maxFd == 0)
return true;
timeval tv, *timeout;
if (milliseconds == INFINITE_TIME)
timeout = NULL;
else
{
tv.tv_sec = milliseconds / 1000;
tv.tv_usec = (milliseconds % 1000) * 1000;
timeout = &tv;
}
int result = select(m_maxFd+1, &m_readfds, &m_writefds, NULL, timeout);
if (result > 0)
return true;
else if (result == 0)
return false;
else
throw Err("WaitObjectContainer: select failed with error " + errno);
}
#endif
// ********************************************************
bool Waitable::Wait(unsigned long milliseconds)
{
WaitObjectContainer container;
GetWaitObjects(container);
return container.Wait(milliseconds);
}
NAMESPACE_END
#endif
|