dbghelp: Get rid of long int issues on 64bit platforms.
[wine/hacks.git] / dlls / ntdll / thread.c
blob43eb0cdd61c67f2d21438779ac09503f1bb0d4c4
1 /*
2 * NT threads support
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <sys/types.h>
26 #ifdef HAVE_SYS_MMAN_H
27 #include <sys/mman.h>
28 #endif
29 #ifdef HAVE_SYS_TIMES_H
30 #include <sys/times.h>
31 #endif
33 #define NONAMELESSUNION
34 #include "ntstatus.h"
35 #define WIN32_NO_STATUS
36 #include "thread.h"
37 #include "winternl.h"
38 #include "wine/library.h"
39 #include "wine/server.h"
40 #include "wine/pthread.h"
41 #include "wine/debug.h"
42 #include "ntdll_misc.h"
43 #include "wine/exception.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(thread);
47 /* info passed to a starting thread */
48 struct startup_info
50 struct wine_pthread_thread_info pthread_info;
51 PRTL_THREAD_START_ROUTINE entry_point;
52 void *entry_arg;
55 static PEB_LDR_DATA ldr;
56 static RTL_USER_PROCESS_PARAMETERS params; /* default parameters if no parent */
57 static WCHAR current_dir[MAX_NT_PATH_LENGTH];
58 static RTL_BITMAP tls_bitmap;
59 static RTL_BITMAP tls_expansion_bitmap;
60 static LIST_ENTRY tls_links;
61 static size_t sigstack_total_size;
62 static ULONG sigstack_zero_bits;
64 struct wine_pthread_functions pthread_functions = { NULL };
66 /***********************************************************************
67 * init_teb
69 static inline NTSTATUS init_teb( TEB *teb )
71 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
72 struct ntdll_thread_regs *thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
74 teb->Tib.ExceptionList = (void *)~0UL;
75 teb->Tib.StackBase = (void *)~0UL;
76 teb->Tib.Self = &teb->Tib;
77 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
78 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
80 if (!(thread_regs->fs = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
81 thread_data->request_fd = -1;
82 thread_data->reply_fd = -1;
83 thread_data->wait_fd[0] = -1;
84 thread_data->wait_fd[1] = -1;
86 return STATUS_SUCCESS;
90 /***********************************************************************
91 * free_teb
93 static inline void free_teb( TEB *teb )
95 SIZE_T size = 0;
96 void *addr = teb;
97 struct ntdll_thread_regs *thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
99 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
100 wine_ldt_free_fs( thread_regs->fs );
101 munmap( teb, sigstack_total_size );
105 /***********************************************************************
106 * fix_unicode_string
108 * Make sure the unicode string doesn't point beyond the end pointer
110 static inline void fix_unicode_string( UNICODE_STRING *str, char *end_ptr )
112 if ((char *)str->Buffer >= end_ptr)
114 str->Length = str->MaximumLength = 0;
115 str->Buffer = NULL;
116 return;
118 if ((char *)str->Buffer + str->MaximumLength > end_ptr)
120 str->MaximumLength = (end_ptr - (char *)str->Buffer) & ~(sizeof(WCHAR) - 1);
122 if (str->Length >= str->MaximumLength)
124 if (str->MaximumLength >= sizeof(WCHAR))
125 str->Length = str->MaximumLength - sizeof(WCHAR);
126 else
127 str->Length = str->MaximumLength = 0;
132 /***********************************************************************
133 * init_user_process_params
135 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
137 static NTSTATUS init_user_process_params( SIZE_T info_size, HANDLE *exe_file )
139 void *ptr;
140 SIZE_T env_size;
141 NTSTATUS status;
142 RTL_USER_PROCESS_PARAMETERS *params = NULL;
144 status = NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&params, 0, &info_size,
145 MEM_COMMIT, PAGE_READWRITE );
146 if (status != STATUS_SUCCESS) return status;
148 params->AllocationSize = info_size;
149 NtCurrentTeb()->Peb->ProcessParameters = params;
151 SERVER_START_REQ( get_startup_info )
153 wine_server_set_reply( req, params, info_size );
154 if (!(status = wine_server_call( req )))
156 info_size = wine_server_reply_size( reply );
157 *exe_file = reply->exe_file;
158 params->hStdInput = reply->hstdin;
159 params->hStdOutput = reply->hstdout;
160 params->hStdError = reply->hstderr;
163 SERVER_END_REQ;
164 if (status != STATUS_SUCCESS) return status;
166 if (params->Size > info_size) params->Size = info_size;
168 /* make sure the strings are valid */
169 fix_unicode_string( &params->CurrentDirectory.DosPath, (char *)info_size );
170 fix_unicode_string( &params->DllPath, (char *)info_size );
171 fix_unicode_string( &params->ImagePathName, (char *)info_size );
172 fix_unicode_string( &params->CommandLine, (char *)info_size );
173 fix_unicode_string( &params->WindowTitle, (char *)info_size );
174 fix_unicode_string( &params->Desktop, (char *)info_size );
175 fix_unicode_string( &params->ShellInfo, (char *)info_size );
176 fix_unicode_string( &params->RuntimeInfo, (char *)info_size );
178 /* environment needs to be a separate memory block */
179 env_size = info_size - params->Size;
180 if (!env_size) env_size = 1;
181 ptr = NULL;
182 status = NtAllocateVirtualMemory( NtCurrentProcess(), &ptr, 0, &env_size,
183 MEM_COMMIT, PAGE_READWRITE );
184 if (status != STATUS_SUCCESS) return status;
185 memcpy( ptr, (char *)params + params->Size, info_size - params->Size );
186 params->Environment = ptr;
188 RtlNormalizeProcessParams( params );
189 return status;
193 /***********************************************************************
194 * thread_init
196 * Setup the initial thread.
198 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
200 HANDLE thread_init(void)
202 PEB *peb;
203 TEB *teb;
204 void *addr;
205 SIZE_T size, info_size;
206 HANDLE exe_file = 0;
207 struct ntdll_thread_data *thread_data;
208 struct ntdll_thread_regs *thread_regs;
209 struct wine_pthread_thread_info thread_info;
210 static struct debug_info debug_info; /* debug info for initial thread */
212 virtual_init();
214 /* reserve space for shared user data */
216 addr = (void *)0x7ffe0000;
217 size = 0x10000;
218 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size, MEM_RESERVE, PAGE_READONLY );
220 /* allocate and initialize the PEB */
222 addr = NULL;
223 size = sizeof(*peb);
224 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 1, &size,
225 MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
226 peb = addr;
228 peb->NumberOfProcessors = 1;
229 peb->ProcessParameters = &params;
230 peb->TlsBitmap = &tls_bitmap;
231 peb->TlsExpansionBitmap = &tls_expansion_bitmap;
232 peb->LdrData = &ldr;
233 params.CurrentDirectory.DosPath.Buffer = current_dir;
234 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
235 params.wShowWindow = 1; /* SW_SHOWNORMAL */
236 RtlInitializeBitMap( &tls_bitmap, peb->TlsBitmapBits, sizeof(peb->TlsBitmapBits) * 8 );
237 RtlInitializeBitMap( &tls_expansion_bitmap, peb->TlsExpansionBitmapBits,
238 sizeof(peb->TlsExpansionBitmapBits) * 8 );
239 InitializeListHead( &ldr.InLoadOrderModuleList );
240 InitializeListHead( &ldr.InMemoryOrderModuleList );
241 InitializeListHead( &ldr.InInitializationOrderModuleList );
242 InitializeListHead( &tls_links );
244 /* allocate and initialize the initial TEB */
246 sigstack_total_size = get_signal_stack_total_size();
247 while (1 << sigstack_zero_bits < sigstack_total_size) sigstack_zero_bits++;
248 assert( 1 << sigstack_zero_bits == sigstack_total_size ); /* must be a power of 2 */
249 thread_info.teb_size = sigstack_total_size;
251 addr = NULL;
252 size = sigstack_total_size;
253 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
254 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE );
255 teb = addr;
256 teb->Peb = peb;
257 thread_info.teb_size = size;
258 init_teb( teb );
259 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
260 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
261 thread_data->debug_info = &debug_info;
262 InsertHeadList( &tls_links, &teb->TlsLinks );
264 thread_info.stack_base = NULL;
265 thread_info.stack_size = 0;
266 thread_info.teb_base = teb;
267 thread_info.teb_sel = thread_regs->fs;
268 wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
269 pthread_functions.init_current_teb( &thread_info );
270 pthread_functions.init_thread( &thread_info );
271 virtual_init_threading();
273 debug_info.str_pos = debug_info.strings;
274 debug_info.out_pos = debug_info.output;
275 debug_init();
277 /* setup the server connection */
278 server_init_process();
279 info_size = server_init_thread( thread_info.pid, thread_info.tid, NULL );
281 /* create the process heap */
282 if (!(peb->ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
284 MESSAGE( "wine: failed to create the process heap\n" );
285 exit(1);
288 /* allocate user parameters */
289 if (info_size)
291 init_user_process_params( info_size, &exe_file );
293 else
295 /* This is wine specific: we have no parent (we're started from unix)
296 * so, create a simple console with bare handles to unix stdio
298 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, OBJ_INHERIT, &params.hStdInput );
299 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdOutput );
300 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, OBJ_INHERIT, &params.hStdError );
302 return exe_file;
305 typedef LONG (WINAPI *PUNHANDLED_EXCEPTION_FILTER)(PEXCEPTION_POINTERS);
306 static PUNHANDLED_EXCEPTION_FILTER get_unhandled_exception_filter(void)
308 static PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter;
309 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
310 UNICODE_STRING module_name;
311 ANSI_STRING func_name;
312 HMODULE kernel32_handle;
314 if (unhandled_exception_filter) return unhandled_exception_filter;
316 RtlInitUnicodeString(&module_name, kernel32W);
317 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
319 if (LdrGetDllHandle( 0, 0, &module_name, &kernel32_handle ) == STATUS_SUCCESS)
320 LdrGetProcedureAddress( kernel32_handle, &func_name, 0,
321 (void **)&unhandled_exception_filter );
323 return unhandled_exception_filter;
326 /***********************************************************************
327 * start_thread
329 * Startup routine for a newly created thread.
331 static void start_thread( struct wine_pthread_thread_info *info )
333 TEB *teb = info->teb_base;
334 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
335 struct startup_info *startup_info = (struct startup_info *)info;
336 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
337 void *arg = startup_info->entry_arg;
338 struct debug_info debug_info;
339 SIZE_T size, page_size = getpagesize();
341 debug_info.str_pos = debug_info.strings;
342 debug_info.out_pos = debug_info.output;
343 thread_data->debug_info = &debug_info;
345 pthread_functions.init_current_teb( info );
346 SIGNAL_Init();
347 server_init_thread( info->pid, info->tid, func );
348 pthread_functions.init_thread( info );
350 /* allocate a memory view for the stack */
351 size = info->stack_size;
352 teb->DeallocationStack = info->stack_base;
353 NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
354 &size, MEM_SYSTEM, PAGE_READWRITE );
355 /* limit is lower than base since the stack grows down */
356 teb->Tib.StackBase = (char *)info->stack_base + info->stack_size;
357 teb->Tib.StackLimit = (char *)info->stack_base + page_size;
359 /* setup the guard page */
360 size = page_size;
361 NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size, PAGE_NOACCESS, NULL );
362 RtlFreeHeap( GetProcessHeap(), 0, info );
364 RtlAcquirePebLock();
365 InsertHeadList( &tls_links, &teb->TlsLinks );
366 RtlReleasePebLock();
368 /* NOTE: Windows does not have an exception handler around the call to
369 * the thread attach. We do for ease of debugging */
370 if (get_unhandled_exception_filter())
372 __TRY
374 MODULE_DllThreadAttach( NULL );
376 __EXCEPT(get_unhandled_exception_filter())
378 NtTerminateThread( GetCurrentThread(), GetExceptionCode() );
380 __ENDTRY
382 else
383 MODULE_DllThreadAttach( NULL );
385 func( arg );
389 /***********************************************************************
390 * RtlCreateUserThread (NTDLL.@)
392 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
393 BOOLEAN suspended, PVOID stack_addr,
394 SIZE_T stack_reserve, SIZE_T stack_commit,
395 PRTL_THREAD_START_ROUTINE start, void *param,
396 HANDLE *handle_ptr, CLIENT_ID *id )
398 struct ntdll_thread_data *thread_data;
399 struct ntdll_thread_regs *thread_regs = NULL;
400 struct startup_info *info = NULL;
401 void *addr = NULL;
402 HANDLE handle = 0;
403 TEB *teb;
404 DWORD tid = 0;
405 int request_pipe[2];
406 NTSTATUS status;
407 SIZE_T size, page_size = getpagesize();
409 if( ! is_current_process( process ) )
411 ERR("Unsupported on other process\n");
412 return STATUS_ACCESS_DENIED;
415 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
416 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
417 wine_server_send_fd( request_pipe[0] );
419 SERVER_START_REQ( new_thread )
421 req->access = THREAD_ALL_ACCESS;
422 req->attributes = 0; /* FIXME */
423 req->suspend = suspended;
424 req->request_fd = request_pipe[0];
425 if (!(status = wine_server_call( req )))
427 handle = reply->handle;
428 tid = reply->tid;
430 close( request_pipe[0] );
432 SERVER_END_REQ;
434 if (status) goto error;
436 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
438 status = STATUS_NO_MEMORY;
439 goto error;
442 addr = NULL;
443 size = sigstack_total_size;
444 if ((status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr, sigstack_zero_bits,
445 &size, MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE )))
446 goto error;
447 teb = addr;
448 teb->Peb = NtCurrentTeb()->Peb;
449 info->pthread_info.teb_size = size;
450 if ((status = init_teb( teb ))) goto error;
452 teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
453 teb->ClientId.UniqueThread = (HANDLE)tid;
455 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
456 thread_regs = (struct ntdll_thread_regs *)teb->SpareBytes1;
457 thread_data->request_fd = request_pipe[1];
459 info->pthread_info.teb_base = teb;
460 info->pthread_info.teb_sel = thread_regs->fs;
462 /* inherit debug registers from parent thread */
463 thread_regs->dr0 = ntdll_get_thread_regs()->dr0;
464 thread_regs->dr1 = ntdll_get_thread_regs()->dr1;
465 thread_regs->dr2 = ntdll_get_thread_regs()->dr2;
466 thread_regs->dr3 = ntdll_get_thread_regs()->dr3;
467 thread_regs->dr6 = ntdll_get_thread_regs()->dr6;
468 thread_regs->dr7 = ntdll_get_thread_regs()->dr7;
470 if (!stack_reserve || !stack_commit)
472 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
473 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
474 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
476 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
477 stack_reserve += page_size; /* for the guard page */
478 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
479 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
481 info->pthread_info.stack_base = NULL;
482 info->pthread_info.stack_size = stack_reserve;
483 info->pthread_info.entry = start_thread;
484 info->entry_point = start;
485 info->entry_arg = param;
487 if (pthread_functions.create_thread( &info->pthread_info ) == -1)
489 status = STATUS_NO_MEMORY;
490 goto error;
493 if (id) id->UniqueThread = (HANDLE)tid;
494 if (handle_ptr) *handle_ptr = handle;
495 else NtClose( handle );
497 return STATUS_SUCCESS;
499 error:
500 if (thread_regs) wine_ldt_free_fs( thread_regs->fs );
501 if (addr)
503 SIZE_T size = 0;
504 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
506 RtlFreeHeap( GetProcessHeap(), 0, info );
507 if (handle) NtClose( handle );
508 close( request_pipe[1] );
509 return status;
513 /***********************************************************************
514 * RtlExitUserThread (NTDLL.@)
516 void WINAPI RtlExitUserThread( ULONG status )
518 LdrShutdownThread();
519 server_exit_thread( status );
523 /***********************************************************************
524 * NtOpenThread (NTDLL.@)
525 * ZwOpenThread (NTDLL.@)
527 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
528 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
530 NTSTATUS ret;
532 SERVER_START_REQ( open_thread )
534 req->tid = (thread_id_t)id->UniqueThread;
535 req->access = access;
536 req->attributes = attr ? attr->Attributes : 0;
537 ret = wine_server_call( req );
538 *handle = reply->handle;
540 SERVER_END_REQ;
541 return ret;
545 /******************************************************************************
546 * NtSuspendThread (NTDLL.@)
547 * ZwSuspendThread (NTDLL.@)
549 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
551 NTSTATUS ret;
553 SERVER_START_REQ( suspend_thread )
555 req->handle = handle;
556 if (!(ret = wine_server_call( req ))) *count = reply->count;
558 SERVER_END_REQ;
559 return ret;
563 /******************************************************************************
564 * NtResumeThread (NTDLL.@)
565 * ZwResumeThread (NTDLL.@)
567 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
569 NTSTATUS ret;
571 SERVER_START_REQ( resume_thread )
573 req->handle = handle;
574 if (!(ret = wine_server_call( req ))) *count = reply->count;
576 SERVER_END_REQ;
577 return ret;
581 /******************************************************************************
582 * NtAlertResumeThread (NTDLL.@)
583 * ZwAlertResumeThread (NTDLL.@)
585 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
587 FIXME( "stub: should alert thread %p\n", handle );
588 return NtResumeThread( handle, count );
592 /******************************************************************************
593 * NtAlertThread (NTDLL.@)
594 * ZwAlertThread (NTDLL.@)
596 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
598 FIXME( "stub: %p\n", handle );
599 return STATUS_NOT_IMPLEMENTED;
603 /******************************************************************************
604 * NtTerminateThread (NTDLL.@)
605 * ZwTerminateThread (NTDLL.@)
607 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
609 NTSTATUS ret;
610 BOOL self, last;
612 SERVER_START_REQ( terminate_thread )
614 req->handle = handle;
615 req->exit_code = exit_code;
616 ret = wine_server_call( req );
617 self = !ret && reply->self;
618 last = reply->last;
620 SERVER_END_REQ;
622 if (self)
624 if (last) exit( exit_code );
625 else server_abort_thread( exit_code );
627 return ret;
631 /******************************************************************************
632 * NtQueueApcThread (NTDLL.@)
634 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
635 ULONG_PTR arg2, ULONG_PTR arg3 )
637 NTSTATUS ret;
638 SERVER_START_REQ( queue_apc )
640 req->handle = handle;
641 req->user = 1;
642 req->func = func;
643 req->arg1 = (void *)arg1;
644 req->arg2 = (void *)arg2;
645 req->arg3 = (void *)arg3;
646 ret = wine_server_call( req );
648 SERVER_END_REQ;
649 return ret;
653 /***********************************************************************
654 * NtSetContextThread (NTDLL.@)
655 * ZwSetContextThread (NTDLL.@)
657 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
659 NTSTATUS ret;
660 DWORD dummy, i;
661 BOOL self = FALSE;
663 #ifdef __i386__
664 /* on i386 debug registers always require a server call */
665 self = (handle == GetCurrentThread());
666 if (self && (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)))
668 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
669 self = (regs->dr0 == context->Dr0 && regs->dr1 == context->Dr1 &&
670 regs->dr2 == context->Dr2 && regs->dr3 == context->Dr3 &&
671 regs->dr6 == context->Dr6 && regs->dr7 == context->Dr7);
673 #endif
675 if (!self)
677 SERVER_START_REQ( set_thread_context )
679 req->handle = handle;
680 req->flags = context->ContextFlags;
681 req->suspend = 0;
682 wine_server_add_data( req, context, sizeof(*context) );
683 ret = wine_server_call( req );
684 self = reply->self;
686 SERVER_END_REQ;
688 if (ret == STATUS_PENDING)
690 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
692 for (i = 0; i < 100; i++)
694 SERVER_START_REQ( set_thread_context )
696 req->handle = handle;
697 req->flags = context->ContextFlags;
698 req->suspend = 0;
699 wine_server_add_data( req, context, sizeof(*context) );
700 ret = wine_server_call( req );
702 SERVER_END_REQ;
703 if (ret != STATUS_PENDING) break;
704 NtYieldExecution();
706 NtResumeThread( handle, &dummy );
708 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
711 if (ret) return ret;
714 if (self) set_cpu_context( context );
715 return STATUS_SUCCESS;
719 /* copy a context structure according to the flags */
720 static inline void copy_context( CONTEXT *to, const CONTEXT *from, DWORD flags )
722 #ifdef __i386__
723 flags &= ~CONTEXT_i386; /* get rid of CPU id */
724 if (flags & CONTEXT_INTEGER)
726 to->Eax = from->Eax;
727 to->Ebx = from->Ebx;
728 to->Ecx = from->Ecx;
729 to->Edx = from->Edx;
730 to->Esi = from->Esi;
731 to->Edi = from->Edi;
733 if (flags & CONTEXT_CONTROL)
735 to->Ebp = from->Ebp;
736 to->Esp = from->Esp;
737 to->Eip = from->Eip;
738 to->SegCs = from->SegCs;
739 to->SegSs = from->SegSs;
740 to->EFlags = from->EFlags;
742 if (flags & CONTEXT_SEGMENTS)
744 to->SegDs = from->SegDs;
745 to->SegEs = from->SegEs;
746 to->SegFs = from->SegFs;
747 to->SegGs = from->SegGs;
749 if (flags & CONTEXT_DEBUG_REGISTERS)
751 to->Dr0 = from->Dr0;
752 to->Dr1 = from->Dr1;
753 to->Dr2 = from->Dr2;
754 to->Dr3 = from->Dr3;
755 to->Dr6 = from->Dr6;
756 to->Dr7 = from->Dr7;
758 if (flags & CONTEXT_FLOATING_POINT)
760 to->FloatSave = from->FloatSave;
762 #elif defined(__x86_64__)
763 flags &= ~CONTEXT_AMD64; /* get rid of CPU id */
764 if (flags & CONTEXT_CONTROL)
766 to->Rbp = from->Rbp;
767 to->Rip = from->Rip;
768 to->Rsp = from->Rsp;
769 to->SegCs = from->SegCs;
770 to->SegSs = from->SegSs;
771 to->EFlags = from->EFlags;
772 to->MxCsr = from->MxCsr;
774 if (flags & CONTEXT_INTEGER)
776 to->Rax = from->Rax;
777 to->Rcx = from->Rcx;
778 to->Rdx = from->Rdx;
779 to->Rbx = from->Rbx;
780 to->Rsi = from->Rsi;
781 to->Rdi = from->Rdi;
782 to->R8 = from->R8;
783 to->R9 = from->R9;
784 to->R10 = from->R10;
785 to->R11 = from->R11;
786 to->R12 = from->R12;
787 to->R13 = from->R13;
788 to->R14 = from->R14;
789 to->R15 = from->R15;
791 if (flags & CONTEXT_SEGMENTS)
793 to->SegDs = from->SegDs;
794 to->SegEs = from->SegEs;
795 to->SegFs = from->SegFs;
796 to->SegGs = from->SegGs;
798 if (flags & CONTEXT_FLOATING_POINT)
800 to->u.FltSave = from->u.FltSave;
802 if (flags & CONTEXT_DEBUG_REGISTERS)
804 to->Dr0 = from->Dr0;
805 to->Dr1 = from->Dr1;
806 to->Dr2 = from->Dr2;
807 to->Dr3 = from->Dr3;
808 to->Dr6 = from->Dr6;
809 to->Dr7 = from->Dr7;
811 #elif defined(__sparc__)
812 flags &= ~CONTEXT_SPARC; /* get rid of CPU id */
813 if (flags & CONTEXT_CONTROL)
815 to->psr = from->psr;
816 to->pc = from->pc;
817 to->npc = from->npc;
818 to->y = from->y;
819 to->wim = from->wim;
820 to->tbr = from->tbr;
822 if (flags & CONTEXT_INTEGER)
824 to->g0 = from->g0;
825 to->g1 = from->g1;
826 to->g2 = from->g2;
827 to->g3 = from->g3;
828 to->g4 = from->g4;
829 to->g5 = from->g5;
830 to->g6 = from->g6;
831 to->g7 = from->g7;
832 to->o0 = from->o0;
833 to->o1 = from->o1;
834 to->o2 = from->o2;
835 to->o3 = from->o3;
836 to->o4 = from->o4;
837 to->o5 = from->o5;
838 to->o6 = from->o6;
839 to->o7 = from->o7;
840 to->l0 = from->l0;
841 to->l1 = from->l1;
842 to->l2 = from->l2;
843 to->l3 = from->l3;
844 to->l4 = from->l4;
845 to->l5 = from->l5;
846 to->l6 = from->l6;
847 to->l7 = from->l7;
848 to->i0 = from->i0;
849 to->i1 = from->i1;
850 to->i2 = from->i2;
851 to->i3 = from->i3;
852 to->i4 = from->i4;
853 to->i5 = from->i5;
854 to->i6 = from->i6;
855 to->i7 = from->i7;
857 if (flags & CONTEXT_FLOATING_POINT)
859 /* FIXME */
861 #elif defined(__powerpc__)
862 /* Has no CPU id */
863 if (flags & CONTEXT_CONTROL)
865 to->Msr = from->Msr;
866 to->Ctr = from->Ctr;
867 to->Iar = from->Iar;
869 if (flags & CONTEXT_INTEGER)
871 to->Gpr0 = from->Gpr0;
872 to->Gpr1 = from->Gpr1;
873 to->Gpr2 = from->Gpr2;
874 to->Gpr3 = from->Gpr3;
875 to->Gpr4 = from->Gpr4;
876 to->Gpr5 = from->Gpr5;
877 to->Gpr6 = from->Gpr6;
878 to->Gpr7 = from->Gpr7;
879 to->Gpr8 = from->Gpr8;
880 to->Gpr9 = from->Gpr9;
881 to->Gpr10 = from->Gpr10;
882 to->Gpr11 = from->Gpr11;
883 to->Gpr12 = from->Gpr12;
884 to->Gpr13 = from->Gpr13;
885 to->Gpr14 = from->Gpr14;
886 to->Gpr15 = from->Gpr15;
887 to->Gpr16 = from->Gpr16;
888 to->Gpr17 = from->Gpr17;
889 to->Gpr18 = from->Gpr18;
890 to->Gpr19 = from->Gpr19;
891 to->Gpr20 = from->Gpr20;
892 to->Gpr21 = from->Gpr21;
893 to->Gpr22 = from->Gpr22;
894 to->Gpr23 = from->Gpr23;
895 to->Gpr24 = from->Gpr24;
896 to->Gpr25 = from->Gpr25;
897 to->Gpr26 = from->Gpr26;
898 to->Gpr27 = from->Gpr27;
899 to->Gpr28 = from->Gpr28;
900 to->Gpr29 = from->Gpr29;
901 to->Gpr30 = from->Gpr30;
902 to->Gpr31 = from->Gpr31;
903 to->Xer = from->Xer;
904 to->Cr = from->Cr;
906 if (flags & CONTEXT_FLOATING_POINT)
908 to->Fpr0 = from->Fpr0;
909 to->Fpr1 = from->Fpr1;
910 to->Fpr2 = from->Fpr2;
911 to->Fpr3 = from->Fpr3;
912 to->Fpr4 = from->Fpr4;
913 to->Fpr5 = from->Fpr5;
914 to->Fpr6 = from->Fpr6;
915 to->Fpr7 = from->Fpr7;
916 to->Fpr8 = from->Fpr8;
917 to->Fpr9 = from->Fpr9;
918 to->Fpr10 = from->Fpr10;
919 to->Fpr11 = from->Fpr11;
920 to->Fpr12 = from->Fpr12;
921 to->Fpr13 = from->Fpr13;
922 to->Fpr14 = from->Fpr14;
923 to->Fpr15 = from->Fpr15;
924 to->Fpr16 = from->Fpr16;
925 to->Fpr17 = from->Fpr17;
926 to->Fpr18 = from->Fpr18;
927 to->Fpr19 = from->Fpr19;
928 to->Fpr20 = from->Fpr20;
929 to->Fpr21 = from->Fpr21;
930 to->Fpr22 = from->Fpr22;
931 to->Fpr23 = from->Fpr23;
932 to->Fpr24 = from->Fpr24;
933 to->Fpr25 = from->Fpr25;
934 to->Fpr26 = from->Fpr26;
935 to->Fpr27 = from->Fpr27;
936 to->Fpr28 = from->Fpr28;
937 to->Fpr29 = from->Fpr29;
938 to->Fpr30 = from->Fpr30;
939 to->Fpr31 = from->Fpr31;
940 to->Fpscr = from->Fpscr;
942 #else
943 #error You must implement context copying for your CPU
944 #endif
948 /***********************************************************************
949 * NtGetContextThread (NTDLL.@)
950 * ZwGetContextThread (NTDLL.@)
952 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
954 NTSTATUS ret;
955 CONTEXT ctx;
956 DWORD dummy, i;
957 DWORD needed_flags = context->ContextFlags;
958 BOOL self = (handle == GetCurrentThread());
960 #ifdef __i386__
961 /* on i386 debug registers always require a server call */
962 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386)) self = FALSE;
963 #endif
965 if (!self)
967 SERVER_START_REQ( get_thread_context )
969 req->handle = handle;
970 req->flags = context->ContextFlags;
971 req->suspend = 0;
972 wine_server_set_reply( req, &ctx, sizeof(ctx) );
973 ret = wine_server_call( req );
974 self = reply->self;
976 SERVER_END_REQ;
978 if (ret == STATUS_PENDING)
980 if (NtSuspendThread( handle, &dummy ) == STATUS_SUCCESS)
982 for (i = 0; i < 100; i++)
984 SERVER_START_REQ( get_thread_context )
986 req->handle = handle;
987 req->flags = context->ContextFlags;
988 req->suspend = 0;
989 wine_server_set_reply( req, &ctx, sizeof(ctx) );
990 ret = wine_server_call( req );
992 SERVER_END_REQ;
993 if (ret != STATUS_PENDING) break;
994 NtYieldExecution();
996 NtResumeThread( handle, &dummy );
998 if (ret == STATUS_PENDING) ret = STATUS_ACCESS_DENIED;
1000 if (ret) return ret;
1001 copy_context( context, &ctx, context->ContextFlags & ctx.ContextFlags );
1002 needed_flags &= ~ctx.ContextFlags;
1005 if (self)
1007 if (needed_flags)
1009 get_cpu_context( &ctx );
1010 copy_context( context, &ctx, ctx.ContextFlags & needed_flags );
1012 #ifdef __i386__
1013 /* update the cached version of the debug registers */
1014 if (context->ContextFlags & (CONTEXT_DEBUG_REGISTERS & ~CONTEXT_i386))
1016 struct ntdll_thread_regs * const regs = ntdll_get_thread_regs();
1017 regs->dr0 = context->Dr0;
1018 regs->dr1 = context->Dr1;
1019 regs->dr2 = context->Dr2;
1020 regs->dr3 = context->Dr3;
1021 regs->dr6 = context->Dr6;
1022 regs->dr7 = context->Dr7;
1024 #endif
1026 return STATUS_SUCCESS;
1030 /******************************************************************************
1031 * NtQueryInformationThread (NTDLL.@)
1032 * ZwQueryInformationThread (NTDLL.@)
1034 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
1035 void *data, ULONG length, ULONG *ret_len )
1037 NTSTATUS status;
1039 switch(class)
1041 case ThreadBasicInformation:
1043 THREAD_BASIC_INFORMATION info;
1045 SERVER_START_REQ( get_thread_info )
1047 req->handle = handle;
1048 req->tid_in = 0;
1049 if (!(status = wine_server_call( req )))
1051 info.ExitStatus = reply->exit_code;
1052 info.TebBaseAddress = reply->teb;
1053 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
1054 info.ClientId.UniqueThread = (HANDLE)reply->tid;
1055 info.AffinityMask = reply->affinity;
1056 info.Priority = reply->priority;
1057 info.BasePriority = reply->priority; /* FIXME */
1060 SERVER_END_REQ;
1061 if (status == STATUS_SUCCESS)
1063 if (data) memcpy( data, &info, min( length, sizeof(info) ));
1064 if (ret_len) *ret_len = min( length, sizeof(info) );
1067 return status;
1068 case ThreadTimes:
1070 KERNEL_USER_TIMES kusrt;
1071 /* We need to do a server call to get the creation time or exit time */
1072 /* This works on any thread */
1073 SERVER_START_REQ( get_thread_info )
1075 req->handle = handle;
1076 req->tid_in = 0;
1077 status = wine_server_call( req );
1078 if (status == STATUS_SUCCESS)
1080 NTDLL_from_server_abstime( &kusrt.CreateTime, &reply->creation_time );
1081 NTDLL_from_server_abstime( &kusrt.ExitTime, &reply->exit_time );
1084 SERVER_END_REQ;
1085 if (status == STATUS_SUCCESS)
1087 /* We call times(2) for kernel time or user time */
1088 /* We can only (portably) do this for the current thread */
1089 if (handle == GetCurrentThread())
1091 struct tms time_buf;
1092 long clocks_per_sec = sysconf(_SC_CLK_TCK);
1094 times(&time_buf);
1095 kusrt.KernelTime.QuadPart = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
1096 kusrt.UserTime.QuadPart = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
1098 else
1100 kusrt.KernelTime.QuadPart = 0;
1101 kusrt.UserTime.QuadPart = 0;
1102 FIXME("Cannot get kerneltime or usertime of other threads\n");
1104 if (data) memcpy( data, &kusrt, min( length, sizeof(kusrt) ));
1105 if (ret_len) *ret_len = min( length, sizeof(kusrt) );
1108 return status;
1109 case ThreadDescriptorTableEntry:
1111 #ifdef __i386__
1112 THREAD_DESCRIPTOR_INFORMATION* tdi = data;
1113 if (length < sizeof(*tdi))
1114 status = STATUS_INFO_LENGTH_MISMATCH;
1115 else if (!(tdi->Selector & 4)) /* GDT selector */
1117 unsigned sel = tdi->Selector & ~3; /* ignore RPL */
1118 status = STATUS_SUCCESS;
1119 if (!sel) /* null selector */
1120 memset( &tdi->Entry, 0, sizeof(tdi->Entry) );
1121 else
1123 tdi->Entry.BaseLow = 0;
1124 tdi->Entry.HighWord.Bits.BaseMid = 0;
1125 tdi->Entry.HighWord.Bits.BaseHi = 0;
1126 tdi->Entry.LimitLow = 0xffff;
1127 tdi->Entry.HighWord.Bits.LimitHi = 0xf;
1128 tdi->Entry.HighWord.Bits.Dpl = 3;
1129 tdi->Entry.HighWord.Bits.Sys = 0;
1130 tdi->Entry.HighWord.Bits.Pres = 1;
1131 tdi->Entry.HighWord.Bits.Granularity = 1;
1132 tdi->Entry.HighWord.Bits.Default_Big = 1;
1133 tdi->Entry.HighWord.Bits.Type = 0x12;
1134 /* it has to be one of the system GDT selectors */
1135 if (sel != (wine_get_ds() & ~3) && sel != (wine_get_ss() & ~3))
1137 if (sel == (wine_get_cs() & ~3))
1138 tdi->Entry.HighWord.Bits.Type |= 8; /* code segment */
1139 else status = STATUS_ACCESS_DENIED;
1143 else
1145 SERVER_START_REQ( get_selector_entry )
1147 req->handle = handle;
1148 req->entry = tdi->Selector >> 3;
1149 status = wine_server_call( req );
1150 if (!status)
1152 if (!(reply->flags & WINE_LDT_FLAGS_ALLOCATED))
1153 status = STATUS_ACCESS_VIOLATION;
1154 else
1156 wine_ldt_set_base ( &tdi->Entry, (void *)reply->base );
1157 wine_ldt_set_limit( &tdi->Entry, reply->limit );
1158 wine_ldt_set_flags( &tdi->Entry, reply->flags );
1162 SERVER_END_REQ;
1164 if (status == STATUS_SUCCESS && ret_len)
1165 /* yes, that's a bit strange, but it's the way it is */
1166 *ret_len = sizeof(LDT_ENTRY);
1167 #else
1168 status = STATUS_NOT_IMPLEMENTED;
1169 #endif
1170 return status;
1172 case ThreadAmILastThread:
1174 SERVER_START_REQ(get_thread_info)
1176 req->handle = handle;
1177 req->tid_in = 0;
1178 status = wine_server_call( req );
1179 if (status == STATUS_SUCCESS)
1181 BOOLEAN last = reply->last;
1182 if (data) memcpy( data, &last, min( length, sizeof(last) ));
1183 if (ret_len) *ret_len = min( length, sizeof(last) );
1186 SERVER_END_REQ;
1187 return status;
1189 case ThreadPriority:
1190 case ThreadBasePriority:
1191 case ThreadAffinityMask:
1192 case ThreadImpersonationToken:
1193 case ThreadEnableAlignmentFaultFixup:
1194 case ThreadEventPair_Reusable:
1195 case ThreadQuerySetWin32StartAddress:
1196 case ThreadZeroTlsCell:
1197 case ThreadPerformanceCount:
1198 case ThreadIdealProcessor:
1199 case ThreadPriorityBoost:
1200 case ThreadSetTlsArrayAddress:
1201 case ThreadIsIoPending:
1202 default:
1203 FIXME( "info class %d not supported yet\n", class );
1204 return STATUS_NOT_IMPLEMENTED;
1209 /******************************************************************************
1210 * NtSetInformationThread (NTDLL.@)
1211 * ZwSetInformationThread (NTDLL.@)
1213 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
1214 LPCVOID data, ULONG length )
1216 NTSTATUS status;
1217 switch(class)
1219 case ThreadZeroTlsCell:
1220 if (handle == GetCurrentThread())
1222 LIST_ENTRY *entry;
1223 DWORD index;
1225 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1226 index = *(const DWORD *)data;
1227 if (index < TLS_MINIMUM_AVAILABLE)
1229 RtlAcquirePebLock();
1230 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1232 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1233 teb->TlsSlots[index] = 0;
1235 RtlReleasePebLock();
1237 else
1239 index -= TLS_MINIMUM_AVAILABLE;
1240 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
1241 return STATUS_INVALID_PARAMETER;
1242 RtlAcquirePebLock();
1243 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
1245 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
1246 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
1248 RtlReleasePebLock();
1250 return STATUS_SUCCESS;
1252 FIXME( "ZeroTlsCell not supported on other threads\n" );
1253 return STATUS_NOT_IMPLEMENTED;
1255 case ThreadImpersonationToken:
1257 const HANDLE *phToken = data;
1258 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
1259 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
1260 SERVER_START_REQ( set_thread_info )
1262 req->handle = handle;
1263 req->token = *phToken;
1264 req->mask = SET_THREAD_INFO_TOKEN;
1265 status = wine_server_call( req );
1267 SERVER_END_REQ;
1269 return status;
1270 case ThreadBasePriority:
1272 const DWORD *pprio = data;
1273 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1274 SERVER_START_REQ( set_thread_info )
1276 req->handle = handle;
1277 req->priority = *pprio;
1278 req->mask = SET_THREAD_INFO_PRIORITY;
1279 status = wine_server_call( req );
1281 SERVER_END_REQ;
1283 return status;
1284 case ThreadAffinityMask:
1286 const DWORD *paff = data;
1287 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
1288 SERVER_START_REQ( set_thread_info )
1290 req->handle = handle;
1291 req->affinity = *paff;
1292 req->mask = SET_THREAD_INFO_AFFINITY;
1293 status = wine_server_call( req );
1295 SERVER_END_REQ;
1297 return status;
1298 case ThreadBasicInformation:
1299 case ThreadTimes:
1300 case ThreadPriority:
1301 case ThreadDescriptorTableEntry:
1302 case ThreadEnableAlignmentFaultFixup:
1303 case ThreadEventPair_Reusable:
1304 case ThreadQuerySetWin32StartAddress:
1305 case ThreadPerformanceCount:
1306 case ThreadAmILastThread:
1307 case ThreadIdealProcessor:
1308 case ThreadPriorityBoost:
1309 case ThreadSetTlsArrayAddress:
1310 case ThreadIsIoPending:
1311 default:
1312 FIXME( "info class %d not supported yet\n", class );
1313 return STATUS_NOT_IMPLEMENTED;
1318 /**********************************************************************
1319 * NtCurrentTeb (NTDLL.@)
1321 #if defined(__i386__) && defined(__GNUC__)
1323 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
1325 #elif defined(__i386__) && defined(_MSC_VER)
1327 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
1329 #else
1331 /**********************************************************************/
1333 TEB * WINAPI NtCurrentTeb(void)
1335 return pthread_functions.get_current_teb();
1338 #endif /* __i386__ */