Crypto++  5.6.5
Free C++ class library of cryptographic schemes
wait.cpp
1 // wait.cpp - written and placed in the public domain by Wei Dai
2 
3 #include "pch.h"
4 #include "config.h"
5 
6 #if CRYPTOPP_MSC_VERSION
7 # pragma warning(disable: 4189)
8 #endif
9 
10 #if !defined(NO_OS_DEPENDENCE) && (defined(SOCKETS_AVAILABLE) || defined(WINDOWS_PIPES_AVAILABLE))
11 
12 #include "wait.h"
13 #include "misc.h"
14 #include "smartptr.h"
15 
16 // Windows 8, Windows Server 2012, and Windows Phone 8.1 need <synchapi.h> and <ioapiset.h>
17 #if defined(CRYPTOPP_WIN32_AVAILABLE)
18 # if ((WINVER >= 0x0602 /*_WIN32_WINNT_WIN8*/) || (_WIN32_WINNT >= 0x0602 /*_WIN32_WINNT_WIN8*/))
19 # include <synchapi.h>
20 # include <ioapiset.h>
21 # define USE_WINDOWS8_API
22 # endif
23 #endif
24 
25 #ifdef USE_BERKELEY_STYLE_SOCKETS
26 #include <errno.h>
27 #include <sys/types.h>
28 #include <sys/time.h>
29 #include <unistd.h>
30 #endif
31 
32 #if defined(CRYPTOPP_MSAN)
33 # include <sanitizer/msan_interface.h>
34 #endif
35 
36 NAMESPACE_BEGIN(CryptoPP)
37 
38 unsigned int WaitObjectContainer::MaxWaitObjects()
39 {
40 #ifdef USE_WINDOWS_STYLE_SOCKETS
41  return MAXIMUM_WAIT_OBJECTS * (MAXIMUM_WAIT_OBJECTS-1);
42 #else
43  return FD_SETSIZE;
44 #endif
45 }
46 
47 WaitObjectContainer::WaitObjectContainer(WaitObjectsTracer* tracer)
48  : m_tracer(tracer),
49 #ifdef USE_WINDOWS_STYLE_SOCKETS
50  m_startWaiting(0), m_stopWaiting(0),
51 #endif
52  m_firstEventTime(0.0f), m_eventTimer(Timer::MILLISECONDS), m_lastResult(0),
53  m_sameResultCount(0), m_noWaitTimer(Timer::MILLISECONDS)
54 {
55  Clear();
56  m_eventTimer.StartTimer();
57 }
58 
59 void WaitObjectContainer::Clear()
60 {
61 #ifdef USE_WINDOWS_STYLE_SOCKETS
62  m_handles.clear();
63 #else
64  m_maxFd = 0;
65  FD_ZERO(&m_readfds);
66  FD_ZERO(&m_writefds);
67 # ifdef CRYPTOPP_MSAN
68  __msan_unpoison(&m_readfds, sizeof(m_readfds));
69  __msan_unpoison(&m_writefds, sizeof(m_writefds));
70 # endif
71 #endif
72  m_noWait = false;
73  m_firstEventTime = 0;
74 }
75 
76 inline void WaitObjectContainer::SetLastResult(LastResultType result)
77 {
78  if (result == m_lastResult)
79  m_sameResultCount++;
80  else
81  {
82  m_lastResult = result;
83  m_sameResultCount = 0;
84  }
85 }
86 
87 void WaitObjectContainer::DetectNoWait(LastResultType result, CallStack const& callStack)
88 {
89  if (result == m_lastResult && m_noWaitTimer.ElapsedTime() > 1000)
90  {
91  if (m_sameResultCount > m_noWaitTimer.ElapsedTime())
92  {
93  if (m_tracer)
94  {
95  std::string desc = "No wait loop detected - m_lastResult: ";
96  desc.append(IntToString(m_lastResult)).append(", call stack:");
97  for (CallStack const* cs = &callStack; cs; cs = cs->Prev())
98  desc.append("\n- ").append(cs->Format());
99  m_tracer->TraceNoWaitLoop(desc);
100  }
101  try { throw 0; } catch (...) {} // help debugger break
102  }
103 
104  m_noWaitTimer.StartTimer();
105  m_sameResultCount = 0;
106  }
107 }
108 
109 void WaitObjectContainer::SetNoWait(CallStack const& callStack)
110 {
111  DetectNoWait(LastResultType(LASTRESULT_NOWAIT), CallStack("WaitObjectContainer::SetNoWait()", &callStack));
112  m_noWait = true;
113 }
114 
115 void WaitObjectContainer::ScheduleEvent(double milliseconds, CallStack const& callStack)
116 {
117  if (milliseconds <= 3)
118  DetectNoWait(LastResultType(LASTRESULT_SCHEDULED), CallStack("WaitObjectContainer::ScheduleEvent()", &callStack));
119  double thisEventTime = m_eventTimer.ElapsedTimeAsDouble() + milliseconds;
120  if (!m_firstEventTime || thisEventTime < m_firstEventTime)
121  m_firstEventTime = thisEventTime;
122 }
123 
124 #ifdef USE_WINDOWS_STYLE_SOCKETS
125 
127 {
128  bool waitingToWait, terminate;
129  HANDLE startWaiting, stopWaiting;
130  const HANDLE *waitHandles;
131  unsigned int count;
132  HANDLE threadHandle;
133  DWORD threadId;
134  DWORD* error;
135 };
136 
137 WaitObjectContainer::~WaitObjectContainer()
138 {
139  try // don't let exceptions escape destructor
140  {
141  if (!m_threads.empty())
142  {
143  HANDLE threadHandles[MAXIMUM_WAIT_OBJECTS] = {0};
144 
145  unsigned int i;
146  for (i=0; i<m_threads.size(); i++)
147  {
148  // Enterprise Analysis warning
149  if(!m_threads[i]) continue;
150 
151  WaitingThreadData &thread = *m_threads[i];
152  while (!thread.waitingToWait) // spin until thread is in the initial "waiting to wait" state
153  Sleep(0);
154  thread.terminate = true;
155  threadHandles[i] = thread.threadHandle;
156  }
157 
158  BOOL bResult = PulseEvent(m_startWaiting);
159  CRYPTOPP_ASSERT(bResult != 0); CRYPTOPP_UNUSED(bResult);
160 
161  // Enterprise Analysis warning
162 #if defined(USE_WINDOWS8_API)
163  DWORD dwResult = ::WaitForMultipleObjectsEx((DWORD)m_threads.size(), threadHandles, TRUE, INFINITE, FALSE);
164  CRYPTOPP_ASSERT(dwResult < (DWORD)m_threads.size());
165 #else
166  DWORD dwResult = ::WaitForMultipleObjects((DWORD)m_threads.size(), threadHandles, TRUE, INFINITE);
167  CRYPTOPP_ASSERT(dwResult < (DWORD)m_threads.size());
168 #endif
169 
170  for (i=0; i<m_threads.size(); i++)
171  {
172  // Enterprise Analysis warning
173  if (!threadHandles[i]) continue;
174 
175  bResult = CloseHandle(threadHandles[i]);
176  CRYPTOPP_ASSERT(bResult != 0);
177  }
178 
179  bResult = CloseHandle(m_startWaiting);
180  CRYPTOPP_ASSERT(bResult != 0);
181  bResult = CloseHandle(m_stopWaiting);
182  CRYPTOPP_ASSERT(bResult != 0);
183  }
184  }
185  catch (const Exception&)
186  {
187  CRYPTOPP_ASSERT(0);
188  }
189 }
190 
191 void WaitObjectContainer::AddHandle(HANDLE handle, CallStack const& callStack)
192 {
193  DetectNoWait(m_handles.size(), CallStack("WaitObjectContainer::AddHandle()", &callStack));
194  m_handles.push_back(handle);
195 }
196 
197 DWORD WINAPI WaitingThread(LPVOID lParam)
198 {
200  WaitingThreadData &thread = *pThread;
201  std::vector<HANDLE> handles;
202 
203  while (true)
204  {
205  thread.waitingToWait = true;
206 #if defined(USE_WINDOWS8_API)
207  DWORD result = ::WaitForSingleObjectEx(thread.startWaiting, INFINITE, FALSE);
208  CRYPTOPP_ASSERT(result != WAIT_FAILED);
209 #else
210  DWORD result = ::WaitForSingleObject(thread.startWaiting, INFINITE);
211  CRYPTOPP_ASSERT(result != WAIT_FAILED);
212 #endif
213 
214  thread.waitingToWait = false;
215  if (thread.terminate)
216  break;
217  if (!thread.count)
218  continue;
219 
220  handles.resize(thread.count + 1);
221  handles[0] = thread.stopWaiting;
222  std::copy(thread.waitHandles, thread.waitHandles+thread.count, handles.begin()+1);
223 
224 #if defined(USE_WINDOWS8_API)
225  result = ::WaitForMultipleObjectsEx((DWORD)handles.size(), &handles[0], FALSE, INFINITE, FALSE);
226  CRYPTOPP_ASSERT(result != WAIT_FAILED);
227 #else
228  result = ::WaitForMultipleObjects((DWORD)handles.size(), &handles[0], FALSE, INFINITE);
229  CRYPTOPP_ASSERT(result != WAIT_FAILED);
230 #endif
231 
232  if (result == WAIT_OBJECT_0)
233  continue; // another thread finished waiting first, so do nothing
234  SetEvent(thread.stopWaiting);
235  if (!(result > WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + handles.size()))
236  {
237  CRYPTOPP_ASSERT(!"error in WaitingThread"); // break here so we can see which thread has an error
238  *thread.error = ::GetLastError();
239  }
240  }
241 
242  return S_OK; // return a value here to avoid compiler warning
243 }
244 
245 void WaitObjectContainer::CreateThreads(unsigned int count)
246 {
247  size_t currentCount = m_threads.size();
248  if (currentCount == 0)
249  {
250  m_startWaiting = ::CreateEvent(NULL, TRUE, FALSE, NULL);
251  m_stopWaiting = ::CreateEvent(NULL, TRUE, FALSE, NULL);
252  }
253 
254  if (currentCount < count)
255  {
256  m_threads.resize(count);
257  for (size_t i=currentCount; i<count; i++)
258  {
259  // Enterprise Analysis warning
260  if(!m_threads[i]) continue;
261 
262  m_threads[i] = new WaitingThreadData;
263  WaitingThreadData &thread = *m_threads[i];
264  thread.terminate = false;
265  thread.startWaiting = m_startWaiting;
266  thread.stopWaiting = m_stopWaiting;
267  thread.waitingToWait = false;
268  thread.threadHandle = CreateThread(NULL, 0, &WaitingThread, &thread, 0, &thread.threadId);
269  }
270  }
271 }
272 
273 bool WaitObjectContainer::Wait(unsigned long milliseconds)
274 {
275  if (m_noWait || (m_handles.empty() && !m_firstEventTime))
276  {
277  SetLastResult(LastResultType(LASTRESULT_NOWAIT));
278  return true;
279  }
280 
281  bool timeoutIsScheduledEvent = false;
282 
283  if (m_firstEventTime)
284  {
285  double timeToFirstEvent = SaturatingSubtract(m_firstEventTime, m_eventTimer.ElapsedTimeAsDouble());
286 
287  if (timeToFirstEvent <= milliseconds)
288  {
289  milliseconds = (unsigned long)timeToFirstEvent;
290  timeoutIsScheduledEvent = true;
291  }
292 
293  if (m_handles.empty() || !milliseconds)
294  {
295  if (milliseconds)
296  Sleep(milliseconds);
297  SetLastResult(timeoutIsScheduledEvent ? LASTRESULT_SCHEDULED : LASTRESULT_TIMEOUT);
298  return timeoutIsScheduledEvent;
299  }
300  }
301 
302  if (m_handles.size() > MAXIMUM_WAIT_OBJECTS)
303  {
304  // too many wait objects for a single WaitForMultipleObjects call, so use multiple threads
305  static const unsigned int WAIT_OBJECTS_PER_THREAD = MAXIMUM_WAIT_OBJECTS-1;
306  unsigned int nThreads = (unsigned int)((m_handles.size() + WAIT_OBJECTS_PER_THREAD - 1) / WAIT_OBJECTS_PER_THREAD);
307  if (nThreads > MAXIMUM_WAIT_OBJECTS) // still too many wait objects, maybe implement recursive threading later?
308  throw Err("WaitObjectContainer: number of wait objects exceeds limit");
309  CreateThreads(nThreads);
310  DWORD error = S_OK;
311 
312  for (unsigned int i=0; i<m_threads.size(); i++)
313  {
314  // Enterprise Analysis warning
315  if(!m_threads[i]) continue;
316 
317  WaitingThreadData &thread = *m_threads[i];
318  while (!thread.waitingToWait) // spin until thread is in the initial "waiting to wait" state
319  Sleep(0);
320  if (i<nThreads)
321  {
322  thread.waitHandles = &m_handles[i*WAIT_OBJECTS_PER_THREAD];
323  thread.count = UnsignedMin(WAIT_OBJECTS_PER_THREAD, m_handles.size() - i*WAIT_OBJECTS_PER_THREAD);
324  thread.error = &error;
325  }
326  else
327  thread.count = 0;
328  }
329 
330  ResetEvent(m_stopWaiting);
331  PulseEvent(m_startWaiting);
332 
333 #if defined(USE_WINDOWS8_API)
334  DWORD result = ::WaitForSingleObjectEx(m_stopWaiting, milliseconds, FALSE);
335  CRYPTOPP_ASSERT(result != WAIT_FAILED);
336 #else
337  DWORD result = ::WaitForSingleObject(m_stopWaiting, milliseconds);
338  CRYPTOPP_ASSERT(result != WAIT_FAILED);
339 #endif
340 
341  if (result == WAIT_OBJECT_0)
342  {
343  if (error == S_OK)
344  return true;
345  else
346  throw Err("WaitObjectContainer: WaitForMultipleObjects in thread failed with error " + IntToString(error));
347  }
348  SetEvent(m_stopWaiting);
349  if (result == WAIT_TIMEOUT)
350  {
351  SetLastResult(timeoutIsScheduledEvent ? LASTRESULT_SCHEDULED : LASTRESULT_TIMEOUT);
352  return timeoutIsScheduledEvent;
353  }
354  else
355  throw Err("WaitObjectContainer: WaitForSingleObject failed with error " + IntToString(::GetLastError()));
356  }
357  else
358  {
359 #if TRACE_WAIT
360  static Timer t(Timer::MICROSECONDS);
361  static unsigned long lastTime = 0;
362  unsigned long timeBeforeWait = t.ElapsedTime();
363 #endif
364 #if defined(USE_WINDOWS8_API)
365  DWORD result = ::WaitForMultipleObjectsEx((DWORD)m_handles.size(), &m_handles[0], FALSE, milliseconds, FALSE);
366  CRYPTOPP_ASSERT(result != WAIT_FAILED);
367 #else
368  DWORD result = ::WaitForMultipleObjects((DWORD)m_handles.size(), &m_handles[0], FALSE, milliseconds);
369  CRYPTOPP_ASSERT(result != WAIT_FAILED);
370 #endif
371 #if TRACE_WAIT
372  if (milliseconds > 0)
373  {
374  unsigned long timeAfterWait = t.ElapsedTime();
375  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());
376  lastTime = timeAfterWait;
377  }
378 #endif
379  if (result < WAIT_OBJECT_0 + m_handles.size())
380  {
381  if (result == m_lastResult)
382  m_sameResultCount++;
383  else
384  {
385  m_lastResult = result;
386  m_sameResultCount = 0;
387  }
388  return true;
389  }
390  else if (result == WAIT_TIMEOUT)
391  {
392  SetLastResult(timeoutIsScheduledEvent ? LASTRESULT_SCHEDULED : LASTRESULT_TIMEOUT);
393  return timeoutIsScheduledEvent;
394  }
395  else
396  throw Err("WaitObjectContainer: WaitForMultipleObjects failed with error " + IntToString(::GetLastError()));
397  }
398 }
399 
400 #else // #ifdef USE_WINDOWS_STYLE_SOCKETS
401 
402 void WaitObjectContainer::AddReadFd(int fd, CallStack const& callStack) // TODO: do something with callStack
403 {
404  CRYPTOPP_UNUSED(callStack);
405  FD_SET(fd, &m_readfds);
406  m_maxFd = STDMAX(m_maxFd, fd);
407 }
408 
409 void WaitObjectContainer::AddWriteFd(int fd, CallStack const& callStack) // TODO: do something with callStack
410 {
411  CRYPTOPP_UNUSED(callStack);
412  FD_SET(fd, &m_writefds);
413  m_maxFd = STDMAX(m_maxFd, fd);
414 }
415 
416 bool WaitObjectContainer::Wait(unsigned long milliseconds)
417 {
418  if (m_noWait || (!m_maxFd && !m_firstEventTime))
419  return true;
420 
421  bool timeoutIsScheduledEvent = false;
422 
423  if (m_firstEventTime)
424  {
425  double timeToFirstEvent = SaturatingSubtract(m_firstEventTime, m_eventTimer.ElapsedTimeAsDouble());
426  if (timeToFirstEvent <= milliseconds)
427  {
428  milliseconds = (unsigned long)timeToFirstEvent;
429  timeoutIsScheduledEvent = true;
430  }
431  }
432 
433  timeval tv, *timeout;
434 
435  if (milliseconds == INFINITE_TIME)
436  timeout = NULL;
437  else
438  {
439  tv.tv_sec = milliseconds / 1000;
440  tv.tv_usec = (milliseconds % 1000) * 1000;
441  timeout = &tv;
442  }
443 
444  int result = select(m_maxFd+1, &m_readfds, &m_writefds, NULL, timeout);
445 
446  if (result > 0)
447  return true;
448  else if (result == 0)
449  return timeoutIsScheduledEvent;
450  else
451  throw Err("WaitObjectContainer: select failed with error " + IntToString(errno));
452 }
453 
454 #endif
455 
456 // ********************************************************
457 
458 std::string CallStack::Format() const
459 {
460  return m_info;
461 }
462 
463 std::string CallStackWithNr::Format() const
464 {
465  return std::string(m_info) + " / nr: " + IntToString(m_nr);
466 }
467 
468 std::string CallStackWithStr::Format() const
469 {
470  return std::string(m_info) + " / " + std::string(m_z);
471 }
472 
473 bool Waitable::Wait(unsigned long milliseconds, CallStack const& callStack)
474 {
475  WaitObjectContainer container;
476  GetWaitObjects(container, callStack); // reduce clutter by not adding this func to stack
477  return container.Wait(milliseconds);
478 }
479 
480 NAMESPACE_END
481 
482 #endif
Base class for all exceptions thrown by the library.
Definition: cryptlib.h:144
container of wait objects
Definition: wait.h:169
high resolution timer
Definition: hrtimer.h:57
Utility functions for the Crypto++ library.
Classes for automatic resource management.
Library configuration file.
Pointer that overloads operator -&gt;
Definition: smartptr.h:39
virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const &callStack)=0
Retrieves waitable objects.
T1 SaturatingSubtract(const T1 &a, const T2 &b)
Performs a saturating subtract clamped at 0.
Definition: misc.h:841
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be neagtive and incorrectly promoted.
Definition: misc.h:506
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:62
const unsigned long INFINITE_TIME
Represents infinite time.
Definition: cryptlib.h:115
bool Wait(unsigned long milliseconds, CallStack const &callStack)
Wait on this object.
Definition: wait.cpp:473
std::string IntToString(T value, unsigned int base=10)
Converts a value to a string.
Definition: misc.h:533
const T & STDMAX(const T &a, const T &b)
Replacement function for std::max.
Definition: misc.h:480