thread.c 40 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
#define NONAMELESSUNION
35
#include "ntstatus.h"
36
#define WIN32_NO_STATUS
37
#include "winternl.h"
38
#include "wine/library.h"
39
#include "wine/server.h"
40
#include "wine/debug.h"
41
#include "ntdll_misc.h"
42
#include "ddk/wdm.h"
43
#include "wine/exception.h"
44 45

WINE_DEFAULT_DEBUG_CHANNEL(thread);
46
WINE_DECLARE_DEBUG_CHANNEL(relay);
47

48 49
struct _KUSER_SHARED_DATA *user_shared_data = NULL;

50 51
PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter = NULL;

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

60 61
static PEB_LDR_DATA ldr;
static RTL_USER_PROCESS_PARAMETERS params;  /* default parameters if no parent */
62
static WCHAR current_dir[MAX_NT_PATH_LENGTH];
63
static RTL_BITMAP tls_bitmap;
64
static RTL_BITMAP tls_expansion_bitmap;
65
static RTL_BITMAP fls_bitmap;
66
static LIST_ENTRY tls_links;
67
static int nb_threads = 1;
68

69
/***********************************************************************
70
 *           get_unicode_string
71
 *
72
 * Copy a unicode string from the startup info.
73
 */
74
static inline void get_unicode_string( UNICODE_STRING *str, WCHAR **src, WCHAR **dst, UINT len )
75
{
76 77 78 79 80 81 82
    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;
83 84 85 86 87 88 89
}

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

99 100
    if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, data_size )))
        return STATUS_NO_MEMORY;
101 102 103

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

116 117 118 119 120 121 122 123 124 125 126 127 128 129
    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;
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
    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 );
170 171 172

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

180 181
done:
    RtlFreeHeap( GetProcessHeap(), 0, info );
182 183 184
    return status;
}

185 186 187 188 189 190 191
/***********************************************************************
 *           thread_init
 *
 * Setup the initial thread.
 *
 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
 */
192
HANDLE thread_init(void)
193
{
194
    PEB *peb;
195 196
    TEB *teb;
    void *addr;
197
    SIZE_T size, info_size;
198
    HANDLE exe_file = 0;
199
    LARGE_INTEGER now;
200
    struct ntdll_thread_data *thread_data;
201
    static struct debug_info debug_info;  /* debug info for initial thread */
202

203 204 205 206 207 208
    virtual_init();

    /* reserve space for shared user data */

    addr = (void *)0x7ffe0000;
    size = 0x10000;
209 210
    NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
    user_shared_data = addr;
211 212 213 214 215 216 217 218 219 220 221 222

    /* 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;
223
    peb->FlsBitmap          = &fls_bitmap;
224
    peb->LdrData            = &ldr;
225 226
    params.CurrentDirectory.DosPath.Buffer = current_dir;
    params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
227
    params.wShowWindow = 1; /* SW_SHOWNORMAL */
228 229 230
    RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
    RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
                         sizeof(peb->TlsExpansionBitmapBits) * 8 );
231 232
    RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
    InitializeListHead( &peb->FlsListHead );
233 234 235
    InitializeListHead( &ldr.InLoadOrderModuleList );
    InitializeListHead( &ldr.InMemoryOrderModuleList );
    InitializeListHead( &ldr.InInitializationOrderModuleList );
236 237
    InitializeListHead( &tls_links );

238 239
    /* allocate and initialize the initial TEB */

240
    signal_alloc_thread( &teb );
241
    teb->Peb = peb;
242 243 244 245
    teb->Tib.StackBase = (void *)~0UL;
    teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
    teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);

246
    thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
247 248 249 250
    thread_data->request_fd = -1;
    thread_data->reply_fd   = -1;
    thread_data->wait_fd[0] = -1;
    thread_data->wait_fd[1] = -1;
251
    thread_data->debug_info = &debug_info;
252 253
    InsertHeadList( &tls_links, &teb->TlsLinks );

254
    signal_init_thread( teb );
255
    virtual_init_threading();
256

257 258 259 260
    debug_info.str_pos = debug_info.strings;
    debug_info.out_pos = debug_info.output;
    debug_init();

