thread.c 47.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * NT threads support
 *
 * Copyright 1996, 2003 Alexandre Julliard
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 20
 */

21 22 23
#include "config.h"
#include "wine/port.h"

24
#include <assert.h>
25
#include <stdarg.h>
26 27 28 29
#include <sys/types.h>
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
30 31 32
#ifdef HAVE_SYS_TIMES_H
#include <sys/times.h>
#endif
33 34 35
#ifdef HAVE_SYS_SYSCALL_H
#include <sys/syscall.h>
#endif
36

37
#define NONAMELESSUNION
38
#include "ntstatus.h"
39
#define WIN32_NO_STATUS
40
#include "winternl.h"
41
#include "wine/library.h"
42
#include "wine/server.h"
43
#include "wine/debug.h"
44
#include "ntdll_misc.h"
45
#include "ddk/wdm.h"
46
#include "wine/exception.h"
47 48

WINE_DEFAULT_DEBUG_CHANNEL(thread);
49
WINE_DECLARE_DEBUG_CHANNEL(relay);
50

51 52
struct _KUSER_SHARED_DATA *user_shared_data = NULL;

53 54
PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter = NULL;

55 56 57
/* info passed to a starting thread */
struct startup_info
{
58
    TEB                            *teb;
59 60 61 62
    PRTL_THREAD_START_ROUTINE       entry_point;
    void                           *entry_arg;
};

63
static PEB *peb;
64 65
static PEB_LDR_DATA ldr;
static RTL_USER_PROCESS_PARAMETERS params;  /* default parameters if no parent */
66
static WCHAR current_dir[MAX_NT_PATH_LENGTH];
67
static RTL_BITMAP tls_bitmap;
68
static RTL_BITMAP tls_expansion_bitmap;
69
static RTL_BITMAP fls_bitmap;
70
static int nb_threads = 1;
71

72
/***********************************************************************
73
 *           get_unicode_string
74
 *
75
 * Copy a unicode string from the startup info.
76
 */
77
static inline void get_unicode_string( UNICODE_STRING *str, WCHAR **src, WCHAR **dst, UINT len )
78
{
79 80 81 82 83 84 85
    str->Buffer = *dst;
    str->Length = len;
    str->MaximumLength = len + sizeof(WCHAR);
    memcpy( str->Buffer, *src, len );
    str->Buffer[len / sizeof(WCHAR)] = 0;
    *src += len / sizeof(WCHAR);
    *dst += len / sizeof(WCHAR) + 1;
86 87 88 89 90 91 92
}

/***********************************************************************
 *           init_user_process_params
 *
 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
 */
93
static NTSTATUS init_user_process_params( SIZE_T data_size, HANDLE *exe_file )
94 95
{
    void *ptr;
96 97
    WCHAR *src, *dst;
    SIZE_T info_size, env_size, size, alloc_size;
98
    NTSTATUS status;
99
    startup_info_t *info;
100 101
    RTL_USER_PROCESS_PARAMETERS *params = NULL;

102 103
    if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, data_size )))
        return STATUS_NO_MEMORY;
104 105 106

    SERVER_START_REQ( get_startup_info )
    {
107
        wine_server_set_reply( req, info, data_size );
108 109
        if (!(status = wine_server_call( req )))
        {
110 111 112
            data_size = wine_server_reply_size( reply );
            info_size = reply->info_size;
            env_size  = data_size - info_size;
113
            *exe_file = wine_server_ptr_handle( reply->exe_file );
114 115 116
        }
    }
    SERVER_END_REQ;
117
    if (status != STATUS_SUCCESS) goto done;
118

119 120 121 122 123 124 125 126 127 128 129 130 131 132
    size = sizeof(*params);
    size += MAX_NT_PATH_LENGTH * sizeof(WCHAR);
    size += info->dllpath_len + sizeof(WCHAR);
    size += info->imagepath_len + sizeof(WCHAR);
    size += info->cmdline_len + sizeof(WCHAR);
    size += info->title_len + sizeof(WCHAR);
    size += info->desktop_len + sizeof(WCHAR);
    size += info->shellinfo_len + sizeof(WCHAR);
    size += info->runtime_len + sizeof(WCHAR);

    alloc_size = size;
    status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&params, 0, &alloc_size,
                                      MEM_COMMIT, PAGE_READWRITE );
    if (status != STATUS_SUCCESS) goto done;
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
    NtCurrentTeb()->Peb->ProcessParameters = params;
    params->AllocationSize  = alloc_size;
    params->Size            = size;
    params->Flags           = PROCESS_PARAMS_FLAG_NORMALIZED;
    params->DebugFlags      = info->debug_flags;
    params->ConsoleHandle   = wine_server_ptr_handle( info->console );
    params->ConsoleFlags    = info->console_flags;
    params->hStdInput       = wine_server_ptr_handle( info->hstdin );
    params->hStdOutput      = wine_server_ptr_handle( info->hstdout );
    params->hStdError       = wine_server_ptr_handle( info->hstderr );
    params->dwX             = info->x;
    params->dwY             = info->y;
    params->dwXSize         = info->xsize;
    params->dwYSize         = info->ysize;
    params->dwXCountChars   = info->xchars;
    params->dwYCountChars   = info->ychars;
    params->dwFillAttribute = info->attribute;
    params->dwFlags         = info->flags;
    params->wShowWindow     = info->show;

    src = (WCHAR *)(info + 1);
    dst = (WCHAR *)(params + 1);

    /* current directory needs more space */
    get_unicode_string( &params->CurrentDirectory.DosPath, &src, &dst, info->curdir_len );
    params->CurrentDirectory.DosPath.MaximumLength = MAX_NT_PATH_LENGTH * sizeof(WCHAR);
    dst = (WCHAR *)(params + 1) + MAX_NT_PATH_LENGTH;

    get_unicode_string( &params->DllPath, &src, &dst, info->dllpath_len );
    get_unicode_string( &params->ImagePathName, &src, &dst, info->imagepath_len );
    get_unicode_string( &params->CommandLine, &src, &dst, info->cmdline_len );
    get_unicode_string( &params->WindowTitle, &src, &dst, info->title_len );
    get_unicode_string( &params->Desktop, &src, &dst, info->desktop_len );
    get_unicode_string( &params->ShellInfo, &src, &dst, info->shellinfo_len );

    /* runtime info isn't a real string */
    params->RuntimeInfo.Buffer = dst;
    params->RuntimeInfo.Length = params->RuntimeInfo.MaximumLength = info->runtime_len;
    memcpy( dst, src, info->runtime_len );
