CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/external/source/vncdll/winvnc/omnithread/nt.cpp
Views: 11784
1
// Package : omnithread
2
// omnithread/nt.cc Created : 6/95 tjr
3
//
4
// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
5
//
6
// This file is part of the omnithread library
7
//
8
// The omnithread library is free software; you can redistribute it and/or
9
// modify it under the terms of the GNU Library General Public
10
// License as published by the Free Software Foundation; either
11
// version 2 of the License, or (at your option) any later version.
12
//
13
// This library is distributed in the hope that it will be useful,
14
// but WITHOUT ANY WARRANTY; without even the implied warranty of
15
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
// Library General Public License for more details.
17
//
18
// You should have received a copy of the GNU Library General Public
19
// License along with this library; if not, write to the Free
20
// Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
21
// 02111-1307, USA
22
//
23
24
//
25
// Implementation of OMNI thread abstraction for NT threads
26
//
27
28
#include <stdlib.h>
29
#include <errno.h>
30
#include "omnithread.h"
31
#include <process.h>
32
33
#define DB(x) // x
34
//#include <iostream.h> or #include <iostream> if DB is on.
35
36
static void get_time_now(unsigned long* abs_sec, unsigned long* abs_nsec);
37
38
///////////////////////////////////////////////////////////////////////////
39
//
40
// Mutex
41
//
42
///////////////////////////////////////////////////////////////////////////
43
44
45
omni_mutex::omni_mutex(void)
46
{
47
InitializeCriticalSection(&crit);
48
}
49
50
omni_mutex::~omni_mutex(void)
51
{
52
DeleteCriticalSection(&crit);
53
}
54
55
void
56
omni_mutex::lock(void)
57
{
58
EnterCriticalSection(&crit);
59
}
60
61
void
62
omni_mutex::unlock(void)
63
{
64
LeaveCriticalSection(&crit);
65
}
66
67
68
69
///////////////////////////////////////////////////////////////////////////
70
//
71
// Condition variable
72
//
73
///////////////////////////////////////////////////////////////////////////
74
75
76
//
77
// Condition variables are tricky to implement using NT synchronisation
78
// primitives, since none of them have the atomic "release mutex and wait to be
79
// signalled" which is central to the idea of a condition variable. To get
80
// around this the solution is to record which threads are waiting and
81
// explicitly wake up those threads.
82
//
83
// Here we implement a condition variable using a list of waiting threads
84
// (protected by a critical section), and a per-thread semaphore (which
85
// actually only needs to be a binary semaphore).
86
//
87
// To wait on the cv, a thread puts itself on the list of waiting threads for
88
// that cv, then releases the mutex and waits on its own personal semaphore. A
89
// signalling thread simply takes a thread from the head of the list and kicks
90
// that thread's semaphore. Broadcast is simply implemented by kicking the
91
// semaphore of each waiting thread.
92
//
93
// The only other tricky part comes when a thread gets a timeout from a timed
94
// wait on its semaphore. Between returning with a timeout from the wait and
95
// entering the critical section, a signalling thread could get in, kick the
96
// waiting thread's semaphore and remove it from the list. If this happens,
97
// the waiting thread's semaphore is now out of step so it needs resetting, and
98
// the thread should indicate that it was signalled rather than that it timed
99
// out.
100
//
101
// It is possible that the thread calling wait or timedwait is not a
102
// omni_thread. In this case we have to provide a temporary data structure,
103
// i.e. for the duration of the call, for the thread to link itself on the
104
// list of waiting threads. _internal_omni_thread_dummy provides such
105
// a data structure and _internal_omni_thread_helper is a helper class to
106
// deal with this special case for wait() and timedwait(). Once created,
107
// the _internal_omni_thread_dummy is cached for use by the next wait() or
108
// timedwait() call from a non-omni_thread. This is probably worth doing
109
// because creating a Semaphore is quite heavy weight.
110
111
class _internal_omni_thread_helper;
112
113
class _internal_omni_thread_dummy : public omni_thread {
114
public:
115
inline _internal_omni_thread_dummy() : next(0) { }
116
inline ~_internal_omni_thread_dummy() { }
117
friend class _internal_omni_thread_helper;
118
private:
119
_internal_omni_thread_dummy* next;
120
};
121
122
class _internal_omni_thread_helper {
123
public:
124
inline _internal_omni_thread_helper() {
125
d = 0;
126
t = omni_thread::self();
127
if (!t) {
128
omni_mutex_lock sync(cachelock);
129
if (cache) {
130
d = cache;
131
cache = cache->next;
132
}
133
else {
134
d = new _internal_omni_thread_dummy;
135
}
136
t = d;
137
}
138
}
139
inline ~_internal_omni_thread_helper() {
140
if (d) {
141
omni_mutex_lock sync(cachelock);
142
d->next = cache;
143
cache = d;
144
}
145
}
146
inline operator omni_thread* () { return t; }
147
inline omni_thread* operator->() { return t; }
148
149
static _internal_omni_thread_dummy* cache;
150
static omni_mutex cachelock;
151
152
private:
153
_internal_omni_thread_dummy* d;
154
omni_thread* t;
155
};
156
157
_internal_omni_thread_dummy* _internal_omni_thread_helper::cache = 0;
158
omni_mutex _internal_omni_thread_helper::cachelock;
159
160
161
omni_condition::omni_condition(omni_mutex* m) : mutex(m)
162
{
163
InitializeCriticalSection(&crit);
164
waiting_head = waiting_tail = NULL;
165
}
166
167
168
omni_condition::~omni_condition(void)
169
{
170
DeleteCriticalSection(&crit);
171
DB( if (waiting_head != NULL) {
172
cerr << "omni_condition::~omni_condition: list of waiting threads "
173
<< "is not empty\n";
174
} )
175
}
176
177
178
void
179
omni_condition::wait(void)
180
{
181
_internal_omni_thread_helper me;
182
183
EnterCriticalSection(&crit);
184
185
me->cond_next = NULL;
186
me->cond_prev = waiting_tail;
187
if (waiting_head == NULL)
188
waiting_head = me;
189
else
190
waiting_tail->cond_next = me;
191
waiting_tail = me;
192
me->cond_waiting = TRUE;
193
194
LeaveCriticalSection(&crit);
195
196
mutex->unlock();
197
198
DWORD result = WaitForSingleObject(me->cond_semaphore, INFINITE);
199
200
mutex->lock();
201
202
if (result != WAIT_OBJECT_0)
203
throw omni_thread_fatal(GetLastError());
204
}
205
206
207
int
208
omni_condition::timedwait(unsigned long abs_sec, unsigned long abs_nsec)
209
{
210
_internal_omni_thread_helper me;
211
212
EnterCriticalSection(&crit);
213
214
me->cond_next = NULL;
215
me->cond_prev = waiting_tail;
216
if (waiting_head == NULL)
217
waiting_head = me;
218
else
219
waiting_tail->cond_next = me;
220
waiting_tail = me;
221
me->cond_waiting = TRUE;
222
223
LeaveCriticalSection(&crit);
224
225
mutex->unlock();
226
227
unsigned long now_sec, now_nsec;
228
229
get_time_now(&now_sec, &now_nsec);
230
231
DWORD timeout = (abs_sec-now_sec) * 1000 + (abs_nsec-now_nsec) / 1000000;
232
233
if ((abs_sec <= now_sec) && ((abs_sec < now_sec) || (abs_nsec < abs_nsec)))
234
timeout = 0;
235
236
DWORD result = WaitForSingleObject(me->cond_semaphore, timeout);
237
238
if (result == WAIT_TIMEOUT) {
239
EnterCriticalSection(&crit);
240
241
if (me->cond_waiting) {
242
if (me->cond_prev != NULL)
243
me->cond_prev->cond_next = me->cond_next;
244
else
245
waiting_head = me->cond_next;
246
if (me->cond_next != NULL)
247
me->cond_next->cond_prev = me->cond_prev;
248
else
249
waiting_tail = me->cond_prev;
250
me->cond_waiting = FALSE;
251
252
LeaveCriticalSection(&crit);
253
254
mutex->lock();
255
return 0;
256
}
257
258
//
259
// We timed out but another thread still signalled us. Wait for
260
// the semaphore (it _must_ have been signalled) to decrement it
261
// again. Return that we were signalled, not that we timed out.
262
//
263
264
LeaveCriticalSection(&crit);
265
266
result = WaitForSingleObject(me->cond_semaphore, INFINITE);
267
}
268
269
if (result != WAIT_OBJECT_0)
270
throw omni_thread_fatal(GetLastError());
271
272
mutex->lock();
273
return 1;
274
}
275
276
277
void
278
omni_condition::signal(void)
279
{
280
EnterCriticalSection(&crit);
281
282
if (waiting_head != NULL) {
283
omni_thread* t = waiting_head;
284
waiting_head = t->cond_next;
285
if (waiting_head == NULL)
286
waiting_tail = NULL;
287
else
288
waiting_head->cond_prev = NULL;
289
t->cond_waiting = FALSE;
290
291
if (!ReleaseSemaphore(t->cond_semaphore, 1, NULL)) {
292
int rc = GetLastError();
293
LeaveCriticalSection(&crit);
294
throw omni_thread_fatal(rc);
295
}
296
}
297
298
LeaveCriticalSection(&crit);
299
}
300
301
302
void
303
omni_condition::broadcast(void)
304
{
305
EnterCriticalSection(&crit);
306
307
while (waiting_head != NULL) {
308
omni_thread* t = waiting_head;
309
waiting_head = t->cond_next;
310
if (waiting_head == NULL)
311
waiting_tail = NULL;
312
else
313
waiting_head->cond_prev = NULL;
314
t->cond_waiting = FALSE;
315
316
if (!ReleaseSemaphore(t->cond_semaphore, 1, NULL)) {
317
int rc = GetLastError();
318
LeaveCriticalSection(&crit);
319
throw omni_thread_fatal(rc);
320
}
321
}
322
323
LeaveCriticalSection(&crit);
324
}
325
326
327
328
///////////////////////////////////////////////////////////////////////////
329
//
330
// Counting semaphore
331
//
332
///////////////////////////////////////////////////////////////////////////
333
334
335
#define SEMAPHORE_MAX 0x7fffffff
336
337
338
omni_semaphore::omni_semaphore(unsigned int initial)
339
{
340
nt_sem = CreateSemaphore(NULL, initial, SEMAPHORE_MAX, NULL);
341
342
if (nt_sem == NULL) {
343
DB( cerr << "omni_semaphore::omni_semaphore: CreateSemaphore error "
344
<< GetLastError() << endl );
345
throw omni_thread_fatal(GetLastError());
346
}
347
}
348
349
350
omni_semaphore::~omni_semaphore(void)
351
{
352
if (!CloseHandle(nt_sem)) {
353
DB( cerr << "omni_semaphore::~omni_semaphore: CloseHandle error "
354
<< GetLastError() << endl );
355
throw omni_thread_fatal(GetLastError());
356
}
357
}
358
359
360
void
361
omni_semaphore::wait(void)
362
{
363
if (WaitForSingleObject(nt_sem, INFINITE) != WAIT_OBJECT_0)
364
throw omni_thread_fatal(GetLastError());
365
}
366
367
368
int
369
omni_semaphore::trywait(void)
370
{
371
switch (WaitForSingleObject(nt_sem, 0)) {
372
373
case WAIT_OBJECT_0:
374
return 1;
375
case WAIT_TIMEOUT:
376
return 0;
377
}
378
379
throw omni_thread_fatal(GetLastError());
380
return 0; /* keep msvc++ happy */
381
}
382
383
384
void
385
omni_semaphore::post(void)
386
{
387
if (!ReleaseSemaphore(nt_sem, 1, NULL))
388
throw omni_thread_fatal(GetLastError());
389
}
390
391
392
393
///////////////////////////////////////////////////////////////////////////
394
//
395
// Thread
396
//
397
///////////////////////////////////////////////////////////////////////////
398
399
400
//
401
// Static variables
402
//
403
404
int omni_thread::init_t::count = 0;
405
406
omni_mutex* omni_thread::next_id_mutex;
407
int omni_thread::next_id = 0;
408
static DWORD self_tls_index;
409
410
//
411
// Initialisation function (gets called before any user code).
412
//
413
414
omni_thread::init_t::init_t(void)
415
{
416
if (count++ != 0) // only do it once however many objects get created.
417
return;
418
419
DB(cerr << "omni_thread::init: NT implementation initialising\n");
420
421
self_tls_index = TlsAlloc();
422
423
if (self_tls_index == 0xffffffff)
424
throw omni_thread_fatal(GetLastError());
425
426
next_id_mutex = new omni_mutex;
427
428
//
429
// Create object for this (i.e. initial) thread.
430
//
431
432
omni_thread* t = new omni_thread;
433
434
t->_state = STATE_RUNNING;
435
436
if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(),
437
GetCurrentProcess(), &t->handle,
438
0, FALSE, DUPLICATE_SAME_ACCESS))
439
throw omni_thread_fatal(GetLastError());
440
441
t->nt_id = GetCurrentThreadId();
442
443
DB(cerr << "initial thread " << t->id() << " NT thread id " << t->nt_id
444
<< endl);
445
446
if (!TlsSetValue(self_tls_index, (LPVOID)t))
447
throw omni_thread_fatal(GetLastError());
448
449
if (!SetThreadPriority(t->handle, nt_priority(PRIORITY_NORMAL)))
450
throw omni_thread_fatal(GetLastError());
451
}
452
453
//
454
// Wrapper for thread creation.
455
//
456
457
extern "C"
458
unsigned __stdcall
459
omni_thread_wrapper(void* ptr)
460
{
461
omni_thread* me = (omni_thread*)ptr;
462
463
DB(cerr << "omni_thread_wrapper: thread " << me->id()
464
<< " started\n");
465
466
TlsSetValue(self_tls_index, (LPVOID)me);
467
//if (!TlsSetValue(self_tls_index, (LPVOID)me))
468
// throw omni_thread_fatal(GetLastError());
469
470
//
471
// Now invoke the thread function with the given argument.
472
//
473
474
if (me->fn_void != NULL) {
475
(*me->fn_void)(me->thread_arg);
476
omni_thread::exit();
477
}
478
479
if (me->fn_ret != NULL) {
480
void* return_value = (*me->fn_ret)(me->thread_arg);
481
omni_thread::exit(return_value);
482
}
483
484
if (me->detached) {
485
me->run(me->thread_arg);
486
omni_thread::exit();
487
} else {
488
void* return_value = me->run_undetached(me->thread_arg);
489
omni_thread::exit(return_value);
490
}
491
492
// should never get here.
493
return 0;
494
}
495
496
497
//
498
// Constructors for omni_thread - set up the thread object but don't
499
// start it running.
500
//
501
502
// construct a detached thread running a given function.
503
504
omni_thread::omni_thread(void (*fn)(void*), void* arg, priority_t pri)
505
{
506
common_constructor(arg, pri, 1);
507
fn_void = fn;
508
fn_ret = NULL;
509
}
510
511
// construct an undetached thread running a given function.
512
513
omni_thread::omni_thread(void* (*fn)(void*), void* arg, priority_t pri)
514
{
515
common_constructor(arg, pri, 0);
516
fn_void = NULL;
517
fn_ret = fn;
518
}
519
520
// construct a thread which will run either run() or run_undetached().
521
522
omni_thread::omni_thread(void* arg, priority_t pri)
523
{
524
common_constructor(arg, pri, 1);
525
fn_void = NULL;
526
fn_ret = NULL;
527
}
528
529
// common part of all constructors.
530
531
void
532
omni_thread::common_constructor(void* arg, priority_t pri, int det)
533
{
534
_state = STATE_NEW;
535
_priority = pri;
536
537
next_id_mutex->lock();
538
_id = next_id++;
539
next_id_mutex->unlock();
540
541
thread_arg = arg;
542
detached = det; // may be altered in start_undetached()
543
544
cond_semaphore = CreateSemaphore(NULL, 0, SEMAPHORE_MAX, NULL);
545
546
if (cond_semaphore == NULL)
547
throw omni_thread_fatal(GetLastError());
548
549
cond_next = cond_prev = NULL;
550
cond_waiting = FALSE;
551
552
handle = NULL;
553
}
554
555
556
//
557
// Destructor for omni_thread.
558
//
559
560
omni_thread::~omni_thread(void)
561
{
562
DB(cerr << "destructor called for thread " << id() << endl);
563
if ((handle != NULL) && !CloseHandle(handle))
564
throw omni_thread_fatal(GetLastError());
565
if (!CloseHandle(cond_semaphore))
566
throw omni_thread_fatal(GetLastError());
567
}
568
569
570
//
571
// Start the thread
572
//
573
574
void
575
omni_thread::start(void)
576
{
577
omni_mutex_lock l(mutex);
578
579
if (_state != STATE_NEW)
580
throw omni_thread_invalid();
581
582
unsigned int t;
583
handle = (HANDLE)_beginthreadex(
584
NULL,
585
0,
586
omni_thread_wrapper,
587
(LPVOID)this,
588
CREATE_SUSPENDED,
589
&t);
590
nt_id = t;
591
if (handle == NULL)
592
throw omni_thread_fatal(GetLastError());
593
594
if (!SetThreadPriority(handle, _priority))
595
throw omni_thread_fatal(GetLastError());
596
597
if (ResumeThread(handle) == 0xffffffff)
598
throw omni_thread_fatal(GetLastError());
599
600
_state = STATE_RUNNING;
601
}
602
603
604
//
605
// Start a thread which will run the member function run_undetached().
606
//
607
608
void
609
omni_thread::start_undetached(void)
610
{
611
if ((fn_void != NULL) || (fn_ret != NULL))
612
throw omni_thread_invalid();
613
614
detached = 0;
615
start();
616
}
617
618
619
//
620
// join - simply check error conditions & call WaitForSingleObject.
621
//
622
623
void
624
omni_thread::join(void** status)
625
{
626
mutex.lock();
627
628
if ((_state != STATE_RUNNING) && (_state != STATE_TERMINATED)) {
629
mutex.unlock();
630
throw omni_thread_invalid();
631
}
632
633
mutex.unlock();
634
635
if (this == self())
636
throw omni_thread_invalid();
637
638
if (detached)
639
throw omni_thread_invalid();
640
641
DB(cerr << "omni_thread::join: doing WaitForSingleObject\n");
642
643
if (WaitForSingleObject(handle, INFINITE) != WAIT_OBJECT_0)
644
throw omni_thread_fatal(GetLastError());
645
646
DB(cerr << "omni_thread::join: WaitForSingleObject succeeded\n");
647
648
if (status)
649
*status = return_val;
650
651
delete this;
652
}
653
654
655
//
656
// Change this thread's priority.
657
//
658
659
void
660
omni_thread::set_priority(priority_t pri)
661
{
662
omni_mutex_lock l(mutex);
663
664
if (_state != STATE_RUNNING)
665
throw omni_thread_invalid();
666
667
_priority = pri;
668
669
if (!SetThreadPriority(handle, nt_priority(pri)))
670
throw omni_thread_fatal(GetLastError());
671
}
672
673
674
//
675
// create - construct a new thread object and start it running. Returns thread
676
// object if successful, null pointer if not.
677
//
678
679
// detached version
680
681
omni_thread*
682
omni_thread::create(void (*fn)(void*), void* arg, priority_t pri)
683
{
684
omni_thread* t = new omni_thread(fn, arg, pri);
685
t->start();
686
return t;
687
}
688
689
// undetached version
690
691
omni_thread*
692
omni_thread::create(void* (*fn)(void*), void* arg, priority_t pri)
693
{
694
omni_thread* t = new omni_thread(fn, arg, pri);
695
t->start();
696
return t;
697
}
698
699
700
//
701
// exit() _must_ lock the mutex even in the case of a detached thread. This is
702
// because a thread may run to completion before the thread that created it has
703
// had a chance to get out of start(). By locking the mutex we ensure that the
704
// creating thread must have reached the end of start() before we delete the
705
// thread object. Of course, once the call to start() returns, the user can
706
// still incorrectly refer to the thread object, but that's their problem.
707
//
708
709
void
710
omni_thread::exit(void* return_value)
711
{
712
omni_thread* me = self();
713
714
if (me)
715
{
716
me->mutex.lock();
717
718
me->_state = STATE_TERMINATED;
719
720
me->mutex.unlock();
721
722
DB(cerr << "omni_thread::exit: thread " << me->id() << " detached "
723
<< me->detached << " return value " << return_value << endl);
724
725
if (me->detached) {
726
delete me;
727
} else {
728
me->return_val = return_value;
729
}
730
}
731
else
732
{
733
DB(cerr << "omni_thread::exit: called with a non-omnithread. Exit quietly." << endl);
734
}
735
// _endthreadex() does not automatically closes the thread handle.
736
// The omni_thread dtor closes the thread handle.
737
_endthreadex(0);
738
}
739
740
741
omni_thread*
742
omni_thread::self(void)
743
{
744
LPVOID me;
745
746
me = TlsGetValue(self_tls_index);
747
748
if (me == NULL) {
749
DB(cerr << "omni_thread::self: called with a non-ominthread. NULL is returned." << endl);
750
}
751
return (omni_thread*)me;
752
}
753
754
755
void
756
omni_thread::yield(void)
757
{
758
Sleep(0);
759
}
760
761
762
#define MAX_SLEEP_SECONDS (DWORD)4294966 // (2**32-2)/1000
763
764
void
765
omni_thread::sleep(unsigned long secs, unsigned long nanosecs)
766
{
767
if (secs <= MAX_SLEEP_SECONDS) {
768
Sleep(secs * 1000 + nanosecs / 1000000);
769
return;
770
}
771
772
DWORD no_of_max_sleeps = secs / MAX_SLEEP_SECONDS;
773
774
for (DWORD i = 0; i < no_of_max_sleeps; i++)
775
Sleep(MAX_SLEEP_SECONDS * 1000);
776
777
Sleep((secs % MAX_SLEEP_SECONDS) * 1000 + nanosecs / 1000000);
778
}
779
780
781
void
782
omni_thread::get_time(unsigned long* abs_sec, unsigned long* abs_nsec,
783
unsigned long rel_sec, unsigned long rel_nsec)
784
{
785
get_time_now(abs_sec, abs_nsec);
786
*abs_nsec += rel_nsec;
787
*abs_sec += rel_sec + *abs_nsec / 1000000000;
788
*abs_nsec = *abs_nsec % 1000000000;
789
}
790
791
792
int
793
omni_thread::nt_priority(priority_t pri)
794
{
795
switch (pri) {
796
797
case PRIORITY_LOW:
798
return THREAD_PRIORITY_LOWEST;
799
800
case PRIORITY_NORMAL:
801
return THREAD_PRIORITY_NORMAL;
802
803
case PRIORITY_HIGH:
804
return THREAD_PRIORITY_HIGHEST;
805
}
806
807
throw omni_thread_invalid();
808
return 0; /* keep msvc++ happy */
809
}
810
811
812
static void
813
get_time_now(unsigned long* abs_sec, unsigned long* abs_nsec)
814
{
815
static int days_in_preceding_months[12]
816
= { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
817
static int days_in_preceding_months_leap[12]
818
= { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
819
820
SYSTEMTIME st;
821
822
GetSystemTime(&st);
823
*abs_nsec = st.wMilliseconds * 1000000;
824
825
// this formula should work until 1st March 2100
826
827
DWORD days = ((st.wYear - 1970) * 365 + (st.wYear - 1969) / 4
828
+ ((st.wYear % 4)
829
? days_in_preceding_months[st.wMonth - 1]
830
: days_in_preceding_months_leap[st.wMonth - 1])
831
+ st.wDay - 1);
832
833
*abs_sec = st.wSecond + 60 * (st.wMinute + 60 * (st.wHour + 24 * days));
834
}
835
836