261
    /* setup the server connection */
262
    server_init_process();
263
    info_size = server_init_thread( peb );
264

265
    /* create the process heap */
266
    if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
267 268 269 270
    {
        MESSAGE( "wine: failed to create the process heap\n" );
        exit(1);
    }
271 272 273 274

    /* allocate user parameters */
    if (info_size)
    {
275
        init_user_process_params( info_size, &exe_file );
276 277 278 279 280 281
    }
    else
    {
        /* This is wine specific: we have no parent (we're started from unix)
         * so, create a simple console with bare handles to unix stdio
         */
282 283 284
        wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE,  OBJ_INHERIT, &params.hStdInput );
        wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdOutput );
        wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdError );
285
    }
286

287 288
    /* initialize time values in user_shared_data */
    NtQuerySystemTime( &now );
289 290
    user_shared_data->SystemTime.LowPart = now.u.LowPart;
    user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
291 292 293 294 295
    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;

296 297
    fill_cpu_info();

298
    return exe_file;
299 300
}

301 302

/***********************************************************************
303
 *           terminate_thread
304
 */
305
void terminate_thread( int status )
306
{
307
    pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
308 309
    if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );

310 311 312 313
    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 );
314
    pthread_exit( UIntToPtr(status) );
315 316 317 318 319 320
}


/***********************************************************************
 *           exit_thread
 */
321
void exit_thread( int status )
322
{
323 324
    static void *prev_teb;
    TEB *teb;
325

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    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();
344 345 346 347 348 349 350 351
    RtlAcquirePebLock();
    RemoveEntryList( &NtCurrentTeb()->TlsLinks );
    RtlReleasePebLock();
    RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
    RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );

    pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );

352 353
    if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
    {
354
        struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
355 356

        pthread_join( thread_data->pthread_id, NULL );
357
        signal_free_thread( teb );
358
    }
359

360 361 362 363
    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 );
364
    pthread_exit( UIntToPtr(status) );
365 366 367
}


368 369 370 371 372
/***********************************************************************
 *           start_thread
 *
 * Startup routine for a newly created thread.
 */
373
static void start_thread( struct startup_info *info )
374
{
375
    TEB *teb = info->teb;
376
    struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
377 378
    PRTL_THREAD_START_ROUTINE func = info->entry_point;
    void *arg = info->entry_arg;
379
    struct debug_info debug_info;
380

381 382
    debug_info.str_pos = debug_info.strings;
    debug_info.out_pos = debug_info.output;
383
    thread_data->debug_info = &debug_info;
384
    thread_data->pthread_id = pthread_self();
385

386
    signal_init_thread( teb );
387
    server_init_thread( func );
388
    pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
389

390 391 392 393
    RtlAcquirePebLock();
    InsertHeadList( &tls_links, &teb->TlsLinks );
    RtlReleasePebLock();

394 395 396 397 398 399
    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 );
400 401 402 403 404 405 406 407 408 409 410 411
}


/***********************************************************************
 *              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 )
{
412
    sigset_t sigset;
413 414
    pthread_t pthread_id;
    pthread_attr_t attr;
415
    struct ntdll_thread_data *thread_data;
416
    struct startup_info *info = NULL;
417
    HANDLE handle = 0;
418
    TEB *teb = NULL;
419 420 421 422
    DWORD tid = 0;
    int request_pipe[2];
    NTSTATUS status;

423
    if (process != NtCurrentProcess())
424
    {
425 426 427
        apc_call_t call;
        apc_result_t result;

428 429
        memset( &call, 0, sizeof(call) );

430
        call.create_thread.type    = APC_CREATE_THREAD;
431 432
        call.create_thread.func    = wine_server_client_ptr( start );
        call.create_thread.arg     = wine_server_client_ptr( param );
433 434 435 436 437 438 439 440
        call.create_thread.reserve = stack_reserve;
        call.create_thread.commit  = stack_commit;
        call.create_thread.suspend = suspended;
        status = NTDLL_queue_process_apc( process, &call, &result );
        if (status != STATUS_SUCCESS) return status;

        if (result.create_thread.status == STATUS_SUCCESS)
        {
441
            if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
442 443
            if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
            else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
444 445
        }
        return result.create_thread.status;
446 447
    }

448
    if (server_pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
449 450 451 452
    wine_server_send_fd( request_pipe[0] );

    SERVER_START_REQ( new_thread )
    {
453 454
        req->access     = THREAD_ALL_ACCESS;
        req->attributes = 0;  /* FIXME */