173 174 175

    /* environment needs to be a separate memory block */
    ptr = NULL;
176 177
    alloc_size = max( 1, env_size );
    status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &alloc_size,
178
                                      MEM_COMMIT, PAGE_READWRITE );
179 180
    if (status != STATUS_SUCCESS) goto done;
    memcpy( ptr, (char *)info + info_size, env_size );
181 182
    params->Environment = ptr;

183 184
done:
    RtlFreeHeap( GetProcessHeap(), 0, info );
185 186 187
    return status;
}

188 189 190 191
#ifdef __APPLE__
#include <mach/mach.h>
#include <mach/mach_error.h>

192
static ULONG64 get_dyld_image_info_addr(void)
193
{
194
    ULONG64 ret = 0;
195 196 197 198 199 200 201 202 203 204
#ifdef TASK_DYLD_INFO
    struct task_dyld_info dyld_info;
    mach_msg_type_number_t size = TASK_DYLD_INFO_COUNT;
    if (task_info(mach_task_self(), TASK_DYLD_INFO, (task_info_t)&dyld_info, &size) == KERN_SUCCESS)
        ret = dyld_info.all_image_info_addr;
#endif
    return ret;
}
#endif  /* __APPLE__ */

205 206 207 208 209 210 211
/***********************************************************************
 *           thread_init
 *
 * Setup the initial thread.
 *
 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
 */
212
HANDLE thread_init(void)
213
{
214 215
    TEB *teb;
    void *addr;
216
    SIZE_T size, info_size;
217
    HANDLE exe_file = 0;
218
    LARGE_INTEGER now;
219
    NTSTATUS status;
220
    struct ntdll_thread_data *thread_data;
221
    static struct debug_info debug_info;  /* debug info for initial thread */
222 223 224
#ifdef __APPLE__
    ULONG64 dyld_image_info;
#endif
225

226 227 228 229 230 231
    virtual_init();

    /* reserve space for shared user data */

    addr = (void *)0x7ffe0000;
    size = 0x10000;
232 233 234 235 236 237 238
    status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
                                      MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
    if (status)
    {
        MESSAGE( "wine: failed to map the shared user data: %08x\n", status );
        exit(1);
    }
239
    user_shared_data = addr;
240 241 242 243 244 245 246 247 248 249 250 251

    /* allocate and initialize the PEB */

    addr = NULL;
    size = sizeof(*peb);
    NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
                             MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
    peb = addr;

    peb->ProcessParameters  = &params;
    peb->TlsBitmap          = &tls_bitmap;
    peb->TlsExpansionBitmap = &tls_expansion_bitmap;
252
    peb->FlsBitmap          = &fls_bitmap;
253
    peb->LdrData            = &ldr;
254 255 256 257
    peb->OSMajorVersion     = 5;
    peb->OSMinorVersion     = 1;
    peb->OSBuildNumber      = 0xA28;
    peb->OSPlatformId       = VER_PLATFORM_WIN32_NT;
258 259
    params.CurrentDirectory.DosPath.Buffer = current_dir;
    params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
260
    params.wShowWindow = 1; /* SW_SHOWNORMAL */
261
    ldr.Length = sizeof(ldr);
262 263 264
    RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
    RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
                         sizeof(peb->TlsExpansionBitmapBits) * 8 );
265
    RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
266
    RtlSetBits( peb->TlsBitmap, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
267
    RtlSetBits( peb->FlsBitmap, 0, 1 );
268
    InitializeListHead( &peb->FlsListHead );
269 270 271
    InitializeListHead( &ldr.InLoadOrderModuleList );
    InitializeListHead( &ldr.InMemoryOrderModuleList );
    InitializeListHead( &ldr.InInitializationOrderModuleList );
272
#ifdef __APPLE__
273 274 275 276 277 278 279 280 281 282 283 284
    dyld_image_info = get_dyld_image_info_addr();
#ifdef __LP64__
#ifdef WORDS_BIGENDIAN
    peb->Reserved[1] = dyld_image_info & 0xFFFFFFFF;
    peb->Reserved[0] = dyld_image_info >> 32;
#else
    peb->Reserved[0] = dyld_image_info & 0xFFFFFFFF;
    peb->Reserved[1] = dyld_image_info >> 32;
#endif
#else
    peb->Reserved[0] = dyld_image_info & 0xFFFFFFFF;
#endif
285
#endif
286

287 288 289 290 291 292
    /*
     * Starting with Vista, the first user to log on has session id 1.
     * Session id 0 is for processes that don't interact with the user (like services).
     */
    peb->SessionId = 1;

293 294
    /* allocate and initialize the initial TEB */

295
    signal_alloc_thread( &teb );
296
    teb->Peb = peb;
297 298 299 300
    teb->Tib.StackBase = (void *)~0UL;
    teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
    teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);

301
    thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
302 303 304 305
    thread_data->request_fd = -1;
    thread_data->reply_fd   = -1;
    thread_data->wait_fd[0] = -1;
    thread_data->wait_fd[1] = -1;
306
    thread_data->debug_info = &debug_info;
307 308
    InsertHeadList( &tls_links, &teb->TlsLinks );

309
    signal_init_thread( teb );
310
    virtual_init_threading();
311

312 313 314 315
    debug_info.str_pos = debug_info.strings;
    debug_info.out_pos = debug_info.output;
    debug_init();

316
    /* setup the server connection */
317
    server_init_process();
318
    info_size = server_init_thread( peb );
