summaryrefslogtreecommitdiffstats
path: root/sal/osl/w32/thread.cxx
blob: fe5ac30b01dfc62b0bcfafb7b790351f14b17493 (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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include "system.h"
#include "thread.hxx"

#include <comphelper/windowserrorstring.hxx>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <osl/thread.h>
#include <rtl/alloc.h>
#include <osl/time.h>
#include <osl/interlck.h>
#include <rtl/tencinfo.h>
#include <sal/log.hxx>
#include <systools/win32/comtools.hxx>

#include <errno.h>

namespace {

/**
    Thread-data structure hidden behind oslThread:
 */
typedef struct
{
    HANDLE              m_hThread;      /* OS-handle used for all thread-functions */
    DWORD               m_ThreadId;     /* identifier for this thread */
    sal_Int32           m_nTerminationRequested;
    oslWorkerFunction   m_WorkerFunction;
    void*               m_pData;

} osl_TThreadImpl;

}

static oslThread oslCreateThread(oslWorkerFunction pWorker, void* pThreadData, sal_uInt32 nFlags);

static DWORD WINAPI oslWorkerWrapperFunction(_In_ LPVOID pData)
{
    osl_TThreadImpl* pThreadImpl= static_cast<osl_TThreadImpl*>(pData);

    /* Initialize COM - Multi Threaded Apartment (MTA) for all threads */
    sal::systools::CoInitializeGuard aGuard(COINIT_MULTITHREADED, false,
                                            sal::systools::CoInitializeGuard::WhenFailed::NoThrow);

    /* call worker-function with data */

    pThreadImpl->m_WorkerFunction(pThreadImpl->m_pData);

    return 0;
}

static oslThread oslCreateThread(oslWorkerFunction pWorker,
                                 void* pThreadData,
                                 sal_uInt32 nFlags)
{
    osl_TThreadImpl* pThreadImpl;

    /* alloc mem. for our internal data structure */
    pThreadImpl= static_cast<osl_TThreadImpl *>(malloc(sizeof(osl_TThreadImpl)));

    OSL_ASSERT(pThreadImpl);

    if ( pThreadImpl == nullptr )
    {
        return nullptr;
    }

    pThreadImpl->m_WorkerFunction= pWorker;
    pThreadImpl->m_pData= pThreadData;
    pThreadImpl->m_nTerminationRequested= 0;

    pThreadImpl->m_hThread= CreateThread(
                               nullptr,                     /* no security */
                               0,                           /* default stack-size */
                               oslWorkerWrapperFunction,    /* worker-function */
                               pThreadImpl,                 /* provide worker-function with data */
                               nFlags,                      /* start thread immediately or suspended */
                               &pThreadImpl->m_ThreadId);

    if(pThreadImpl->m_hThread == nullptr)
    {
        SAL_WARN("sal.osl", "CreateThread failed:" << WindowsErrorString(GetLastError()));

        /* create failed */
        free(pThreadImpl);
        return nullptr;
    }

    return pThreadImpl;
}

oslThread SAL_CALL osl_createThread(oslWorkerFunction pWorker,
                                    void* pThreadData)
{
    return oslCreateThread(pWorker, pThreadData, 0);
}

oslThread SAL_CALL osl_createSuspendedThread(oslWorkerFunction pWorker,
                                             void* pThreadData)
{
    return oslCreateThread(pWorker, pThreadData, CREATE_SUSPENDED);
}

oslThreadIdentifier SAL_CALL osl_getThreadIdentifier(oslThread Thread)
{
    osl_TThreadImpl* pThreadImpl= static_cast<osl_TThreadImpl*>(Thread);

    if (pThreadImpl != nullptr)
        return static_cast<oslThreadIdentifier>(pThreadImpl->m_ThreadId);
    else
        return static_cast<oslThreadIdentifier>(GetCurrentThreadId());
}

void SAL_CALL osl_destroyThread(oslThread Thread)
{
    osl_TThreadImpl* pThreadImpl= static_cast<osl_TThreadImpl*>(Thread);

    if (Thread == nullptr) /* valid ptr? */
    {
        /* thread already destroyed or not created */
        return;
    }

    /* !!!! _exitthreadex does _not_ call CloseHandle !!! */
    CloseHandle( pThreadImpl->m_hThread );

    /* free memory */
    free(Thread);
}

void SAL_CALL osl_resumeThread(oslThread Thread)
{
    osl_TThreadImpl* pThreadImpl= static_cast<osl_TThreadImpl*>(Thread);

    OSL_ASSERT(pThreadImpl);        /* valid ptr? */

    ResumeThread(pThreadImpl->m_hThread);
}

void SAL_CALL osl_suspendThread(oslThread Thread)
{
    osl_TThreadImpl* pThreadImpl= static_cast<osl_TThreadImpl*>(Thread);

    OSL_ASSERT(pThreadImpl);        /* valid ptr? */

    SuspendThread(pThreadImpl->m_hThread);
}

void SAL_CALL osl_setThreadPriority(oslThread Thread,
                           oslThreadPriority Priority)
{
    int winPriority;
    osl_TThreadImpl* pThreadImpl= static_cast<osl_TThreadImpl*>(Thread);

    OSL_ASSERT(pThreadImpl);        /* valid ptr? */

    /*  map enum to WIN32 levels
        it would be faster and more elegant to preset
        the enums, but that would require an #ifdef in
        the exported header, which is not desired.
    */
    switch(Priority) {

    case osl_Thread_PriorityHighest:
        winPriority= THREAD_PRIORITY_HIGHEST;
        break;

    case osl_Thread_PriorityAboveNormal:
        winPriority= THREAD_PRIORITY_ABOVE_NORMAL;
        break;

    case osl_Thread_PriorityNormal:
        winPriority= THREAD_PRIORITY_NORMAL;
        break;

    case osl_Thread_PriorityBelowNormal:
        winPriority= THREAD_PRIORITY_BELOW_NORMAL;
        break;

    case osl_Thread_PriorityLowest:
        winPriority= THREAD_PRIORITY_LOWEST;
        break;

    case osl_Thread_PriorityUnknown:
        OSL_ASSERT(FALSE);      /* only fools try this...*/

        /* let release-version behave friendly */
        return;

    default:
        OSL_ASSERT(FALSE);      /* enum expanded, but forgotten here...*/

        /* let release-version behave friendly */
        return;
    }

    SetThreadPriority(pThreadImpl->m_hThread, winPriority);
}

oslThreadPriority SAL_CALL osl_getThreadPriority(const oslThread Thread)
{
    int winPriority;
    oslThreadPriority Priority;

    osl_TThreadImpl* pThreadImpl= static_cast<osl_TThreadImpl*>(Thread);

    /* invalid arguments ?*/
    if(pThreadImpl==nullptr || pThreadImpl->m_hThread==nullptr)
    {
        return osl_Thread_PriorityUnknown;
    }

    winPriority=
        GetThreadPriority(pThreadImpl->m_hThread);

    if(winPriority == THREAD_PRIORITY_ERROR_RETURN)
    {
        return osl_Thread_PriorityUnknown;
    }

    /* map WIN32 priority to enum */
    switch(winPriority)
    {
    case THREAD_PRIORITY_TIME_CRITICAL:
    case THREAD_PRIORITY_HIGHEST:
        Priority= osl_Thread_PriorityHighest;
        break;

    case THREAD_PRIORITY_ABOVE_NORMAL:
        Priority= osl_Thread_PriorityAboveNormal;
        break;

    case THREAD_PRIORITY_NORMAL:
        Priority= osl_Thread_PriorityNormal;
        break;

    case THREAD_PRIORITY_BELOW_NORMAL:
        Priority= osl_Thread_PriorityBelowNormal;
        break;

    case THREAD_PRIORITY_IDLE:
    case THREAD_PRIORITY_LOWEST:
        Priority= osl_Thread_PriorityLowest;
        break;

    default:
        OSL_ASSERT(FALSE); /* WIN32 API changed, incorporate new prio-level! */

        /* release-version behaves friendly */
        Priority= osl_Thread_PriorityUnknown;
    }

    return Priority;
}

sal_Bool SAL_CALL osl_isThreadRunning(const oslThread Thread)
{
    osl_TThreadImpl* pThreadImpl= static_cast<osl_TThreadImpl*>(Thread);

    /* invalid arguments ?*/
    if(pThreadImpl==nullptr || pThreadImpl->m_hThread==nullptr)
    {
        return false;
    }

    return WaitForSingleObject(pThreadImpl->m_hThread, 0) != WAIT_OBJECT_0;
}

void SAL_CALL osl_joinWithThread(oslThread Thread)
{
    osl_TThreadImpl* pThreadImpl= static_cast<osl_TThreadImpl*>(Thread);

    /* invalid arguments?*/
    if(pThreadImpl==nullptr || pThreadImpl->m_hThread==nullptr)
    {
        /* assume thread is not running */
        return;
    }

    WaitForSingleObject(pThreadImpl->m_hThread, INFINITE);
}

void SAL_CALL osl_waitThread(const TimeValue* pDelay)
{
    if (pDelay)
    {
        DWORD millisecs = pDelay->Seconds * 1000L + pDelay->Nanosec / 1000000L;

        Sleep(millisecs);
    }
}

void SAL_CALL osl_terminateThread(oslThread Thread)
{
    osl_TThreadImpl* pThreadImpl= static_cast<osl_TThreadImpl*>(Thread);

    /* invalid arguments?*/
    if (pThreadImpl==nullptr || pThreadImpl->m_hThread==nullptr)
    {
        /* assume thread is not running */
        return;
    }

    osl_atomic_increment(&(pThreadImpl->m_nTerminationRequested));
}

sal_Bool SAL_CALL osl_scheduleThread(oslThread Thread)
{
    osl_TThreadImpl* pThreadImpl= static_cast<osl_TThreadImpl*>(Thread);

    osl_yieldThread();

    /* invalid arguments?*/
    if (pThreadImpl==nullptr || pThreadImpl->m_hThread==nullptr)
    {
        /* assume thread is not running */
        return false;
    }

    return 0 == pThreadImpl->m_nTerminationRequested;
}

void SAL_CALL osl_yieldThread(void)
{
    Sleep(0);
}

static void impSetThreadDescription(char const * name) {
    // SetThreadDescription is only available since Windows 10 version 1607
    typedef HRESULT(WINAPI * TSetThreadDescription)(HANDLE, PCWSTR);
    static const auto pSetThreadDescription = reinterpret_cast<TSetThreadDescription>(
        GetProcAddress(GetModuleHandleA("KernelBase.dll"), "SetThreadDescription"));
    if (pSetThreadDescription)
    {
        if (const int nReqCCh = MultiByteToWideChar(CP_ACP, 0, name, -1, nullptr, 0))
        {
            if (PWSTR wStr = static_cast<PWSTR>(malloc(nReqCCh * sizeof(WCHAR))))
            {
                if (MultiByteToWideChar(CP_ACP, 0, name, -1, wStr, nReqCCh))
                    pSetThreadDescription(GetCurrentThread(), wStr);
                free(wStr);
            }
        }
    }
}

void SAL_CALL osl_setThreadName(char const * name) {
    /* See < https://docs.microsoft.com/en-us/visualstudio/debugger/how-to-set-a-thread-name-in-native-code >: */
#pragma pack(push, 8)
    struct {
        DWORD dwType = 0x1000;
        LPCSTR szName;
        DWORD dwThreadID = DWORD(-1);
        DWORD dwFlags = 0;
    } info;
#pragma pack(pop)
    info.szName = name;
    __try {
        RaiseException(
            0x406D1388, 0, sizeof info / sizeof (ULONG_PTR),
            reinterpret_cast<ULONG_PTR *>(&info));
    } __except (EXCEPTION_EXECUTE_HANDLER) {}

    impSetThreadDescription(name);
}

namespace {

typedef struct TLS_
{
    DWORD                           dwIndex;
    oslThreadKeyCallbackFunction    pfnCallback;
    struct TLS_                     *pNext, *pPrev;
} TLS, *PTLS;

PTLS g_pThreadKeyList = nullptr;
osl::Mutex& getThreadKeyListMutex()
{
    static osl::Mutex g_ThreadKeyListMutex;
    return g_ThreadKeyListMutex;
}

}

static void AddKeyToList( PTLS pTls )
{
    if ( pTls )
    {
        osl::MutexGuard aGuard(getThreadKeyListMutex());

        pTls->pNext = g_pThreadKeyList;
        pTls->pPrev = nullptr;

        if ( g_pThreadKeyList )
            g_pThreadKeyList->pPrev = pTls;

        g_pThreadKeyList = pTls;
    }
}

static void RemoveKeyFromList( PTLS pTls )
{
    if ( pTls )
    {
        osl::MutexGuard aGuard(getThreadKeyListMutex());
        if ( pTls->pPrev )
            pTls->pPrev->pNext = pTls->pNext;
        else
        {
            OSL_ASSERT( pTls == g_pThreadKeyList );
            g_pThreadKeyList = pTls->pNext;
        }

        if ( pTls->pNext )
            pTls->pNext->pPrev = pTls->pPrev;
    }
}

void osl_callThreadKeyCallbackOnThreadDetach(void)
{
    PTLS    pTls;

    osl::MutexGuard aGuard(getThreadKeyListMutex());
    pTls = g_pThreadKeyList;
    while ( pTls )
    {
        if ( pTls->pfnCallback )
        {
            void    *pValue = TlsGetValue( pTls->dwIndex );

            if ( pValue )
                pTls->pfnCallback( pValue );
        }

        pTls = pTls->pNext;
    }
}

oslThreadKey SAL_CALL osl_createThreadKey(oslThreadKeyCallbackFunction pCallback)
{
    PTLS    pTls = static_cast<PTLS>(malloc( sizeof(TLS) ));

    if ( pTls )
    {
        pTls->pfnCallback = pCallback;
        if ( DWORD(-1) == (pTls->dwIndex = TlsAlloc()) )
        {
            free( pTls );
            pTls = nullptr;
        }
        else
            AddKeyToList( pTls );
    }

    return pTls;
}

void SAL_CALL osl_destroyThreadKey(oslThreadKey Key)
{
    if (Key != nullptr)
    {
        PTLS    pTls = static_cast<PTLS>(Key);

        RemoveKeyFromList( pTls );
        TlsFree( pTls->dwIndex );
        free( pTls );
    }
}

void* SAL_CALL osl_getThreadKeyData(oslThreadKey Key)
{
    if (Key != nullptr)
    {
        PTLS    pTls = static_cast<PTLS>(Key);

        return TlsGetValue( pTls->dwIndex );
    }

    return nullptr;
}

sal_Bool SAL_CALL osl_setThreadKeyData(oslThreadKey Key, void *pData)
{
    if (Key != nullptr)
    {
        PTLS    pTls = static_cast<PTLS>(Key);
        void*   pOldData = nullptr;
        bool    fSuccess;

        if ( pTls->pfnCallback )
            pOldData = TlsGetValue( pTls->dwIndex );

        fSuccess = TlsSetValue( pTls->dwIndex, pData );

        if ( fSuccess && pTls->pfnCallback && pOldData )
            pTls->pfnCallback( pOldData );

        return fSuccess;
    }

    return false;
}

namespace
{
rtl_TextEncoding& getThreadTextEncodingImpl()
{
    static thread_local rtl_TextEncoding s_enc = rtl_getTextEncodingFromWindowsCodePage(GetACP());
    return s_enc;
}
}

rtl_TextEncoding SAL_CALL osl_getThreadTextEncoding(void) { return getThreadTextEncodingImpl(); }

rtl_TextEncoding SAL_CALL osl_setThreadTextEncoding( rtl_TextEncoding Encoding )
{
    rtl_TextEncoding oldEncoding = getThreadTextEncodingImpl();
    getThreadTextEncodingImpl() = Encoding;
    return oldEncoding;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */