summaryrefslogtreecommitdiffstats
path: root/tinySAK/winrt/ThreadEmulation.cxx
blob: 91f22944659c651480aa8a83071bd1b2c815f63b (plain)
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
331
332
333
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.

#include "ThreadEmulation.h"

#include <assert.h>
#include <vector>
#include <set>
#include <map>
#include <mutex>

using namespace std;
using namespace Platform;
using namespace Windows::Foundation;
using namespace Windows::System::Threading;


namespace ThreadEmulation
{
// Stored data for CREATE_SUSPENDED and ResumeThread.
struct PendingThreadInfo {
    LPTHREAD_START_ROUTINE lpStartAddress;
    LPVOID lpParameter;
    HANDLE completionEvent;
    int nPriority;
};

static map<HANDLE, PendingThreadInfo> pendingThreads;
static mutex pendingThreadsLock;


// Thread local storage.
typedef vector<void*> ThreadLocalData;

static __declspec(thread) ThreadLocalData* currentThreadData = nullptr;
static set<ThreadLocalData*> allThreadData;
static DWORD nextTlsIndex = 0;
static vector<DWORD> freeTlsIndices;
static mutex tlsAllocationLock;


// Converts a Win32 thread priority to WinRT format.
static WorkItemPriority GetWorkItemPriority(int nPriority)
{
    if (nPriority < 0) {
        return WorkItemPriority::Low;
    }
    else if (nPriority > 0) {
        return WorkItemPriority::High;
    }
    else {
        return WorkItemPriority::Normal;
    }
}


// Helper shared between CreateThread and ResumeThread.
static void StartThread(LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, HANDLE completionEvent, int nPriority)
{
    auto workItemHandler = ref new WorkItemHandler([=](IAsyncAction^) {
        // Run the user callback.
        try {
            lpStartAddress(lpParameter);
        }
        catch (...) { }

        // Clean up any TLS allocations made by this thread.
        TlsShutdown();

        // Signal that the thread has completed.
        SetEvent(completionEvent);
        CloseHandle(completionEvent);

    }, CallbackContext::Any);

    ThreadPool::RunAsync(workItemHandler, GetWorkItemPriority(nPriority), WorkItemOptions::TimeSliced);
}


_Use_decl_annotations_ HANDLE WINAPI CreateThread(LPSECURITY_ATTRIBUTES unusedThreadAttributes, SIZE_T unusedStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD unusedThreadId)
{
    // Validate parameters.
    assert(unusedThreadAttributes == nullptr);
    assert(unusedStackSize == 0);
    assert((dwCreationFlags & ~CREATE_SUSPENDED) == 0);
    assert(unusedThreadId == nullptr);

    // Create a handle that will be signalled when the thread has completed.
    HANDLE threadHandle = CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);

    if (!threadHandle) {
        return nullptr;
    }

    // Make a copy of the handle for internal use. This is necessary because
    // the caller is responsible for closing the handle returned by CreateThread,
    // and they may do that before or after the thread has finished running.
    HANDLE completionEvent;

    if (!DuplicateHandle(GetCurrentProcess(), threadHandle, GetCurrentProcess(), &completionEvent, 0, false, DUPLICATE_SAME_ACCESS)) {
        CloseHandle(threadHandle);
        return nullptr;
    }

    try {
        if (dwCreationFlags & CREATE_SUSPENDED) {
            // Store info about a suspended thread.
            PendingThreadInfo info;

            info.lpStartAddress = lpStartAddress;
            info.lpParameter = lpParameter;
            info.completionEvent = completionEvent;
            info.nPriority = 0;

            lock_guard<mutex> lock(pendingThreadsLock);

            pendingThreads[threadHandle] = info;
        }
        else {
            // Start the thread immediately.
            StartThread(lpStartAddress, lpParameter, completionEvent, 0);
        }

        return threadHandle;
    }
    catch (...) {
        // Clean up if thread creation fails.
        CloseHandle(threadHandle);
        CloseHandle(completionEvent);

        return nullptr;
    }
}


_Use_decl_annotations_ DWORD WINAPI ResumeThread(HANDLE hThread)
{
    lock_guard<mutex> lock(pendingThreadsLock);

    // Look up the requested thread.
    auto threadInfo = pendingThreads.find(hThread);

    if (threadInfo == pendingThreads.end()) {
        // Can only resume threads while they are in CREATE_SUSPENDED state.
        assert(false);
        return (DWORD)-1;
    }

    // Start the thread.
    try {
        PendingThreadInfo& info = threadInfo->second;

        StartThread(info.lpStartAddress, info.lpParameter, info.completionEvent, info.nPriority);
    }
    catch (...) {
        return (DWORD)-1;
    }

    // Remove this thread from the pending list.
    pendingThreads.erase(threadInfo);

    return 0;
}