319

320
    /* create the process heap */
321
    if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
322 323 324 325
    {
        MESSAGE( "wine: failed to create the process heap\n" );
        exit(1);
    }
326 327 328 329

    /* allocate user parameters */
    if (info_size)
    {
330
        init_user_process_params( info_size, &exe_file );
331 332 333
    }
    else
    {
334 335 336 337 338 339 340 341
        if (isatty(0) || isatty(1) || isatty(2))
            params.ConsoleHandle = (HANDLE)2; /* see kernel32/kernel_private.h */
        if (!isatty(0))
            wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE,  OBJ_INHERIT, &params.hStdInput );
        if (!isatty(1))
            wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdOutput );
        if (!isatty(2))
            wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdError );
342
    }
343

344 345
    /* initialize time values in user_shared_data */
    NtQuerySystemTime( &now );
346 347
    user_shared_data->SystemTime.LowPart = now.u.LowPart;
    user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
348 349 350 351 352
    user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
    user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
    user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
    user_shared_data->TickCountMultiplier = 1 << 24;

353 354
    fill_cpu_info();

355 356
    NtCreateKeyedEvent( &keyed_event, GENERIC_READ | GENERIC_WRITE, NULL, 0 );

357
    return exe_file;
358 359
}

360 361

/***********************************************************************
362
 *           terminate_thread
363
 */
364
void terminate_thread( int status )
365
{
366
    pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
367 368
    if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );

369 370 371 372
    close( ntdll_get_thread_data()->wait_fd[0] );
    close( ntdll_get_thread_data()->wait_fd[1] );
    close( ntdll_get_thread_data()->reply_fd );
    close( ntdll_get_thread_data()->request_fd );
373
    pthread_exit( UIntToPtr(status) );
374 375 376 377 378 379
}


/***********************************************************************
 *           exit_thread
 */
380
void exit_thread( int status )
381
{
382 383
    static void *prev_teb;
    TEB *teb;
384

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    if (status)  /* send the exit code to the server (0 is already the default) */
    {
        SERVER_START_REQ( terminate_thread )
        {
            req->handle    = wine_server_obj_handle( GetCurrentThread() );
            req->exit_code = status;
            wine_server_call( req );
        }
        SERVER_END_REQ;
    }

    if (interlocked_xchg_add( &nb_threads, -1 ) <= 1)
    {
        LdrShutdownProcess();
        exit( status );
    }

    LdrShutdownThread();
403
    RtlFreeThreadActivationContextStack();
404 405 406

    pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );

407 408
    if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
    {
409
        struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
410

411 412 413 414 415
        if (thread_data->pthread_id)
        {
            pthread_join( thread_data->pthread_id, NULL );
            signal_free_thread( teb );
        }
416
    }
417

418 419 420 421
    close( ntdll_get_thread_data()->wait_fd[0] );
    close( ntdll_get_thread_data()->wait_fd[1] );
    close( ntdll_get_thread_data()->reply_fd );
    close( ntdll_get_thread_data()->request_fd );
422
    pthread_exit( UIntToPtr(status) );
423 424 425
}


426 427 428 429 430
/***********************************************************************
 *           start_thread
 *
 * Startup routine for a newly created thread.
 */
431
static void start_thread( struct startup_info *info )
432
{
433
    TEB *teb = info->teb;
434
    struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
435 436
    PRTL_THREAD_START_ROUTINE func = info->entry_point;
    void *arg = info->entry_arg;
437
    struct debug_info debug_info;
438

439 440
    debug_info.str_pos = debug_info.strings;
    debug_info.out_pos = debug_info.output;
441
    thread_data->debug_info = &debug_info;
442
    thread_data->pthread_id = pthread_self();
443

444
    signal_init_thread( teb );
445
    server_init_thread( func );
446
    pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
447

448 449 450 451 452 453
    MODULE_DllThreadAttach( NULL );

    if (TRACE_ON(relay))
        DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );

    call_thread_entry_point( (LPTHREAD_START_ROUTINE)func, arg );
454 455 456 457 458 459 460 461 462 463 464 465
}


/***********************************************************************
 *              RtlCreateUserThread   (NTDLL.@)
 */
NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
                                     BOOLEAN suspended, PVOID stack_addr,
                                     SIZE_T stack_reserve, SIZE_T stack_commit,
                                     PRTL_THREAD_START_ROUTINE start, void *param,
                                     HANDLE *handle_ptr, CLIENT_ID *id )
{
466
    sigset_t sigset;
467 468
    pthread_t pthread_id;
    pthread_attr_t attr;
469
    struct ntdll_thread_data *thread_data;
470
    struct startup_info *info;
471
    HANDLE handle = 0, actctx = 0;
472
    TEB *teb = NULL;
473 474 475 476
    DWORD tid = 0;
    int request_pipe[2];
    NTSTATUS status;

477
    if (process != NtCurrentProcess())
478
    {
479 480 481
        apc_call_t call;
        apc_result_t result;

482 483
        memset( &call, 0, sizeof(call) );

484
        call.create_thread.type    = APC_CREATE_THREAD;
485 486
        call.create_thread.func    = wine_server_client_ptr( start );
        call.create_thread.arg     = wine_server_client_ptr( param );
487 488 489
        call.create_thread.reserve = stack_reserve;
        call.create_thread.commit  = stack_commit;
        call.create_thread.suspend = suspended;
490
        status = server_queue_process_apc( process, &call, &result );
491 492 493 494
        if (status != STATUS_SUCCESS) return status;

        if (result.create_thread.status == STATUS_SUCCESS)
        {
495
            if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
496 497
            if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
            else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
498 499
        }
        return result.create_thread.status;
500 501
    }

502
    if (server_pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
503 504 505 506
    wine_server_send_fd( request_pipe[0] );

    SERVER_START_REQ( new_thread )
    {
507 508
        req->access     = THREAD_ALL_ACCESS;
        req->attributes = 0;  /* FIXME */
509 510 511 512
        req->suspend    = suspended;
        req->request_fd = request_pipe[0];
        if (!(status = wine_server_call( req )))
        {
513
            handle = wine_server_ptr_handle( reply->handle );
514 515 516 517 518 519
            tid = reply->tid;
        }
        close( request_pipe[0] );
    }
    SERVER_END_REQ;

520 521 522 523 524 525
    if (status)
    {
        close( request_pipe[1] );
        return status;
    }

526
    pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
527

528 529
    if ((status = signal_alloc_thread( &teb ))) goto error;

530
    teb->Peb = NtCurrentTeb()->Peb;
531 532 533 534 535
    teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
    teb->ClientId.UniqueThread  = ULongToHandle(tid);
    teb->StaticUnicodeString.Buffer        = teb->StaticUnicodeBuffer;
    teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);

536 537 538 539 540 541 542 543 544 545 546 547 548
    /* create default activation context frame for new thread */
    RtlGetActiveActivationContext(&actctx);
    if (actctx)
    {
        RTL_ACTIVATION_CONTEXT_STACK_FRAME *frame;

        frame = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*frame));
        frame->Previous = NULL;
        frame->ActivationContext = actctx;
        frame->Flags = 0;
        teb->ActivationContextStack.ActiveFrame = frame;
    }