455 456 457 458
        req->suspend    = suspended;
        req->request_fd = request_pipe[0];
        if (!(status = wine_server_call( req )))
        {
459
            handle = wine_server_ptr_handle( reply->handle );
460 461 462 463 464 465
            tid = reply->tid;
        }
        close( request_pipe[0] );
    }
    SERVER_END_REQ;

466 467 468 469 470 471
    if (status)
    {
        close( request_pipe[1] );
        return status;
    }

472
    pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
473

474 475
    if ((status = signal_alloc_thread( &teb ))) goto error;

476
    teb->Peb = NtCurrentTeb()->Peb;
477 478 479 480 481
    teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
    teb->ClientId.UniqueThread  = ULongToHandle(tid);
    teb->StaticUnicodeString.Buffer        = teb->StaticUnicodeBuffer;
    teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);

482
    info = (struct startup_info *)(teb + 1);
483 484 485 486
    info->teb         = teb;
    info->entry_point = start;
    info->entry_arg   = param;

487
    thread_data = (struct ntdll_thread_data *)teb->SpareBytes1;
488
    thread_data->request_fd  = request_pipe[1];
489 490 491
    thread_data->reply_fd    = -1;
    thread_data->wait_fd[0]  = -1;
    thread_data->wait_fd[1]  = -1;
492

493
    if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
494

495
    pthread_attr_init( &attr );
496 497
    pthread_attr_setstack( &attr, teb->DeallocationStack,
                           (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
498 499 500
    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 ))
501
    {
502 503
        interlocked_xchg_add( &nb_threads, -1 );
        pthread_attr_destroy( &attr );
504
        status = STATUS_NO_MEMORY;
505 506
        goto error;
    }
507
    pthread_attr_destroy( &attr );
508
    pthread_sigmask( SIG_SETMASK, &sigset, NULL );
509

510
    if (id) id->UniqueThread = ULongToHandle(tid);
511 512 513 514 515 516
    if (handle_ptr) *handle_ptr = handle;
    else NtClose( handle );

    return STATUS_SUCCESS;

error:
517
    if (teb) signal_free_thread( teb );
518
    if (handle) NtClose( handle );
519
    pthread_sigmask( SIG_SETMASK, &sigset, NULL );
520 521 522 523 524
    close( request_pipe[1] );
    return status;
}


525 526 527 528 529 530 531 532 533 534 535
/***********************************************************************
 *              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 )
    {
536
        req->tid        = HandleToULong(id->UniqueThread);
537 538
        req->access     = access;
        req->attributes = attr ? attr->Attributes : 0;
539
        ret = wine_server_call( req );
540
        *handle = wine_server_ptr_handle( reply->handle );
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    }
    SERVER_END_REQ;
    return ret;
}


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

    SERVER_START_REQ( suspend_thread )
    {
557
        req->handle = wine_server_obj_handle( handle );
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
        if (!(ret = wine_server_call( req ))) *count = reply->count;
    }
    SERVER_END_REQ;
    return ret;
}


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

    SERVER_START_REQ( resume_thread )
    {
575
        req->handle = wine_server_obj_handle( handle );
576 577 578 579 580 581 582
        if (!(ret = wine_server_call( req ))) *count = reply->count;
    }
    SERVER_END_REQ;
    return ret;
}


583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
/******************************************************************************
 *              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;
}


605 606 607 608 609 610 611
/******************************************************************************
 *              NtTerminateThread  (NTDLL.@)
 *              ZwTerminateThread  (NTDLL.@)
 */
NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
{
    NTSTATUS ret;
612
    BOOL self;
613 614 615

    SERVER_START_REQ( terminate_thread )
    {
616
        req->handle    = wine_server_obj_handle( handle );
617 618 619 620 621 622
        req->exit_code = exit_code;
        ret = wine_server_call( req );
        self = !ret && reply->self;
    }
    SERVER_END_REQ;

623
    if (self) abort_thread( exit_code );
624 625 626 627 628 629 630 631 632 633 634 635 636
    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 )
    {
637
        req->handle = wine_server_obj_handle( handle );
638 639 640
        if (func)
        {
            req->call.type         = APC_USER;
641
            req->call.user.func    = wine_server_client_ptr( func );
642 643 644 645 646
            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 */
647 648 649 650 651 652 653 654 655 656 657 658 659 660
        ret = wine_server_call( req );
    }
    SERVER_END_REQ;
    return ret;
}


/***********************************************************************
 *              NtSetContextThread  (NTDLL.@)
 *              ZwSetContextThread  (NTDLL.@)
 */
NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
{
    NTSTATUS ret;
661
    DWORD dummy, i;
662
    BOOL self = FALSE;
663

664 665
#ifdef __i386__
    /* on i386 debug registers always require a server call */
666 667 668
    self = (handle == GetCurrentThread());
    if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
    {
669 670 671 672 673 674
        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);
675
    }
676
#endif
677

678
    if (!self)
679
    {
680 681 682 683
        context_t server_context;

        context_to_server( &server_context, context );

684
        SERVER_START_REQ( set_thread_context )
685
        {
686
            req->handle  = wine_server_obj_handle( handle );
687
            req->suspend = 0;
688
            wine_server_add_data( req, &server_context, sizeof(server_context) );
689 690 691 692 693 694 695 696
            ret = wine_server_call( req );
            self = reply->self;
        }
        SERVER_END_REQ;

        if (ret == STATUS_PENDING)
        {
            if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
697
            {
698
                for (i = 0; i < 100; i++)
699
                {
700 701
                    SERVER_START_REQ( set_thread_context )
                    {
702
                        req->handle  = wine_server_obj_handle( handle );
703
                        req->suspend = 0;
704
                        wine_server_add_data( req, &server_context, sizeof(server_context) );
705 706 707
                        ret = wine_server_call( req );
                    }
                    SERVER_END_REQ;
708 709 710 711 712 713 714
                    if (ret == STATUS_PENDING)
                    {
                        LARGE_INTEGER timeout;
                        timeout.QuadPart = -10000;
                        NtDelayExecution( FALSE, &timeout );
                    }
                    else break;
715
                }
716
                NtResumeThread( handle, &dummy );
717
            }
718
            if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
719
        }
720 721

        if (ret) return ret;
722 723
    }

724 725
    if (self) set_cpu_context( context );
    return STATUS_SUCCESS;
726 727 728
}


729 730 731 732 733
/* convert CPU-specific flags to generic server flags */
static inline unsigned int get_server_context_flags( DWORD flags )
{
    unsigned int ret = 0;

734
    flags &= 0x3f;  /* mask CPU id flags */
735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
    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;
}

752 753 754 755 756 757 758
/***********************************************************************
 *              NtGetContextThread  (NTDLL.@)
 *              ZwGetContextThread  (NTDLL.@)
 */
NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
{
    NTSTATUS ret;
759
    DWORD dummy, i;
760 761
    DWORD needed_flags = context->ContextFlags;
    BOOL self = (handle == GetCurrentThread());
762

763 764 765 766
#ifdef __i386__
    /* on i386 debug registers always require a server call */
    if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
#endif
767

768
    if (!self)
769
    {
770 771 772
        unsigned int server_flags = get_server_context_flags( context->ContextFlags );
        context_t server_context;

773 774
        SERVER_START_REQ( get_thread_context )
        {
775
            req->handle  = wine_server_obj_handle( handle );
776
            req->flags   = server_flags;
777
            req->suspend = 0;
778
            wine_server_set_reply( req, &server_context, sizeof(server_context) );
779 780 781 782 783 784
            ret = wine_server_call( req );
            self = reply->self;
        }
        SERVER_END_REQ;

        if (ret == STATUS_PENDING)
785
        {
786
            if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
787
            {
788
                for (i = 0; i < 100; i++)
789
                {
790 791
                    SERVER_START_REQ( get_thread_context )
                    {
792
                        req->handle  = wine_server_obj_handle( handle );
793
                        req->flags   = server_flags;
794
                        req->suspend = 0;
795
                        wine_server_set_reply( req, &server_context, sizeof(server_context) );
796 797 798
                        ret = wine_server_call( req );
                    }
                    SERVER_END_REQ;
799 800 801 802 803 804 805
                    if (ret == STATUS_PENDING)
                    {
                        LARGE_INTEGER timeout;
                        timeout.QuadPart = -10000;
                        NtDelayExecution( FALSE, &timeout );
                    }
                    else break;
806
                }
807
                NtResumeThread( handle, &dummy );
808
            }
809
            if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
810
        }
811
        if (!ret) ret = context_from_server( context, &server_context );
812
        if (ret) return ret;
813
        needed_flags &= ~context->ContextFlags;
814 815
    }

816
    if (self)
817
    {
818 819
        if (needed_flags)
        {
820
            CONTEXT ctx;
821
            RtlCaptureContext( &ctx );
822
            copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
823
            context->ContextFlags |= ctx.ContextFlags & needed_flags;
824
        }
825 826
#ifdef __i386__
        /* update the cached version of the debug registers */
827
        if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
828
        {
829 830 831 832 833 834
            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;
835 836 837
        }
#endif
    }
838
    return STATUS_SUCCESS;
839
}
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855


/******************************************************************************
 *              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;
856
            const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
857 858 859

            SERVER_START_REQ( get_thread_info )
            {
860
                req->handle = wine_server_obj_handle( handle );
861 862 863 864
                req->tid_in = 0;
                if (!(status = wine_server_call( req )))
                {
                    info.ExitStatus             = reply->exit_code;
865
                    info.TebBaseAddress         = wine_server_get_ptr( reply->teb );
866 867
                    info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
                    info.ClientId.UniqueThread  = ULongToHandle(reply->tid);
868
                    info.AffinityMask           = reply->affinity & affinity_mask;
869 870 871 872 873 874 875 876 877 878 879 880
                    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;
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900
    case ThreadAffinityMask:
        {
            const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
            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;
901
    case ThreadTimes:
902 903 904 905 906 907
        {
            KERNEL_USER_TIMES   kusrt;
            /* We need to do a server call to get the creation time or exit time */
            /* This works on any thread */
            SERVER_START_REQ( get_thread_info )
            {
908
                req->handle = wine_server_obj_handle( handle );
909 910 911 912
                req->tid_in = 0;
                status = wine_server_call( req );
                if (status == STATUS_SUCCESS)
                {
913 914
                    kusrt.CreateTime.QuadPart = reply->creation_time;
                    kusrt.ExitTime.QuadPart = reply->exit_time;
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
                }
            }
            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
                {
933 934
                    static BOOL reported = FALSE;

935 936
                    kusrt.KernelTime.QuadPart = 0;
                    kusrt.UserTime.QuadPart = 0;
937 938 939 940 941 942 943
                    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;
                    }