_Use_decl_annotations_ BOOL WINAPI SetThreadPriority(HANDLE hThread, int nPriority)
{
    lock_guard<mutex> lock(pendingThreadsLock);

    // Look up the requested thread.
    auto threadInfo = pendingThreads.find(hThread);

    if (threadInfo == pendingThreads.end()) {
        // Can only set priority on threads while they are in CREATE_SUSPENDED state.
        return false;
    }

    // Store the new priority.
    threadInfo->second.nPriority = nPriority;

    return true;
}


_Use_decl_annotations_ VOID WINAPI Sleep(DWORD dwMilliseconds)
{
    static HANDLE singletonEvent = nullptr;

    HANDLE sleepEvent = singletonEvent;

    // Demand create the event.
    if (!sleepEvent) {
        sleepEvent = CreateEventEx(nullptr, nullptr, CREATE_EVENT_MANUAL_RESET, EVENT_ALL_ACCESS);

        if (!sleepEvent) {
            return;
        }

        HANDLE previousEvent = InterlockedCompareExchangePointerRelease(&singletonEvent, sleepEvent, nullptr);

        if (previousEvent) {
            // Back out if multiple threads try to demand create at the same time.
            CloseHandle(sleepEvent);
            sleepEvent = previousEvent;
        }
    }

    // Emulate sleep by waiting with timeout on an event that is never signalled.
    WaitForSingleObjectEx(sleepEvent, dwMilliseconds, false);
}


DWORD WINAPI TlsAlloc()
{
    lock_guard<mutex> lock(tlsAllocationLock);

    // Can we reuse a previously freed TLS slot?
    if (!freeTlsIndices.empty()) {
        DWORD result = freeTlsIndices.back();
        freeTlsIndices.pop_back();
        return result;
    }

    // Allocate a new TLS slot.
    return nextTlsIndex++;
}


_Use_decl_annotations_ BOOL WINAPI TlsFree(DWORD dwTlsIndex)
{
    lock_guard<mutex> lock(tlsAllocationLock);

    assert(dwTlsIndex < nextTlsIndex);
    assert(find(freeTlsIndices.begin(), freeTlsIndices.end(), dwTlsIndex) == freeTlsIndices.end());

    // Store this slot for reuse by TlsAlloc.
    try {
        freeTlsIndices.push_back(dwTlsIndex);
    }
    catch (...) {
        return false;
    }

    // Zero the value for all threads that might be using this now freed slot.
    for each (auto threadData in allThreadData) {
        if (threadData->size() > dwTlsIndex) {
            threadData->at(dwTlsIndex) = nullptr;
        }
    }

    return true;
}


_Use_decl_annotations_ LPVOID WINAPI TlsGetValue(DWORD dwTlsIndex)
{
    ThreadLocalData* threadData = currentThreadData;

    if (threadData && threadData->size() > dwTlsIndex) {
        // Return the value of an allocated TLS slot.
        return threadData->at(dwTlsIndex);
    }
    else {
        // Default value for unallocated slots.
        return nullptr;
    }
}


_Use_decl_annotations_ BOOL WINAPI TlsSetValue(DWORD dwTlsIndex, LPVOID lpTlsValue)
{
    ThreadLocalData* threadData = currentThreadData;

    if (!threadData) {
        // First time allocation of TLS data for this thread.
        try {
            threadData = new ThreadLocalData(dwTlsIndex + 1, nullptr);

            lock_guard<mutex> lock(tlsAllocationLock);

            allThreadData.insert(threadData);

            currentThreadData = threadData;
        }
        catch (...) {
            if (threadData) {
                delete threadData;
            }

            return false;
        }
    }
    else if (threadData->size() <= dwTlsIndex) {
        // This thread already has a TLS data block, but it must be expanded to fit the specified slot.
        try {
            lock_guard<mutex> lock(tlsAllocationLock);

            threadData->resize(dwTlsIndex + 1, nullptr);
        }
        catch (...) {
            return false;
        }
    }

    // Store the new value for this slot.
    threadData->at(dwTlsIndex) = lpTlsValue;

    return true;
}


// Called at thread exit to clean up TLS allocations.
void WINAPI TlsShutdown()
{
    ThreadLocalData* threadData = currentThreadData;

    if (threadData) {
        {
            lock_guard<mutex> lock(tlsAllocationLock);

            allThreadData.erase(threadData);
        }

        currentThreadData = nullptr;

        delete threadData;
    }
}
}
OpenPOWER on IntegriCloud