549
    info = (struct startup_info *)(teb + 1);
550 551 552 553
    info->teb         = teb;
    info->entry_point = start;
    info->entry_arg   = param;

554
    thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
555
    thread_data->request_fd  = request_pipe[1];
556 557 558
    thread_data->reply_fd    = -1;
    thread_data->wait_fd[0]  = -1;
    thread_data->wait_fd[1]  = -1;
559

560
    if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
561

562
    pthread_attr_init( &attr );
563 564
    pthread_attr_setstack( &attr, teb->DeallocationStack,
                           (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
565 566 567
    pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
    interlocked_xchg_add( &nb_threads, 1 );
    if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
568
    {
569 570
        interlocked_xchg_add( &nb_threads, -1 );
        pthread_attr_destroy( &attr );
571
        status = STATUS_NO_MEMORY;
572 573
        goto error;
    }
574
    pthread_attr_destroy( &attr );
575
    pthread_sigmask( SIG_SETMASK, &sigset, NULL );
576

577
    if (id) id->UniqueThread = ULongToHandle(tid);
578 579 580 581 582 583
    if (handle_ptr) *handle_ptr = handle;
    else NtClose( handle );

    return STATUS_SUCCESS;

error:
584
    if (teb) signal_free_thread( teb );
585
    if (handle) NtClose( handle );
586
    pthread_sigmask( SIG_SETMASK, &sigset, NULL );
587 588 589 590 591
    close( request_pipe[1] );
    return status;
}


592 593 594 595 596 597 598 599 600 601
/******************************************************************************
 *              RtlGetNtGlobalFlags   (NTDLL.@)
 */
ULONG WINAPI RtlGetNtGlobalFlags(void)
{
    if (!peb) return 0;  /* init not done yet */
    return peb->NtGlobalFlag;
}


602 603 604 605 606 607 608 609 610 611 612
/***********************************************************************
 *              NtOpenThread   (NTDLL.@)
 *              ZwOpenThread   (NTDLL.@)
 */
NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
                              const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
{
    NTSTATUS ret;

    SERVER_START_REQ( open_thread )
    {
613
        req->tid        = HandleToULong(id->UniqueThread);
614 615
        req->access     = access;
        req->attributes = attr ? attr->Attributes : 0;
616
        ret = wine_server_call( req );
617
        *handle = wine_server_ptr_handle( reply->handle );
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
    }
    SERVER_END_REQ;
    return ret;
}


/******************************************************************************
 *              NtSuspendThread   (NTDLL.@)
 *              ZwSuspendThread   (NTDLL.@)
 */
NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
{
    NTSTATUS ret;

    SERVER_START_REQ( suspend_thread )
    {
634
        req->handle = wine_server_obj_handle( handle );
635 636 637 638
        if (!(ret = wine_server_call( req )))
        {
            if (count) *count = reply->count;
        }
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
    }
    SERVER_END_REQ;
    return ret;
}


/******************************************************************************
 *              NtResumeThread   (NTDLL.@)
 *              ZwResumeThread   (NTDLL.@)
 */
NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
{
    NTSTATUS ret;

    SERVER_START_REQ( resume_thread )
    {
655
        req->handle = wine_server_obj_handle( handle );
656 657 658 659
        if (!(ret = wine_server_call( req )))
        {
            if (count) *count = reply->count;
        }
660 661 662 663 664 665
    }
    SERVER_END_REQ;
    return ret;
}


666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
/******************************************************************************
 *              NtAlertResumeThread   (NTDLL.@)
 *              ZwAlertResumeThread   (NTDLL.@)
 */
NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
{
    FIXME( "stub: should alert thread %p\n", handle );
    return NtResumeThread( handle, count );
}


/******************************************************************************
 *              NtAlertThread   (NTDLL.@)
 *              ZwAlertThread   (NTDLL.@)
 */
NTSTATUS WINAPI NtAlertThread( HANDLE handle )
{
    FIXME( "stub: %p\n", handle );
    return STATUS_NOT_IMPLEMENTED;
}


688 689 690 691 692 693 694
/******************************************************************************
 *              NtTerminateThread  (NTDLL.@)
 *              ZwTerminateThread  (NTDLL.@)
 */
NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
{
    NTSTATUS ret;
695
    BOOL self;
696 697 698

    SERVER_START_REQ( terminate_thread )
    {
699
        req->handle    = wine_server_obj_handle( handle );
700 701 702 703 704 705
        req->exit_code = exit_code;
        ret = wine_server_call( req );
        self = !ret && reply->self;
    }
    SERVER_END_REQ;

706
    if (self) abort_thread( exit_code );
707 708 709 710 711 712 713 714 715 716 717 718 719
    return ret;
}


/******************************************************************************
 *              NtQueueApcThread  (NTDLL.@)
 */
NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
                                  ULONG_PTR arg2, ULONG_PTR arg3 )
{
    NTSTATUS ret;
    SERVER_START_REQ( queue_apc )
    {
720
        req->handle = wine_server_obj_handle( handle );
721 722 723
        if (func)
        {
            req->call.type         = APC_USER;
724
            req->call.user.func    = wine_server_client_ptr( func );
725 726 727 728 729
            req->call.user.args[0] = arg1;
            req->call.user.args[1] = arg2;
            req->call.user.args[2] = arg3;
        }
        else req->call.type = APC_NONE;  /* wake up only */
730 731 732 733 734 735 736 737 738 739 740 741 742 743
        ret = wine_server_call( req );
    }
    SERVER_END_REQ;
    return ret;
}