944 945 946 947 948 949
                }
                if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
                if (ret_len) *ret_len = min( length, sizeof(kusrt) );
            }
        }
        return status;
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
    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 */
            {
                unsigned sel = tdi->Selector & ~3;  /* ignore RPL */
                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;
                    /* 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 */
                        else status = STATUS_ACCESS_DENIED;
                    }
                }
            }
            else
            {
                SERVER_START_REQ( get_selector_entry )
                {
988
                    req->handle = wine_server_obj_handle( handle );
989 990 991 992 993
                    req->entry = tdi->Selector >> 3;
                    status = wine_server_call( req );
                    if (!status)
                    {
                        if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
994
                            status = STATUS_ACCESS_VIOLATION;
995 996 997 998 999 1000 1001 1002 1003 1004
                        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;
            }
1005 1006 1007
            if (status == STATUS_SUCCESS && ret_len)
                /* yes, that's a bit strange, but it's the way it is */
                *ret_len = sizeof(LDT_ENTRY);
1008 1009 1010 1011 1012
#else
            status = STATUS_NOT_IMPLEMENTED;
#endif
            return status;
        }
1013 1014 1015 1016
    case ThreadAmILastThread:
        {
            SERVER_START_REQ(get_thread_info)
            {
1017
                req->handle = wine_server_obj_handle( handle );
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
                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;
        }
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    case ThreadPriority:
    case ThreadBasePriority:
    case ThreadImpersonationToken:
    case ThreadEnableAlignmentFaultFixup:
    case ThreadEventPair_Reusable:
    case ThreadQuerySetWin32StartAddress:
    case ThreadZeroTlsCell:
    case ThreadPerformanceCount:
    case ThreadIdealProcessor:
    case ThreadPriorityBoost:
    case ThreadSetTlsArrayAddress:
    case ThreadIsIoPending:
    default:
        FIXME( "info class %d not supported yet\n", class );
        return STATUS_NOT_IMPLEMENTED;
    }
}
1047 1048 1049 1050 1051 1052 1053 1054 1055


/******************************************************************************
 *              NtSetInformationThread  (NTDLL.@)
 *              ZwSetInformationThread  (NTDLL.@)
 */
NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
                                        LPCVOID data, ULONG length )
{
1056
    NTSTATUS status;
1057 1058 1059 1060 1061
    switch(class)
    {
    case ThreadZeroTlsCell:
        if (handle == GetCurrentThread())
        {
1062
            LIST_ENTRY *entry;
1063 1064 1065
            DWORD index;

            if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1066
            index = *(const DWORD *)data;
1067
            if (index < TLS_MINIMUM_AVAILABLE)
1068
            {
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
                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();
1089
            }
1090 1091 1092 1093 1094
            return STATUS_SUCCESS;
        }
        FIXME( "ZeroTlsCell not supported on other threads\n" );
        return STATUS_NOT_IMPLEMENTED;

1095 1096 1097 1098
    case ThreadImpersonationToken:
        {
            const HANDLE *phToken = data;
            if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1099 1100 1101
            TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
            SERVER_START_REQ( set_thread_info )
            {
1102 1103
                req->handle   = wine_server_obj_handle( handle );
                req->token    = wine_server_obj_handle( *phToken );
1104 1105 1106 1107
                req->mask     = SET_THREAD_INFO_TOKEN;
                status = wine_server_call( req );
            }
            SERVER_END_REQ;
1108
        }
1109 1110 1111 1112 1113 1114 1115
        return status;
    case ThreadBasePriority:
        {
            const DWORD *pprio = data;
            if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
            SERVER_START_REQ( set_thread_info )
            {
1116
                req->handle   = wine_server_obj_handle( handle );
1117 1118 1119 1120 1121 1122 1123
                req->priority = *pprio;
                req->mask     = SET_THREAD_INFO_PRIORITY;
                status = wine_server_call( req );
            }
            SERVER_END_REQ;
        }
        return status;
1124 1125
    case ThreadAffinityMask:
        {
1126 1127 1128
            const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
            const ULONG_PTR *paff = data;
            if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1129
            if (*paff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1130
            if (!*paff) return STATUS_INVALID_PARAMETER;
1131 1132
            SERVER_START_REQ( set_thread_info )
            {
1133
                req->handle   = wine_server_obj_handle( handle );
1134 1135 1136 1137 1138 1139 1140
                req->affinity = *paff;
                req->mask     = SET_THREAD_INFO_AFFINITY;
                status = wine_server_call( req );
            }
            SERVER_END_REQ;
        }
        return status;
1141 1142 1143 1144
    case ThreadHideFromDebugger:
        /* pretend the call succeeded to satisfy some code protectors */
        return STATUS_SUCCESS;

1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    case ThreadBasicInformation:
    case ThreadTimes:
    case ThreadPriority:
    case ThreadDescriptorTableEntry:
    case ThreadEnableAlignmentFaultFixup:
    case ThreadEventPair_Reusable:
    case ThreadQuerySetWin32StartAddress:
    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;
    }
}