4 * Copyright 1996, 2003 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * 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
22 #include "wine/port.h"
26 #include <sys/types.h>
27 #ifdef HAVE_SYS_MMAN_H
30 #ifdef HAVE_SYS_TIMES_H
31 #include <sys/times.h>
34 #define NONAMELESSUNION
36 #define WIN32_NO_STATUS
38 #include "wine/library.h"
39 #include "wine/server.h"
40 #include "wine/debug.h"
41 #include "ntdll_misc.h"
43 #include "wine/exception.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(thread);
46 WINE_DECLARE_DEBUG_CHANNEL(relay);
48 struct _KUSER_SHARED_DATA *user_shared_data = NULL;
50 PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter = NULL;
52 /* info passed to a starting thread */
56 PRTL_THREAD_START_ROUTINE entry_point;
60 static PEB_LDR_DATA ldr;
61 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 size_t sigstack_total_size;
68 static ULONG sigstack_zero_bits;
69 static int nb_threads = 1;
71 static RTL_CRITICAL_SECTION ldt_section;
72 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
75 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
76 0, 0, { (DWORD_PTR)(__FILE__ ": ldt_section") }
78 static RTL_CRITICAL_SECTION ldt_section = { &critsect_debug, -1, 0, 0, 0, 0 };
79 static sigset_t ldt_sigset;
81 /***********************************************************************
82 * locking for LDT routines
84 static void ldt_lock(void)
88 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
89 RtlEnterCriticalSection( &ldt_section );
90 if (ldt_section.RecursionCount == 1) ldt_sigset = sigset;
93 static void ldt_unlock(void)
95 if (ldt_section.RecursionCount == 1)
97 sigset_t sigset = ldt_sigset;
98 RtlLeaveCriticalSection( &ldt_section );
99 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
101 else RtlLeaveCriticalSection( &ldt_section );
105 /***********************************************************************
108 static inline NTSTATUS init_teb( TEB *teb )
110 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
112 teb->Tib.ExceptionList = (void *)~0UL;
113 teb->Tib.StackBase = (void *)~0UL;
114 teb->Tib.Self = &teb->Tib;
115 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
116 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
118 if (!(thread_data->fs = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
119 thread_data->request_fd = -1;
120 thread_data->reply_fd = -1;
121 thread_data->wait_fd[0] = -1;
122 thread_data->wait_fd[1] = -1;
124 return STATUS_SUCCESS;
128 /***********************************************************************
131 * Copy a unicode string from the startup info.
133 static inline void get_unicode_string( UNICODE_STRING *str, WCHAR **src, WCHAR **dst, UINT len )
137 str->MaximumLength = len + sizeof(WCHAR);
138 memcpy( str->Buffer, *src, len );
139 str->Buffer[len / sizeof(WCHAR)] = 0;
140 *src += len / sizeof(WCHAR);
141 *dst += len / sizeof(WCHAR) + 1;
144 /***********************************************************************
145 * init_user_process_params
147 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
149 static NTSTATUS init_user_process_params( SIZE_T data_size, HANDLE *exe_file )
153 SIZE_T info_size, env_size, size, alloc_size;
155 startup_info_t *info;
156 RTL_USER_PROCESS_PARAMETERS *params = NULL;
158 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, data_size )))
159 return STATUS_NO_MEMORY;
161 SERVER_START_REQ( get_startup_info )
163 wine_server_set_reply( req, info, data_size );
164 if (!(status = wine_server_call( req )))
166 data_size = wine_server_reply_size( reply );
167 info_size = reply->info_size;
168 env_size = data_size - info_size;
169 *exe_file = wine_server_ptr_handle( reply->exe_file );
173 if (status != STATUS_SUCCESS) goto done;
175 size = sizeof(*params);
176 size += MAX_NT_PATH_LENGTH * sizeof(WCHAR);
177 size += info->dllpath_len + sizeof(WCHAR);
178 size += info->imagepath_len + sizeof(WCHAR);
179 size += info->cmdline_len + sizeof(WCHAR);
180 size += info->title_len + sizeof(WCHAR);
181 size += info->desktop_len + sizeof(WCHAR);
182 size += info->shellinfo_len + sizeof(WCHAR);
183 size += info->runtime_len + sizeof(WCHAR);
186 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &alloc_size,
187 MEM_COMMIT, PAGE_READWRITE );
188 if (status != STATUS_SUCCESS) goto done;
190 NtCurrentTeb()->Peb->ProcessParameters = params;
191 params->AllocationSize = alloc_size;
193 params->Flags = PROCESS_PARAMS_FLAG_NORMALIZED;
194 params->DebugFlags = info->debug_flags;
195 params->ConsoleHandle = wine_server_ptr_handle( info->console );
196 params->ConsoleFlags = info->console_flags;
197 params->hStdInput = wine_server_ptr_handle( info->hstdin );
198 params->hStdOutput = wine_server_ptr_handle( info->hstdout );
199 params->hStdError = wine_server_ptr_handle( info->hstderr );
200 params->dwX = info->x;
201 params->dwY = info->y;
202 params->dwXSize = info->xsize;
203 params->dwYSize = info->ysize;
204 params->dwXCountChars = info->xchars;
205 params->dwYCountChars = info->ychars;
206 params->dwFillAttribute = info->attribute;
207 params->dwFlags = info->flags;
208 params->wShowWindow = info->show;
210 src = (WCHAR *)(info + 1);
211 dst = (WCHAR *)(params + 1);
213 /* current directory needs more space */
214 get_unicode_string( ¶ms->CurrentDirectory.DosPath, &src, &dst, info->curdir_len );
215 params->CurrentDirectory.DosPath.MaximumLength = MAX_NT_PATH_LENGTH * sizeof(WCHAR);
216 dst = (WCHAR *)(params + 1) + MAX_NT_PATH_LENGTH;
218 get_unicode_string( ¶ms->DllPath, &src, &dst, info->dllpath_len );
219 get_unicode_string( ¶ms->ImagePathName, &src, &dst, info->imagepath_len );
220 get_unicode_string( ¶ms->CommandLine, &src, &dst, info->cmdline_len );
221 get_unicode_string( ¶ms->WindowTitle, &src, &dst, info->title_len );
222 get_unicode_string( ¶ms->Desktop, &src, &dst, info->desktop_len );
223 get_unicode_string( ¶ms->ShellInfo, &src, &dst, info->shellinfo_len );
225 /* runtime info isn't a real string */
226 params->RuntimeInfo.Buffer = dst;
227 params->RuntimeInfo.Length = params->RuntimeInfo.MaximumLength = info->runtime_len;
228 memcpy( dst, src, info->runtime_len );
230 /* environment needs to be a separate memory block */
232 alloc_size = max( 1, env_size );
233 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &alloc_size,
234 MEM_COMMIT, PAGE_READWRITE );
235 if (status != STATUS_SUCCESS) goto done;
236 memcpy( ptr, (char *)info + info_size, env_size );
237 params->Environment = ptr;
240 RtlFreeHeap( GetProcessHeap(), 0, info );
245 /***********************************************************************
248 * Setup the initial thread.
250 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
252 HANDLE thread_init(void)
257 SIZE_T size, info_size;
260 struct ntdll_thread_data *thread_data;
261 static struct debug_info debug_info; /* debug info for initial thread */
265 /* reserve space for shared user data */
267 addr = (void *)0x7ffe0000;
269 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE );
270 user_shared_data = addr;
272 /* allocate and initialize the PEB */
276 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
277 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
280 peb->NumberOfProcessors = 1;
281 peb->ProcessParameters = ¶ms;
282 peb->TlsBitmap = &tls_bitmap;
283 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
284 peb->FlsBitmap = &fls_bitmap;
286 params.CurrentDirectory.DosPath.Buffer = current_dir;
287 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
288 params.wShowWindow = 1; /* SW_SHOWNORMAL */
289 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
290 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
291 sizeof(peb->TlsExpansionBitmapBits) * 8 );
292 RtlInitializeBitMap( &fls_bitmap, peb->FlsBitmapBits, sizeof(peb->FlsBitmapBits) * 8 );
293 InitializeListHead( &peb->FlsListHead );
294 InitializeListHead( &ldr.InLoadOrderModuleList );
295 InitializeListHead( &ldr.InMemoryOrderModuleList );
296 InitializeListHead( &ldr.InInitializationOrderModuleList );
297 InitializeListHead( &tls_links );
299 /* allocate and initialize the initial TEB */
301 sigstack_total_size = get_signal_stack_total_size();
302 while (1U << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
303 assert( 1U << sigstack_zero_bits == sigstack_total_size ); /* must be a power of 2 */
304 assert( sigstack_total_size >= sizeof(TEB) + sizeof(struct startup_info) );
307 size = sigstack_total_size;
308 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
309 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
313 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
314 thread_data->debug_info = &debug_info;
315 InsertHeadList( &tls_links, &teb->TlsLinks );
317 signal_init_thread( teb );
318 virtual_init_threading();
320 debug_info.str_pos = debug_info.strings;
321 debug_info.out_pos = debug_info.output;
324 /* setup the server connection */
325 server_init_process();
326 info_size = server_init_thread( peb );
328 /* create the process heap */
329 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
331 MESSAGE( "wine: failed to create the process heap\n" );
335 /* allocate user parameters */
338 init_user_process_params( info_size, &exe_file );
342 /* This is wine specific: we have no parent (we're started from unix)
343 * so, create a simple console with bare handles to unix stdio
345 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdInput );
346 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdOutput );
347 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, ¶ms.hStdError );
350 /* initialize LDT locking */
351 wine_ldt_init_locking( ldt_lock, ldt_unlock );
353 /* initialize time values in user_shared_data */
354 NtQuerySystemTime( &now );
355 user_shared_data->SystemTime.LowPart = now.u.LowPart;
356 user_shared_data->SystemTime.High1Time = user_shared_data->SystemTime.High2Time = now.u.HighPart;
357 user_shared_data->u.TickCountQuad = (now.QuadPart - server_start_time) / 10000;
358 user_shared_data->u.TickCount.High2Time = user_shared_data->u.TickCount.High1Time;
359 user_shared_data->TickCountLowDeprecated = user_shared_data->u.TickCount.LowPart;
360 user_shared_data->TickCountMultiplier = 1 << 24;
366 /***********************************************************************
369 void abort_thread( int status )
371 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
372 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1) _exit( status );
374 close( ntdll_get_thread_data()->wait_fd[0] );
375 close( ntdll_get_thread_data()->wait_fd[1] );
376 close( ntdll_get_thread_data()->reply_fd );
377 close( ntdll_get_thread_data()->request_fd );
378 pthread_exit( UIntToPtr(status) );
382 /***********************************************************************
385 void exit_thread( int status )
387 static void *prev_teb;
390 if (status) /* send the exit code to the server (0 is already the default) */
392 SERVER_START_REQ( terminate_thread )
394 req->handle = wine_server_obj_handle( GetCurrentThread() );
395 req->exit_code = status;
396 wine_server_call( req );
401 if (interlocked_xchg_add( &nb_threads, -1 ) <= 1)
403 LdrShutdownProcess();
409 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
411 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
412 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
414 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
416 if ((teb = interlocked_xchg_ptr( &prev_teb, NtCurrentTeb() )))
418 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
421 pthread_join( thread_data->pthread_id, NULL );
422 wine_ldt_free_fs( thread_data->fs );
424 NtFreeVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
426 NtFreeVirtualMemory( GetCurrentProcess(), (void **)&teb, &size, MEM_RELEASE );
429 close( ntdll_get_thread_data()->wait_fd[0] );
430 close( ntdll_get_thread_data()->wait_fd[1] );
431 close( ntdll_get_thread_data()->reply_fd );
432 close( ntdll_get_thread_data()->request_fd );
433 pthread_exit( UIntToPtr(status) );
437 /***********************************************************************
440 * Startup routine for a newly created thread.
442 static void start_thread( struct startup_info *info )
444 TEB *teb = info->teb;
445 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
446 PRTL_THREAD_START_ROUTINE func = info->entry_point;
447 void *arg = info->entry_arg;
448 struct debug_info debug_info;
450 debug_info.str_pos = debug_info.strings;
451 debug_info.out_pos = debug_info.output;
452 thread_data->debug_info = &debug_info;
453 thread_data->pthread_id = pthread_self();
455 signal_init_thread( teb );
456 server_init_thread( func );
457 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
460 InsertHeadList( &tls_links, &teb->TlsLinks );
463 MODULE_DllThreadAttach( NULL );
466 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func, arg );
468 call_thread_entry_point( (LPTHREAD_START_ROUTINE)func, arg );
472 /***********************************************************************
473 * RtlCreateUserThread (NTDLL.@)
475 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
476 BOOLEAN suspended, PVOID stack_addr,
477 SIZE_T stack_reserve, SIZE_T stack_commit,
478 PRTL_THREAD_START_ROUTINE start, void *param,
479 HANDLE *handle_ptr, CLIENT_ID *id )
482 pthread_t pthread_id;
484 struct ntdll_thread_data *thread_data = NULL;
485 struct ntdll_thread_regs *thread_regs;
486 struct startup_info *info = NULL;
495 if (process != NtCurrentProcess())
500 memset( &call, 0, sizeof(call) );
502 call.create_thread.type = APC_CREATE_THREAD;
503 call.create_thread.func = wine_server_client_ptr( start );
504 call.create_thread.arg = wine_server_client_ptr( param );
505 call.create_thread.reserve = stack_reserve;
506 call.create_thread.commit = stack_commit;
507 call.create_thread.suspend = suspended;
508 status = NTDLL_queue_process_apc( process, &call, &result );
509 if (status != STATUS_SUCCESS) return status;
511 if (result.create_thread.status == STATUS_SUCCESS)
513 if (id) id->UniqueThread = ULongToHandle(result.create_thread.tid);
514 if (handle_ptr) *handle_ptr = wine_server_ptr_handle( result.create_thread.handle );
515 else NtClose( wine_server_ptr_handle( result.create_thread.handle ));
517 return result.create_thread.status;
520 if (server_pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
521 wine_server_send_fd( request_pipe[0] );
523 SERVER_START_REQ( new_thread )
525 req->access = THREAD_ALL_ACCESS;
526 req->attributes = 0; /* FIXME */
527 req->suspend = suspended;
528 req->request_fd = request_pipe[0];
529 if (!(status = wine_server_call( req )))
531 handle = wine_server_ptr_handle( reply->handle );
534 close( request_pipe[0] );
540 close( request_pipe[1] );
544 pthread_sigmask( SIG_BLOCK, &server_block_set, &sigset );
547 size = sigstack_total_size;
548 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
549 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
552 teb->Peb = NtCurrentTeb()->Peb;
553 info = (struct startup_info *)(teb + 1);
555 info->entry_point = start;
556 info->entry_arg = param;
558 if ((status = init_teb( teb ))) goto error;
560 teb->ClientId.UniqueProcess = ULongToHandle(GetCurrentProcessId());
561 teb->ClientId.UniqueThread = ULongToHandle(tid);
563 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
564 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
565 thread_data->request_fd = request_pipe[1];
567 /* inherit debug registers from parent thread */
568 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
569 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
570 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
571 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
572 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
573 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
575 if ((status = virtual_alloc_thread_stack( teb, stack_reserve, stack_commit ))) goto error;
577 pthread_attr_init( &attr );
578 pthread_attr_setstack( &attr, teb->DeallocationStack,
579 (char *)teb->Tib.StackBase - (char *)teb->DeallocationStack );
580 pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM ); /* force creating a kernel thread */
581 interlocked_xchg_add( &nb_threads, 1 );
582 if (pthread_create( &pthread_id, &attr, (void * (*)(void *))start_thread, info ))
584 interlocked_xchg_add( &nb_threads, -1 );
585 pthread_attr_destroy( &attr );
587 NtFreeVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, MEM_RELEASE );
588 status = STATUS_NO_MEMORY;
591 pthread_attr_destroy( &attr );
592 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
594 if (id) id->UniqueThread = ULongToHandle(tid);
595 if (handle_ptr) *handle_ptr = handle;
596 else NtClose( handle );
598 return STATUS_SUCCESS;
601 if (thread_data) wine_ldt_free_fs( thread_data->fs );
605 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
607 if (handle) NtClose( handle );
608 pthread_sigmask( SIG_SETMASK, &sigset, NULL );
609 close( request_pipe[1] );
614 /***********************************************************************
615 * NtOpenThread (NTDLL.@)
616 * ZwOpenThread (NTDLL.@)
618 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
619 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
623 SERVER_START_REQ( open_thread )
625 req->tid = HandleToULong(id->UniqueThread);
626 req->access = access;
627 req->attributes = attr ? attr->Attributes : 0;
628 ret = wine_server_call( req );
629 *handle = wine_server_ptr_handle( reply->handle );
636 /******************************************************************************
637 * NtSuspendThread (NTDLL.@)
638 * ZwSuspendThread (NTDLL.@)
640 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
644 SERVER_START_REQ( suspend_thread )
646 req->handle = wine_server_obj_handle( handle );
647 if (!(ret = wine_server_call( req ))) *count = reply->count;
654 /******************************************************************************
655 * NtResumeThread (NTDLL.@)
656 * ZwResumeThread (NTDLL.@)
658 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
662 SERVER_START_REQ( resume_thread )
664 req->handle = wine_server_obj_handle( handle );
665 if (!(ret = wine_server_call( req ))) *count = reply->count;
672 /******************************************************************************
673 * NtAlertResumeThread (NTDLL.@)
674 * ZwAlertResumeThread (NTDLL.@)
676 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
678 FIXME( "stub: should alert thread %p\n", handle );
679 return NtResumeThread( handle, count );
683 /******************************************************************************
684 * NtAlertThread (NTDLL.@)
685 * ZwAlertThread (NTDLL.@)
687 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
689 FIXME( "stub: %p\n", handle );
690 return STATUS_NOT_IMPLEMENTED;
694 /******************************************************************************
695 * NtTerminateThread (NTDLL.@)
696 * ZwTerminateThread (NTDLL.@)
698 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
703 SERVER_START_REQ( terminate_thread )
705 req->handle = wine_server_obj_handle( handle );
706 req->exit_code = exit_code;
707 ret = wine_server_call( req );
708 self = !ret && reply->self;
715 if (last) _exit( exit_code );
716 else abort_thread( exit_code );
722 /******************************************************************************
723 * NtQueueApcThread (NTDLL.@)
725 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
726 ULONG_PTR arg2, ULONG_PTR arg3 )
729 SERVER_START_REQ( queue_apc )
731 req->handle = wine_server_obj_handle( handle );
734 req->call.type = APC_USER;
735 req->call.user.func = wine_server_client_ptr( func );
736 req->call.user.args[0] = arg1;
737 req->call.user.args[1] = arg2;
738 req->call.user.args[2] = arg3;
740 else req->call.type = APC_NONE; /* wake up only */
741 ret = wine_server_call( req );
748 /***********************************************************************
749 * NtSetContextThread (NTDLL.@)
750 * ZwSetContextThread (NTDLL.@)
752 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
759 /* on i386 debug registers always require a server call */
760 self = (handle == GetCurrentThread());
761 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
763 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
764 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
765 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
766 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
772 context_t server_context;
774 context_to_server( &server_context, context );
776 SERVER_START_REQ( set_thread_context )
778 req->handle = wine_server_obj_handle( handle );
780 wine_server_add_data( req, &server_context, sizeof(server_context) );
781 ret = wine_server_call( req );
786 if (ret == STATUS_PENDING)
788 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
790 for (i = 0; i < 100; i++)
792 SERVER_START_REQ( set_thread_context )
794 req->handle = wine_server_obj_handle( handle );
796 wine_server_add_data( req, &server_context, sizeof(server_context) );
797 ret = wine_server_call( req );
800 if (ret == STATUS_PENDING)
802 LARGE_INTEGER timeout;
803 timeout.QuadPart = -10000;
804 NtDelayExecution( FALSE, &timeout );
808 NtResumeThread( handle, &dummy );
810 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
816 if (self) set_cpu_context( context );
817 return STATUS_SUCCESS;
821 /* convert CPU-specific flags to generic server flags */
822 static inline unsigned int get_server_context_flags( DWORD flags )
824 unsigned int ret = 0;
826 flags &= 0x3f; /* mask CPU id flags */
827 if (flags & CONTEXT_CONTROL) ret |= SERVER_CTX_CONTROL;
828 if (flags & CONTEXT_INTEGER) ret |= SERVER_CTX_INTEGER;
829 #ifdef CONTEXT_SEGMENTS
830 if (flags & CONTEXT_SEGMENTS) ret |= SERVER_CTX_SEGMENTS;
832 #ifdef CONTEXT_FLOATING_POINT
833 if (flags & CONTEXT_FLOATING_POINT) ret |= SERVER_CTX_FLOATING_POINT;
835 #ifdef CONTEXT_DEBUG_REGISTERS
836 if (flags & CONTEXT_DEBUG_REGISTERS) ret |= SERVER_CTX_DEBUG_REGISTERS;
838 #ifdef CONTEXT_EXTENDED_REGISTERS
839 if (flags & CONTEXT_EXTENDED_REGISTERS) ret |= SERVER_CTX_EXTENDED_REGISTERS;
844 /***********************************************************************
845 * NtGetContextThread (NTDLL.@)
846 * ZwGetContextThread (NTDLL.@)
848 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
852 DWORD needed_flags = context->ContextFlags;
853 BOOL self = (handle == GetCurrentThread());
856 /* on i386 debug registers always require a server call */
857 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
862 unsigned int server_flags = get_server_context_flags( context->ContextFlags );
863 context_t server_context;
865 SERVER_START_REQ( get_thread_context )
867 req->handle = wine_server_obj_handle( handle );
868 req->flags = server_flags;
870 wine_server_set_reply( req, &server_context, sizeof(server_context) );
871 ret = wine_server_call( req );
876 if (ret == STATUS_PENDING)
878 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
880 for (i = 0; i < 100; i++)
882 SERVER_START_REQ( get_thread_context )
884 req->handle = wine_server_obj_handle( handle );
885 req->flags = server_flags;
887 wine_server_set_reply( req, &server_context, sizeof(server_context) );
888 ret = wine_server_call( req );
891 if (ret == STATUS_PENDING)
893 LARGE_INTEGER timeout;
894 timeout.QuadPart = -10000;
895 NtDelayExecution( FALSE, &timeout );
899 NtResumeThread( handle, &dummy );
901 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
903 if (!ret) ret = context_from_server( context, &server_context );
905 needed_flags &= ~context->ContextFlags;
913 RtlCaptureContext( &ctx );
914 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
915 context->ContextFlags |= ctx.ContextFlags & needed_flags;
918 /* update the cached version of the debug registers */
919 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
921 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
922 regs->dr0 = context->Dr0;
923 regs->dr1 = context->Dr1;
924 regs->dr2 = context->Dr2;
925 regs->dr3 = context->Dr3;
926 regs->dr6 = context->Dr6;
927 regs->dr7 = context->Dr7;
931 return STATUS_SUCCESS;
935 /******************************************************************************
936 * NtQueryInformationThread (NTDLL.@)
937 * ZwQueryInformationThread (NTDLL.@)
939 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
940 void *data, ULONG length, ULONG *ret_len )
946 case ThreadBasicInformation:
948 THREAD_BASIC_INFORMATION info;
949 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
951 SERVER_START_REQ( get_thread_info )
953 req->handle = wine_server_obj_handle( handle );
955 if (!(status = wine_server_call( req )))
957 info.ExitStatus = reply->exit_code;
958 info.TebBaseAddress = wine_server_get_ptr( reply->teb );
959 info.ClientId.UniqueProcess = ULongToHandle(reply->pid);
960 info.ClientId.UniqueThread = ULongToHandle(reply->tid);
961 info.AffinityMask = reply->affinity & affinity_mask;
962 info.Priority = reply->priority;
963 info.BasePriority = reply->priority; /* FIXME */
967 if (status == STATUS_SUCCESS)
969 if (data) memcpy( data, &info, min( length, sizeof(info) ));
970 if (ret_len) *ret_len = min( length, sizeof(info) );
974 case ThreadAffinityMask:
976 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
977 ULONG_PTR affinity = 0;
979 SERVER_START_REQ( get_thread_info )
981 req->handle = wine_server_obj_handle( handle );
983 if (!(status = wine_server_call( req )))
984 affinity = reply->affinity & affinity_mask;
987 if (status == STATUS_SUCCESS)
989 if (data) memcpy( data, &affinity, min( length, sizeof(affinity) ));
990 if (ret_len) *ret_len = min( length, sizeof(affinity) );
996 KERNEL_USER_TIMES kusrt;
997 /* We need to do a server call to get the creation time or exit time */
998 /* This works on any thread */
999 SERVER_START_REQ( get_thread_info )
1001 req->handle = wine_server_obj_handle( handle );
1003 status = wine_server_call( req );
1004 if (status == STATUS_SUCCESS)
1006 kusrt.CreateTime.QuadPart = reply->creation_time;
1007 kusrt.ExitTime.QuadPart = reply->exit_time;
1011 if (status == STATUS_SUCCESS)
1013 /* We call times(2) for kernel time or user time */
1014 /* We can only (portably) do this for the current thread */
1015 if (handle == GetCurrentThread())
1017 struct tms time_buf;
1018 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1021 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1022 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1026 static BOOL reported = FALSE;
1028 kusrt.KernelTime.QuadPart = 0;
1029 kusrt.UserTime.QuadPart = 0;
1031 TRACE("Cannot get kerneltime or usertime of other threads\n");
1034 FIXME("Cannot get kerneltime or usertime of other threads\n");
1038 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1039 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1043 case ThreadDescriptorTableEntry:
1046 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1047 if (length < sizeof(*tdi))
1048 status = STATUS_INFO_LENGTH_MISMATCH;
1049 else if (!(tdi->Selector & 4)) /* GDT selector */
1051 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1052 status = STATUS_SUCCESS;
1053 if (!sel) /* null selector */
1054 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1057 tdi->Entry.BaseLow = 0;
1058 tdi->Entry.HighWord.Bits.BaseMid = 0;
1059 tdi->Entry.HighWord.Bits.BaseHi = 0;
1060 tdi->Entry.LimitLow = 0xffff;
1061 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1062 tdi->Entry.HighWord.Bits.Dpl = 3;
1063 tdi->Entry.HighWord.Bits.Sys = 0;
1064 tdi->Entry.HighWord.Bits.Pres = 1;
1065 tdi->Entry.HighWord.Bits.Granularity = 1;
1066 tdi->Entry.HighWord.Bits.Default_Big = 1;
1067 tdi->Entry.HighWord.Bits.Type = 0x12;
1068 /* it has to be one of the system GDT selectors */
1069 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1071 if (sel == (wine_get_cs() & ~3))
1072 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1073 else status = STATUS_ACCESS_DENIED;
1079 SERVER_START_REQ( get_selector_entry )
1081 req->handle = wine_server_obj_handle( handle );
1082 req->entry = tdi->Selector >> 3;
1083 status = wine_server_call( req );
1086 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1087 status = STATUS_ACCESS_VIOLATION;
1090 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1091 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1092 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1098 if (status == STATUS_SUCCESS && ret_len)
1099 /* yes, that's a bit strange, but it's the way it is */
1100 *ret_len = sizeof(LDT_ENTRY);
1102 status = STATUS_NOT_IMPLEMENTED;
1106 case ThreadAmILastThread:
1108 SERVER_START_REQ(get_thread_info)
1110 req->handle = wine_server_obj_handle( handle );
1112 status = wine_server_call( req );
1113 if (status == STATUS_SUCCESS)
1115 BOOLEAN last = reply->last;
1116 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1117 if (ret_len) *ret_len = min( length, sizeof(last) );
1123 case ThreadPriority:
1124 case ThreadBasePriority:
1125 case ThreadImpersonationToken:
1126 case ThreadEnableAlignmentFaultFixup:
1127 case ThreadEventPair_Reusable:
1128 case ThreadQuerySetWin32StartAddress:
1129 case ThreadZeroTlsCell:
1130 case ThreadPerformanceCount:
1131 case ThreadIdealProcessor:
1132 case ThreadPriorityBoost:
1133 case ThreadSetTlsArrayAddress:
1134 case ThreadIsIoPending:
1136 FIXME( "info class %d not supported yet\n", class );
1137 return STATUS_NOT_IMPLEMENTED;
1142 /******************************************************************************
1143 * NtSetInformationThread (NTDLL.@)
1144 * ZwSetInformationThread (NTDLL.@)
1146 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1147 LPCVOID data, ULONG length )
1152 case ThreadZeroTlsCell:
1153 if (handle == GetCurrentThread())
1158 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1159 index = *(const DWORD *)data;
1160 if (index < TLS_MINIMUM_AVAILABLE)
1162 RtlAcquirePebLock();
1163 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1165 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1166 teb->TlsSlots[index] = 0;
1168 RtlReleasePebLock();
1172 index -= TLS_MINIMUM_AVAILABLE;
1173 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1174 return STATUS_INVALID_PARAMETER;
1175 RtlAcquirePebLock();
1176 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1178 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1179 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1181 RtlReleasePebLock();
1183 return STATUS_SUCCESS;
1185 FIXME( "ZeroTlsCell not supported on other threads\n" );
1186 return STATUS_NOT_IMPLEMENTED;
1188 case ThreadImpersonationToken:
1190 const HANDLE *phToken = data;
1191 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1192 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1193 SERVER_START_REQ( set_thread_info )
1195 req->handle = wine_server_obj_handle( handle );
1196 req->token = wine_server_obj_handle( *phToken );
1197 req->mask = SET_THREAD_INFO_TOKEN;
1198 status = wine_server_call( req );
1203 case ThreadBasePriority:
1205 const DWORD *pprio = data;
1206 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1207 SERVER_START_REQ( set_thread_info )
1209 req->handle = wine_server_obj_handle( handle );
1210 req->priority = *pprio;
1211 req->mask = SET_THREAD_INFO_PRIORITY;
1212 status = wine_server_call( req );
1217 case ThreadAffinityMask:
1219 const ULONG_PTR affinity_mask = ((ULONG_PTR)1 << NtCurrentTeb()->Peb->NumberOfProcessors) - 1;
1220 const ULONG_PTR *paff = data;
1221 if (length != sizeof(ULONG_PTR)) return STATUS_INVALID_PARAMETER;
1222 if (*paff & ~affinity_mask) return STATUS_INVALID_PARAMETER;
1223 SERVER_START_REQ( set_thread_info )
1225 req->handle = wine_server_obj_handle( handle );
1226 req->affinity = *paff;
1227 req->mask = SET_THREAD_INFO_AFFINITY;
1228 status = wine_server_call( req );
1233 case ThreadBasicInformation:
1235 case ThreadPriority:
1236 case ThreadDescriptorTableEntry:
1237 case ThreadEnableAlignmentFaultFixup:
1238 case ThreadEventPair_Reusable:
1239 case ThreadQuerySetWin32StartAddress:
1240 case ThreadPerformanceCount:
1241 case ThreadAmILastThread:
1242 case ThreadIdealProcessor:
1243 case ThreadPriorityBoost:
1244 case ThreadSetTlsArrayAddress:
1245 case ThreadIsIoPending:
1247 FIXME( "info class %d not supported yet\n", class );
1248 return STATUS_NOT_IMPLEMENTED;