/***********************************************************************
 *              NtSetContextThread  (NTDLL.@)
 *              ZwSetContextThread  (NTDLL.@)
 */
NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
{
    NTSTATUS ret;
744
    DWORD dummy, i;
745
    BOOL self;
746

747 748
#ifdef __i386__
    /* on i386 debug registers always require a server call */
749 750 751
    self = (handle == GetCurrentThread());
    if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
    {
752 753 754 755 756 757
        self = (ntdll_get_thread_data()->dr0 == context->Dr0 &&
                ntdll_get_thread_data()->dr1 == context->Dr1 &&
                ntdll_get_thread_data()->dr2 == context->Dr2 &&
                ntdll_get_thread_data()->dr3 == context->Dr3 &&
                ntdll_get_thread_data()->dr6 == context->Dr6 &&
                ntdll_get_thread_data()->dr7 == context->Dr7);
758
    }
759 760
#else
    self = FALSE;
761
#endif
762

763
    if (!self)
764
    {
765 766 767 768
        context_t server_context;

        context_to_server( &server_context, context );

769
        SERVER_START_REQ( set_thread_context )
770
        {
771
            req->handle  = wine_server_obj_handle( handle );
772
            req->suspend = 1;
773
            wine_server_add_data( req, &server_context, sizeof(server_context) );
774 775 776 777 778 779 780
            ret = wine_server_call( req );
            self = reply->self;
        }
        SERVER_END_REQ;

        if (ret == STATUS_PENDING)
        {
781
            for (i = 0; i < 100; i++)
782
            {
783
                SERVER_START_REQ( set_thread_context )
784
                {
785 786 787 788
                    req->handle  = wine_server_obj_handle( handle );
                    req->suspend = 0;
                    wine_server_add_data( req, &server_context, sizeof(server_context) );
                    ret = wine_server_call( req );
789
                }
790 791 792 793 794 795 796 797
                SERVER_END_REQ;
                if (ret == STATUS_PENDING)
                {
                    LARGE_INTEGER timeout;
                    timeout.QuadPart = -10000;
                    NtDelayExecution( FALSE, &timeout );
                }
                else break;
798
            }
799
            NtResumeThread( handle, &dummy );
800
            if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
801
        }
802 803

        if (ret) return ret;
804 805
    }

806 807
    if (self) set_cpu_context( context );
    return STATUS_SUCCESS;
808 809 810
}


811 812 813 814 815
/* convert CPU-specific flags to generic server flags */
static inline unsigned int get_server_context_flags( DWORD flags )
{
    unsigned int ret = 0;

816
    flags &= 0x3f;  /* mask CPU id flags */
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
    if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
    if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
#ifdef CONTEXT_SEGMENTS
    if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
#endif
#ifdef CONTEXT_FLOATING_POINT
    if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
#endif
#ifdef CONTEXT_DEBUG_REGISTERS
    if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
#endif
#ifdef CONTEXT_EXTENDED_REGISTERS
    if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
#endif
    return ret;
}

834 835 836 837 838 839 840
/***********************************************************************
 *              NtGetContextThread  (NTDLL.@)
 *              ZwGetContextThread  (NTDLL.@)
 */
NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
{
    NTSTATUS ret;
841
    DWORD dummy, i;
842 843
    DWORD needed_flags = context->ContextFlags;
    BOOL self = (handle == GetCurrentThread());
844

845
    /* on i386/amd64 debug registers always require a server call */
846 847
#ifdef __i386__
    if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
848 849
#elif defined(__x86_64__)
    if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_AMD64)) self = FALSE;
850
#endif
851

852
    if (!self)
853
    {
854 855 856
        unsigned int server_flags = get_server_context_flags( context->ContextFlags );
        context_t server_context;

857 858
        SERVER_START_REQ( get_thread_context )
        {
859
            req->handle  = wine_server_obj_handle( handle );
860
            req->flags   = server_flags;
861
            req->suspend = 1;
862
            wine_server_set_reply( req, &server_context, sizeof(server_context) );
863 864 865 866 867 868
            ret = wine_server_call( req );
            self = reply->self;
        }
        SERVER_END_REQ;

        if (ret == STATUS_PENDING)
869
        {
870
            for (i = 0; i < 100; i++)
871
            {
872 873 874 875 876 877 878 879 880 881
                SERVER_START_REQ( get_thread_context )
                {
                    req->handle  = wine_server_obj_handle( handle );
                    req->flags   = server_flags;
                    req->suspend = 0;
                    wine_server_set_reply( req, &server_context, sizeof(server_context) );
                    ret = wine_server_call( req );
                }
                SERVER_END_REQ;
                if (ret == STATUS_PENDING)
882
                {
883 884 885
                    LARGE_INTEGER timeout;
                    timeout.QuadPart = -10000;
                    NtDelayExecution( FALSE, &timeout );
886
                }
887
                else break;
888
            }
889
            NtResumeThread( handle, &dummy );
890
            if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
891
        }
892
        if (!ret) ret = context_from_server( context, &server_context );
893
        if (ret) return ret;
894
        needed_flags &= ~context->ContextFlags;
895 896
    }

897
    if (self)
898
    {
899 900
        if (needed_flags)
        {
901
            CONTEXT ctx;
902
            RtlCaptureContext( &ctx );
903
            copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
904
            context->ContextFlags |= ctx.ContextFlags & needed_flags;
905
        }
906 907
#ifdef __i386__
        /* update the cached version of the debug registers */
908
        if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
909
        {
910 911 912 913 914 915
            ntdll_get_thread_data()->dr0 = context->Dr0;
            ntdll_get_thread_data()->dr1 = context->Dr1;
            ntdll_get_thread_data()->dr2 = context->Dr2;
            ntdll_get_thread_data()->dr3 = context->Dr3;
            ntdll_get_thread_data()->dr6 = context->Dr6;
            ntdll_get_thread_data()->dr7 = context->Dr7;
916 917 918
        }
#endif
    }
919
    return STATUS_SUCCESS;
920
}
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936


/******************************************************************************
 *              NtQueryInformationThread  (NTDLL.@)
 *              ZwQueryInformationThread  (NTDLL.@)
 */
NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
                                          void *data, ULONG length, ULONG *ret_len )
{
    NTSTATUS status;

    switch(class)
    {
    case ThreadBasicInformation:
        {
            THREAD_BASIC_INFORMATION info;
937
            const ULONG_PTR affinity_mask = get_system_affinity_mask();
938 939 940

            SERVER_START_REQ( get_thread_info )
            {
941
                req->handle = wine_server_obj_handle( handle );
942 943 944 945
                req->tid_in = 0;
                if (!(status = wine_server_call( req )))
                {
                    info.ExitStatus             = reply->exit_code;
946
                    info.TebBaseAddress         = wine_server_get_ptr( reply->teb );
947 948
                    info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
                    info.ClientId.UniqueThread  = ULongToHandle(reply->tid);
949
                    info.AffinityMask           = reply->affinity & affinity_mask;
950 951 952 953 954 955 956 957 958 959 960 961
                    info.Priority               = reply->priority;
                    info.BasePriority           = reply->priority;  /* FIXME */
                }
            }
            SERVER_END_REQ;
            if (status == STATUS_SUCCESS)
            {
                if (data) memcpy( data, &info, min( length, sizeof(info) ));
                if (ret_len) *ret_len = min( length, sizeof(info) );
            }
        }
        return status;
962 963
    case ThreadAffinityMask:
        {
964
            const ULONG_PTR affinity_mask = get_system_affinity_mask();
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
            ULONG_PTR affinity = 0;

            SERVER_START_REQ( get_thread_info )
            {
                req->handle = wine_server_obj_handle( handle );
                req->tid_in = 0;
                if (!(status = wine_server_call( req )))
                    affinity = reply->affinity & affinity_mask;
            }
            SERVER_END_REQ;
            if (status == STATUS_SUCCESS)
            {
                if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
                if (ret_len) *ret_len = min( length, sizeof(affinity) );
            }
        }
        return status;
982
    case ThreadTimes:
983 984
        {
            KERNEL_USER_TIMES   kusrt;
985 986

            SERVER_START_REQ( get_thread_times )
987
            {
988
                req->handle = wine_server_obj_handle( handle );
989 990 991
                status = wine_server_call( req );
                if (status == STATUS_SUCCESS)
                {
992 993
                    kusrt.CreateTime.QuadPart = reply->creation_time;
                    kusrt.ExitTime.QuadPart = reply->exit_time;
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
                }
            }
            SERVER_END_REQ;
            if (status == STATUS_SUCCESS)
            {
                /* We call times(2) for kernel time or user time */
                /* We can only (portably) do this for the current thread */
                if (handle == GetCurrentThread())
                {
                    struct tms time_buf;
                    long clocks_per_sec = sysconf(_SC_CLK_TCK);

                    times(&time_buf);
                    kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
                    kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
                }
                else
                {
1012 1013
                    static BOOL reported = FALSE;

1014 1015
                    kusrt.KernelTime.QuadPart = 0;
                    kusrt.UserTime.QuadPart = 0;
1016 1017 1018 1019 1020 1021 1022
                    if (reported)
                        TRACE("Cannot get kerneltime or usertime of other threads\n");
                    else
                    {
                        FIXME("Cannot get kerneltime or usertime of other threads\n");
                        reported = TRUE;
                    }
1023 1024 1025 1026 1027 1028
                }
                if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
                if (ret_len) *ret_len = min( length, sizeof(kusrt) );
            }
        }
        return status;
1029 1030 1031 1032 1033 1034 1035 1036
    case ThreadDescriptorTableEntry:
        {
#ifdef __i386__
            THREAD_DESCRIPTOR_INFORMATION*      tdi = data;
            if (length < sizeof(*tdi))
                status = STATUS_INFO_LENGTH_MISMATCH;
            else if (!(tdi->Selector & 4))  /* GDT selector */
            {
1037
                unsigned sel = LOWORD(tdi->Selector) & ~3;  /* ignore RPL */
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
                status = STATUS_SUCCESS;
                if (!sel)  /* null selector */
                    memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
                else
                {
                    tdi->Entry.BaseLow                   = 0;
                    tdi->Entry.HighWord.Bits.BaseMid     = 0;
                    tdi->Entry.HighWord.Bits.BaseHi      = 0;
                    tdi->Entry.LimitLow                  = 0xffff;
                    tdi->Entry.HighWord.Bits.LimitHi     = 0xf;
                    tdi->Entry.HighWord.Bits.Dpl         = 3;
                    tdi->Entry.HighWord.Bits.Sys         = 0;
                    tdi->Entry.HighWord.Bits.Pres        = 1;
                    tdi->Entry.HighWord.Bits.Granularity = 1;
                    tdi->Entry.HighWord.Bits.Default_Big = 1;
                    tdi->Entry.HighWord.Bits.Type        = 0x12;
1054
                    tdi->Entry.HighWord.Bits.Reserved_0  = 0;
1055 1056 1057 1058 1059
                    /* it has to be one of the system GDT selectors */
                    if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
                    {
                        if (sel == (wine_get_cs() & ~3))
                            tdi->Entry.HighWord.Bits.Type |= 8;  /* code segment */
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
                        else if (sel == (ntdll_get_thread_data()->fs & ~3))
                        {
                            ULONG_PTR fs_base = (ULONG_PTR)NtCurrentTeb();
                            tdi->Entry.BaseLow                   = fs_base & 0xffff;
                            tdi->Entry.HighWord.Bits.BaseMid     = (fs_base >> 16) & 0xff;
                            tdi->Entry.HighWord.Bits.BaseHi      = (fs_base >> 24) & 0xff;
                            tdi->Entry.LimitLow                  = 0x0fff;
                            tdi->Entry.HighWord.Bits.LimitHi     = 0;
                            tdi->Entry.HighWord.Bits.Granularity = 0;
                        }
1070 1071 1072 1073 1074 1075 1076 1077
                        else status = STATUS_ACCESS_DENIED;
                    }
                }
            }
            else
            {
                SERVER_START_REQ( get_selector_entry )
                {
1078
                    req->handle = wine_server_obj_handle( handle );
1079
                    req->entry = LOWORD(tdi->Selector) >> 3;
1080 1081 1082 1083
                    status = wine_server_call( req );
                    if (!status)
                    {
                        if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1084
                            status = STATUS_ACCESS_VIOLATION;
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
                        else
                        {
                            wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
                            wine_ldt_set_limit( &tdi->Entry, reply->limit );
                            wine_ldt_set_flags( &tdi->Entry, reply->flags );
                        }
                    }
                }
                SERVER_END_REQ;
            }
1095 1096 1097
            if (status == STATUS_SUCCESS && ret_len)
                /* yes, that's a bit strange, but it's the way it is */
                *ret_len = sizeof(LDT_ENTRY);
1098 1099 1100 1101 1102
#else
            status = STATUS_NOT_IMPLEMENTED;
#endif
            return status;
        }
1103 1104 1105 1106
    case ThreadAmILastThread:
        {
            SERVER_START_REQ(get_thread_info)
            {
1107
                req->handle = wine_server_obj_handle( handle );
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
                req->tid_in = 0;
                status = wine_server_call( req );
                if (status == STATUS_SUCCESS)
                {
                    BOOLEAN last = reply->last;
                    if (data) memcpy( data, &last, min( length, sizeof(last) ));
                    if (ret_len) *ret_len = min( length, sizeof(last) );
                }
            }
            SERVER_END_REQ;
            return status;
        }
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
    case ThreadQuerySetWin32StartAddress:
        {
            SERVER_START_REQ( get_thread_info )
            {
                req->handle = wine_server_obj_handle( handle );
                req->tid_in = 0;
                status = wine_server_call( req );
                if (status == STATUS_SUCCESS)
                {
                    PRTL_THREAD_START_ROUTINE entry = wine_server_get_ptr( reply->entry_point );
                    if (data) memcpy( data, &entry, min( length, sizeof(entry) ) );
                    if (ret_len) *ret_len = min( length, sizeof(entry) );
                }
            }
            SERVER_END_REQ;
            return status;
        }
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    case ThreadGroupInformation:
        {
            const ULONG_PTR affinity_mask = get_system_affinity_mask();
            GROUP_AFFINITY affinity;

            memset(&affinity, 0, sizeof(affinity));
            affinity.Group = 0; /* Wine only supports max 64 processors */

            SERVER_START_REQ( get_thread_info )
            {
                req->handle = wine_server_obj_handle( handle );
                req->tid_in = 0;
                if (!(status = wine_server_call( req )))
                    affinity.Mask = reply->affinity & affinity_mask;
            }
            SERVER_END_REQ;
            if (status == STATUS_SUCCESS)
            {
                if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
                if (ret_len) *ret_len = min( length, sizeof(affinity) );
            }
        }
        return status;
1160 1161 1162 1163 1164 1165 1166 1167
    case ThreadIsIoPending:
        FIXME( "ThreadIsIoPending info class not supported yet\n" );
        if (length != sizeof(BOOL)) return STATUS_INFO_LENGTH_MISMATCH;
        if (!data) return STATUS_ACCESS_DENIED;

        *(BOOL*)data = FALSE;
        if (ret_len) *ret_len = sizeof(BOOL);
        return STATUS_SUCCESS;
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    case ThreadPriority:
    case ThreadBasePriority:
    case ThreadImpersonationToken:
    case ThreadEnableAlignmentFaultFixup:
    case ThreadEventPair_Reusable:
    case ThreadZeroTlsCell:
    case ThreadPerformanceCount:
    case ThreadIdealProcessor:
    case ThreadPriorityBoost:
    case ThreadSetTlsArrayAddress:
    default:
        FIXME( "info class %d not supported yet\n", class );
        return STATUS_NOT_IMPLEMENTED;
    }
}
1183 1184 1185 1186 1187 1188 1189 1190 1191


/******************************************************************************
 *              NtSetInformationThread  (NTDLL.@)
 *              ZwSetInformationThread  (NTDLL.@)
 */
NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
                                        LPCVOID data, ULONG length )
{
1192
    NTSTATUS status;
1193 1194 1195 1196 1197
    switch(class)
    {
    case ThreadZeroTlsCell:
        if (handle == GetCurrentThread())
        {
1198
            LIST_ENTRY *entry;
1199 1200 1201
            DWORD index;

            if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1202
            index = *(const DWORD *)data;
1203
            if (index < TLS_MINIMUM_AVAILABLE)
1204
            {
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
                RtlAcquirePebLock();
                for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
                {
                    TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
                    teb->TlsSlots[index] = 0;
                }
                RtlReleasePebLock();
            }
            else
            {
                index -= TLS_MINIMUM_AVAILABLE;
                if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
                    return STATUS_INVALID_PARAMETER;
                RtlAcquirePebLock();
                for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
                {
                    TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
                    if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
                }
                RtlReleasePebLock();
1225
            }
1226 1227 1228 1229 1230
            return STATUS_SUCCESS;
        }
        FIXME( "ZeroTlsCell not supported on other threads\n" );
        return STATUS_NOT_IMPLEMENTED;

1231 1232 1233 1234
    case ThreadImpersonationToken:
        {
            const HANDLE *phToken = data;
            if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1235 1236 1237
            TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
            SERVER_START_REQ( set_thread_info )
            {
1238 1239
                req->handle   = wine_server_obj_handle( handle );
                req->token    = wine_server_obj_handle( *phToken );
1240 1241 1242 1243
                req->mask     = SET_THREAD_INFO_TOKEN;
                status = wine_server_call( req );
            }
            SERVER_END_REQ;
1244
        }
1245 1246 1247 1248 1249 1250 1251
        return status;
    case ThreadBasePriority:
        {
            const DWORD *pprio = data;
            if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
            SERVER_START_REQ( set_thread_info )
            {
1252
                req->handle   = wine_server_obj_handle( handle );
1253 1254 1255 1256 1257 1258 1259
                req->priority = *pprio;
                req->mask     = SET_THREAD_INFO_PRIORITY;
                status = wine_server_call( req );
            }
            SERVER_END_REQ;
        }
        return status;
1260 1261
    case ThreadAffinityMask:
        {
1262
            const ULONG_PTR affinity_mask = get_system_affinity_mask();
1263 1264
            ULONG_PTR req_aff;

1265
            if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1266
            req_aff = *(const ULONG_PTR *)data;
1267
            if ((ULONG)req_aff == ~0u) req_aff = affinity_mask;
1268 1269
            else if (req_aff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
            else if (!req_aff) return STATUS_INVALID_PARAMETER;
1270 1271
            SERVER_START_REQ( set_thread_info )
            {
1272
                req->handle   = wine_server_obj_handle( handle );
1273
                req->affinity = req_aff;
1274 1275 1276 1277 1278 1279
                req->mask     = SET_THREAD_INFO_AFFINITY;
                status = wine_server_call( req );
            }
            SERVER_END_REQ;
        }
        return status;
1280 1281 1282
    case ThreadHideFromDebugger:
        /* pretend the call succeeded to satisfy some code protectors */
        return STATUS_SUCCESS;
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
    case ThreadQuerySetWin32StartAddress:
        {
            const PRTL_THREAD_START_ROUTINE *entry = data;
            if (length != sizeof(PRTL_THREAD_START_ROUTINE)) return STATUS_INVALID_PARAMETER;
            SERVER_START_REQ( set_thread_info )
            {
                req->handle   = wine_server_obj_handle( handle );
                req->mask     = SET_THREAD_INFO_ENTRYPOINT;
                req->entry_point = wine_server_client_ptr( *entry );
                status = wine_server_call( req );
            }
            SERVER_END_REQ;
        }
        return status;
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
    case ThreadGroupInformation:
        {
            const ULONG_PTR affinity_mask = get_system_affinity_mask();
            const GROUP_AFFINITY *req_aff;

            if (length != sizeof(*req_aff)) return STATUS_INVALID_PARAMETER;
            if (!data) return STATUS_ACCESS_VIOLATION;
            req_aff = data;

            /* On Windows the request fails if the reserved fields are set */
            if (req_aff->Reserved[0] || req_aff->Reserved[1] || req_aff->Reserved[2])
                return STATUS_INVALID_PARAMETER;

            /* Wine only supports max 64 processors */
            if (req_aff->Group) return STATUS_INVALID_PARAMETER;
            if (req_aff->Mask & ~affinity_mask) return STATUS_INVALID_PARAMETER;
            if (!req_aff->Mask) return STATUS_INVALID_PARAMETER;
            SERVER_START_REQ( set_thread_info )
            {
                req->handle   = wine_server_obj_handle( handle );
                req->affinity = req_aff->Mask;
                req->mask     = SET_THREAD_INFO_AFFINITY;
                status = wine_server_call( req );
            }
            SERVER_END_REQ;
        }
        return status;
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
    case ThreadBasicInformation:
    case ThreadTimes:
    case ThreadPriority:
    case ThreadDescriptorTableEntry:
    case ThreadEnableAlignmentFaultFixup:
    case ThreadEventPair_Reusable:
    case ThreadPerformanceCount:
    case ThreadAmILastThread:
    case ThreadIdealProcessor:
    case ThreadPriorityBoost:
    case ThreadSetTlsArrayAddress:
    case ThreadIsIoPending:
    default:
        FIXME( "info class %d not supported yet\n", class );
        return STATUS_NOT_IMPLEMENTED;
    }
}
1341 1342 1343 1344 1345 1346 1347 1348 1349

/******************************************************************************
 * NtGetCurrentProcessorNumber (NTDLL.@)
 *
 * Return the processor, on which the thread is running
 *
 */
ULONG WINAPI NtGetCurrentProcessorNumber(void)
{
1350
    ULONG processor;
1351

1352
#if defined(__linux__) && defined(__NR_getcpu)
1353
    int res = syscall(__NR_getcpu, &processor, NULL, NULL);
1354 1355 1356
    if (res != -1) return processor;
#endif

1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
    if (NtCurrentTeb()->Peb->NumberOfProcessors > 1)
    {
        ULONG_PTR thread_mask, processor_mask;
        NTSTATUS status;

        status = NtQueryInformationThread(GetCurrentThread(), ThreadAffinityMask,
                                          &thread_mask, sizeof(thread_mask), NULL);
        if (status == STATUS_SUCCESS)
        {
            for (processor = 0; processor < NtCurrentTeb()->Peb->NumberOfProcessors; processor++)
            {
                processor_mask = (1 << processor);
                if (thread_mask & processor_mask)
                {
                    if (thread_mask != processor_mask)
                        FIXME("need multicore support (%d processors)\n",
                              NtCurrentTeb()->Peb->NumberOfProcessors);
                    return processor;
                }
            }
        }
1378 1379 1380 1381 1382
    }

    /* fallback to the first processor */
    return 0;
}