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>
33 #ifdef HAVE_SYS_SYSCALL_H
34 #include <sys/syscall.h>
37 #define NONAMELESSUNION
39 #define WIN32_NO_STATUS
41 #include "wine/library.h"
42 #include "wine/server.h"
43 #include "wine/debug.h"
44 #include "ntdll_misc.h"
46 #include "wine/exception.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(thread
);
49 WINE_DECLARE_DEBUG_CHANNEL(relay
);
51 struct _KUSER_SHARED_DATA
*user_shared_data
= NULL
;
53 PUNHANDLED_EXCEPTION_FILTER unhandled_exception_filter
= NULL
;
55 /* info passed to a starting thread */
59 PRTL_THREAD_START_ROUTINE entry_point
;
64 static PEB_LDR_DATA ldr
;
65 static RTL_USER_PROCESS_PARAMETERS params
; /* default parameters if no parent */
66 static WCHAR current_dir
[MAX_NT_PATH_LENGTH
];
67 static RTL_BITMAP tls_bitmap
;
68 static RTL_BITMAP tls_expansion_bitmap
;
69 static RTL_BITMAP fls_bitmap
;
70 static int nb_threads
= 1;
72 /***********************************************************************
75 * Copy a unicode string from the startup info.
77 static inline void get_unicode_string( UNICODE_STRING
*str
, WCHAR
**src
, WCHAR
**dst
, UINT len
)
81 str
->MaximumLength
= len
+ sizeof(WCHAR
);
82 memcpy( str
->Buffer
, *src
, len
);
83 str
->Buffer
[len
/ sizeof(WCHAR
)] = 0;
84 *src
+= len
/ sizeof(WCHAR
);
85 *dst
+= len
/ sizeof(WCHAR
) + 1;
88 /***********************************************************************
89 * init_user_process_params
91 * Fill the RTL_USER_PROCESS_PARAMETERS structure from the server.
93 static NTSTATUS
init_user_process_params( SIZE_T data_size
, HANDLE
*exe_file
)
97 SIZE_T info_size
, env_size
, size
, alloc_size
;
100 RTL_USER_PROCESS_PARAMETERS
*params
= NULL
;
102 if (!(info
= RtlAllocateHeap( GetProcessHeap(), 0, data_size
)))
103 return STATUS_NO_MEMORY
;
105 SERVER_START_REQ( get_startup_info
)
107 wine_server_set_reply( req
, info
, data_size
);
108 if (!(status
= wine_server_call( req
)))
110 data_size
= wine_server_reply_size( reply
);
111 info_size
= reply
->info_size
;
112 env_size
= data_size
- info_size
;
113 *exe_file
= wine_server_ptr_handle( reply
->exe_file
);
117 if (status
!= STATUS_SUCCESS
) goto done
;
119 size
= sizeof(*params
);
120 size
+= MAX_NT_PATH_LENGTH
* sizeof(WCHAR
);
121 size
+= info
->dllpath_len
+ sizeof(WCHAR
);
122 size
+= info
->imagepath_len
+ sizeof(WCHAR
);
123 size
+= info
->cmdline_len
+ sizeof(WCHAR
);
124 size
+= info
->title_len
+ sizeof(WCHAR
);
125 size
+= info
->desktop_len
+ sizeof(WCHAR
);
126 size
+= info
->shellinfo_len
+ sizeof(WCHAR
);
127 size
+= info
->runtime_len
+ sizeof(WCHAR
);
130 status
= NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms
, 0, &alloc_size
,
131 MEM_COMMIT
, PAGE_READWRITE
);
132 if (status
!= STATUS_SUCCESS
) goto done
;
134 NtCurrentTeb()->Peb
->ProcessParameters
= params
;
135 params
->AllocationSize
= alloc_size
;
137 params
->Flags
= PROCESS_PARAMS_FLAG_NORMALIZED
;
138 params
->DebugFlags
= info
->debug_flags
;
139 params
->ConsoleHandle
= wine_server_ptr_handle( info
->console
);
140 params
->ConsoleFlags
= info
->console_flags
;
141 params
->hStdInput
= wine_server_ptr_handle( info
->hstdin
);
142 params
->hStdOutput
= wine_server_ptr_handle( info
->hstdout
);
143 params
->hStdError
= wine_server_ptr_handle( info
->hstderr
);
144 params
->dwX
= info
->x
;
145 params
->dwY
= info
->y
;
146 params
->dwXSize
= info
->xsize
;
147 params
->dwYSize
= info
->ysize
;
148 params
->dwXCountChars
= info
->xchars
;
149 params
->dwYCountChars
= info
->ychars
;
150 params
->dwFillAttribute
= info
->attribute
;
151 params
->dwFlags
= info
->flags
;
152 params
->wShowWindow
= info
->show
;
154 src
= (WCHAR
*)(info
+ 1);
155 dst
= (WCHAR
*)(params
+ 1);
157 /* current directory needs more space */
158 get_unicode_string( ¶ms
->CurrentDirectory
.DosPath
, &src
, &dst
, info
->curdir_len
);
159 params
->CurrentDirectory
.DosPath
.MaximumLength
= MAX_NT_PATH_LENGTH
* sizeof(WCHAR
);
160 dst
= (WCHAR
*)(params
+ 1) + MAX_NT_PATH_LENGTH
;
162 get_unicode_string( ¶ms
->DllPath
, &src
, &dst
, info
->dllpath_len
);
163 get_unicode_string( ¶ms
->ImagePathName
, &src
, &dst
, info
->imagepath_len
);
164 get_unicode_string( ¶ms
->CommandLine
, &src
, &dst
, info
->cmdline_len
);
165 get_unicode_string( ¶ms
->WindowTitle
, &src
, &dst
, info
->title_len
);
166 get_unicode_string( ¶ms
->Desktop
, &src
, &dst
, info
->desktop_len
);
167 get_unicode_string( ¶ms
->ShellInfo
, &src
, &dst
, info
->shellinfo_len
);
169 /* runtime info isn't a real string */
170 params
->RuntimeInfo
.Buffer
= dst
;
171 params
->RuntimeInfo
.Length
= params
->RuntimeInfo
.MaximumLength
= info
->runtime_len
;
172 memcpy( dst
, src
, info
->runtime_len
);
174 /* environment needs to be a separate memory block */
176 alloc_size
= max( 1, env_size
);
177 status
= NtAllocateVirtualMemory( NtCurrentProcess(), &ptr
, 0, &alloc_size
,
178 MEM_COMMIT
, PAGE_READWRITE
);
179 if (status
!= STATUS_SUCCESS
) goto done
;
180 memcpy( ptr
, (char *)info
+ info_size
, env_size
);
181 params
->Environment
= ptr
;
184 RtlFreeHeap( GetProcessHeap(), 0, info
);
189 #include <mach/mach.h>
190 #include <mach/mach_error.h>
192 static ULONG64
get_dyld_image_info_addr(void)
195 #ifdef TASK_DYLD_INFO
196 struct task_dyld_info dyld_info
;
197 mach_msg_type_number_t size
= TASK_DYLD_INFO_COUNT
;
198 if (task_info(mach_task_self(), TASK_DYLD_INFO
, (task_info_t
)&dyld_info
, &size
) == KERN_SUCCESS
)
199 ret
= dyld_info
.all_image_info_addr
;
203 #endif /* __APPLE__ */
205 /***********************************************************************
208 * Setup the initial thread.
210 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
212 HANDLE
thread_init(void)
216 SIZE_T size
, info_size
;
220 struct ntdll_thread_data
*thread_data
;
221 static struct debug_info debug_info
; /* debug info for initial thread */
223 ULONG64 dyld_image_info
;
228 /* reserve space for shared user data */
230 addr
= (void *)0x7ffe0000;
232 status
= NtAllocateVirtualMemory( NtCurrentProcess(), &addr
, 0, &size
,
233 MEM_RESERVE
|MEM_COMMIT
, PAGE_READWRITE
);
236 MESSAGE( "wine: failed to map the shared user data: %08x\n", status
);
239 user_shared_data
= addr
;
241 /* allocate and initialize the PEB */
245 NtAllocateVirtualMemory( NtCurrentProcess(), &addr
, 1, &size
,
246 MEM_COMMIT
| MEM_TOP_DOWN
, PAGE_READWRITE
);
249 peb
->ProcessParameters
= ¶ms
;
250 peb
->TlsBitmap
= &tls_bitmap
;
251 peb
->TlsExpansionBitmap
= &tls_expansion_bitmap
;
252 peb
->FlsBitmap
= &fls_bitmap
;
254 params
.CurrentDirectory
.DosPath
.Buffer
= current_dir
;
255 params
.CurrentDirectory
.DosPath
.MaximumLength
= sizeof(current_dir
);
256 params
.wShowWindow
= 1; /* SW_SHOWNORMAL */
257 ldr
.Length
= sizeof(ldr
);
258 RtlInitializeBitMap( &tls_bitmap
, peb
->TlsBitmapBits
, sizeof(peb
->TlsBitmapBits
) * 8 );
259 RtlInitializeBitMap( &tls_expansion_bitmap
, peb
->TlsExpansionBitmapBits
,
260 sizeof(peb
->TlsExpansionBitmapBits
) * 8 );
261 RtlInitializeBitMap( &fls_bitmap
, peb
->FlsBitmapBits
, sizeof(peb
->FlsBitmapBits
) * 8 );
262 RtlSetBits( peb
->TlsBitmap
, 0, 1 ); /* TLS index 0 is reserved and should be initialized to NULL. */
263 RtlSetBits( peb
->FlsBitmap
, 0, 1 );
264 InitializeListHead( &peb
->FlsListHead
);
265 InitializeListHead( &ldr
.InLoadOrderModuleList
);
266 InitializeListHead( &ldr
.InMemoryOrderModuleList
);
267 InitializeListHead( &ldr
.InInitializationOrderModuleList
);
269 dyld_image_info
= get_dyld_image_info_addr();
271 #ifdef WORDS_BIGENDIAN
272 peb
->Reserved
[1] = dyld_image_info
& 0xFFFFFFFF;
273 peb
->Reserved
[0] = dyld_image_info
>> 32;
275 peb
->Reserved
[0] = dyld_image_info
& 0xFFFFFFFF;
276 peb
->Reserved
[1] = dyld_image_info
>> 32;
279 peb
->Reserved
[0] = dyld_image_info
& 0xFFFFFFFF;
283 /* allocate and initialize the initial TEB */
285 signal_alloc_thread( &teb
);
287 teb
->Tib
.StackBase
= (void *)~0UL;
288 teb
->StaticUnicodeString
.Buffer
= teb
->StaticUnicodeBuffer
;
289 teb
->StaticUnicodeString
.MaximumLength
= sizeof(teb
->StaticUnicodeBuffer
);
291 thread_data
= (struct ntdll_thread_data
*)teb
->SpareBytes1
;
292 thread_data
->request_fd
= -1;
293 thread_data
->reply_fd
= -1;
294 thread_data
->wait_fd
[0] = -1;
295 thread_data
->wait_fd
[1] = -1;
296 thread_data
->debug_info
= &debug_info
;
297 InsertHeadList( &tls_links
, &teb
->TlsLinks
);
299 signal_init_thread( teb
);
300 virtual_init_threading();
302 debug_info
.str_pos
= debug_info
.strings
;
303 debug_info
.out_pos
= debug_info
.output
;
306 /* setup the server connection */
307 server_init_process();
308 info_size
= server_init_thread( peb
);
310 /* create the process heap */
311 if (!(peb
->ProcessHeap
= RtlCreateHeap( HEAP_GROWABLE
, NULL
, 0, 0, NULL
, NULL
)))
313 MESSAGE( "wine: failed to create the process heap\n" );
317 /* allocate user parameters */
320 init_user_process_params( info_size
, &exe_file
);
324 if (isatty(0) || isatty(1) || isatty(2))
325 params
.ConsoleHandle
= (HANDLE
)2; /* see kernel32/kernel_private.h */
327 wine_server_fd_to_handle( 0, GENERIC_READ
|SYNCHRONIZE
, OBJ_INHERIT
, ¶ms
.hStdInput
);
329 wine_server_fd_to_handle( 1, GENERIC_WRITE
|SYNCHRONIZE
, OBJ_INHERIT
, ¶ms
.hStdOutput
);
331 wine_server_fd_to_handle( 2, GENERIC_WRITE
|SYNCHRONIZE
, OBJ_INHERIT
, ¶ms
.hStdError
);
334 /* initialize time values in user_shared_data */
335 NtQuerySystemTime( &now
);
336 user_shared_data
->SystemTime
.LowPart
= now
.u
.LowPart
;
337 user_shared_data
->SystemTime
.High1Time
= user_shared_data
->SystemTime
.High2Time
= now
.u
.HighPart
;
338 user_shared_data
->u
.TickCountQuad
= (now
.QuadPart
- server_start_time
) / 10000;
339 user_shared_data
->u
.TickCount
.High2Time
= user_shared_data
->u
.TickCount
.High1Time
;
340 user_shared_data
->TickCountLowDeprecated
= user_shared_data
->u
.TickCount
.LowPart
;
341 user_shared_data
->TickCountMultiplier
= 1 << 24;
345 NtCreateKeyedEvent( &keyed_event
, GENERIC_READ
| GENERIC_WRITE
, NULL
, 0 );
351 /***********************************************************************
354 void terminate_thread( int status
)
356 pthread_sigmask( SIG_BLOCK
, &server_block_set
, NULL
);
357 if (interlocked_xchg_add( &nb_threads
, -1 ) <= 1) _exit( status
);
359 close( ntdll_get_thread_data()->wait_fd
[0] );
360 close( ntdll_get_thread_data()->wait_fd
[1] );
361 close( ntdll_get_thread_data()->reply_fd
);
362 close( ntdll_get_thread_data()->request_fd
);
363 pthread_exit( UIntToPtr(status
) );
367 /***********************************************************************
370 void exit_thread( int status
)
372 static void *prev_teb
;
375 if (status
) /* send the exit code to the server (0 is already the default) */
377 SERVER_START_REQ( terminate_thread
)
379 req
->handle
= wine_server_obj_handle( GetCurrentThread() );
380 req
->exit_code
= status
;
381 wine_server_call( req
);
386 if (interlocked_xchg_add( &nb_threads
, -1 ) <= 1)
388 LdrShutdownProcess();
393 RtlFreeThreadActivationContextStack();
395 pthread_sigmask( SIG_BLOCK
, &server_block_set
, NULL
);
397 if ((teb
= interlocked_xchg_ptr( &prev_teb
, NtCurrentTeb() )))
399 struct ntdll_thread_data
*thread_data
= (struct ntdll_thread_data
*)teb
->SpareBytes1
;
401 if (thread_data
->pthread_id
)
403 pthread_join( thread_data
->pthread_id
, NULL
);
404 signal_free_thread( teb
);
408 close( ntdll_get_thread_data()->wait_fd
[0] );
409 close( ntdll_get_thread_data()->wait_fd
[1] );
410 close( ntdll_get_thread_data()->reply_fd
);
411 close( ntdll_get_thread_data()->request_fd
);
412 pthread_exit( UIntToPtr(status
) );
416 /***********************************************************************
419 * Startup routine for a newly created thread.
421 static void start_thread( struct startup_info
*info
)
423 TEB
*teb
= info
->teb
;
424 struct ntdll_thread_data
*thread_data
= (struct ntdll_thread_data
*)teb
->SpareBytes1
;
425 PRTL_THREAD_START_ROUTINE func
= info
->entry_point
;
426 void *arg
= info
->entry_arg
;
427 struct debug_info debug_info
;
429 debug_info
.str_pos
= debug_info
.strings
;
430 debug_info
.out_pos
= debug_info
.output
;
431 thread_data
->debug_info
= &debug_info
;
432 thread_data
->pthread_id
= pthread_self();
434 signal_init_thread( teb
);
435 server_init_thread( func
);
436 pthread_sigmask( SIG_UNBLOCK
, &server_block_set
, NULL
);
438 MODULE_DllThreadAttach( NULL
);
441 DPRINTF( "%04x:Starting thread proc %p (arg=%p)\n", GetCurrentThreadId(), func
, arg
);
443 call_thread_entry_point( (LPTHREAD_START_ROUTINE
)func
, arg
);
447 /***********************************************************************
448 * RtlCreateUserThread (NTDLL.@)
450 NTSTATUS WINAPI
RtlCreateUserThread( HANDLE process
, const SECURITY_DESCRIPTOR
*descr
,
451 BOOLEAN suspended
, PVOID stack_addr
,
452 SIZE_T stack_reserve
, SIZE_T stack_commit
,
453 PRTL_THREAD_START_ROUTINE start
, void *param
,
454 HANDLE
*handle_ptr
, CLIENT_ID
*id
)
457 pthread_t pthread_id
;
459 struct ntdll_thread_data
*thread_data
;
460 struct startup_info
*info
= NULL
;
461 HANDLE handle
= 0, actctx
= 0;
467 if (process
!= NtCurrentProcess())
472 memset( &call
, 0, sizeof(call
) );
474 call
.create_thread
.type
= APC_CREATE_THREAD
;
475 call
.create_thread
.func
= wine_server_client_ptr( start
);
476 call
.create_thread
.arg
= wine_server_client_ptr( param
);
477 call
.create_thread
.reserve
= stack_reserve
;
478 call
.create_thread
.commit
= stack_commit
;
479 call
.create_thread
.suspend
= suspended
;
480 status
= server_queue_process_apc( process
, &call
, &result
);
481 if (status
!= STATUS_SUCCESS
) return status
;
483 if (result
.create_thread
.status
== STATUS_SUCCESS
)
485 if (id
) id
->UniqueThread
= ULongToHandle(result
.create_thread
.tid
);
486 if (handle_ptr
) *handle_ptr
= wine_server_ptr_handle( result
.create_thread
.handle
);
487 else NtClose( wine_server_ptr_handle( result
.create_thread
.handle
));
489 return result
.create_thread
.status
;
492 if (server_pipe( request_pipe
) == -1) return STATUS_TOO_MANY_OPENED_FILES
;
493 wine_server_send_fd( request_pipe
[0] );
495 SERVER_START_REQ( new_thread
)
497 req
->access
= THREAD_ALL_ACCESS
;
498 req
->attributes
= 0; /* FIXME */
499 req
->suspend
= suspended
;
500 req
->request_fd
= request_pipe
[0];
501 if (!(status
= wine_server_call( req
)))
503 handle
= wine_server_ptr_handle( reply
->handle
);
506 close( request_pipe
[0] );
512 close( request_pipe
[1] );
516 pthread_sigmask( SIG_BLOCK
, &server_block_set
, &sigset
);
518 if ((status
= signal_alloc_thread( &teb
))) goto error
;
520 teb
->Peb
= NtCurrentTeb()->Peb
;
521 teb
->ClientId
.UniqueProcess
= ULongToHandle(GetCurrentProcessId());
522 teb
->ClientId
.UniqueThread
= ULongToHandle(tid
);
523 teb
->StaticUnicodeString
.Buffer
= teb
->StaticUnicodeBuffer
;
524 teb
->StaticUnicodeString
.MaximumLength
= sizeof(teb
->StaticUnicodeBuffer
);
526 /* create default activation context frame for new thread */
527 RtlGetActiveActivationContext(&actctx
);
530 RTL_ACTIVATION_CONTEXT_STACK_FRAME
*frame
;
532 frame
= RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*frame
));
533 frame
->Previous
= NULL
;
534 frame
->ActivationContext
= actctx
;
536 teb
->ActivationContextStack
.ActiveFrame
= frame
;
539 info
= (struct startup_info
*)(teb
+ 1);
541 info
->entry_point
= start
;
542 info
->entry_arg
= param
;
544 thread_data
= (struct ntdll_thread_data
*)teb
->SpareBytes1
;
545 thread_data
->request_fd
= request_pipe
[1];
546 thread_data
->reply_fd
= -1;
547 thread_data
->wait_fd
[0] = -1;
548 thread_data
->wait_fd
[1] = -1;
550 if ((status
= virtual_alloc_thread_stack( teb
, stack_reserve
, stack_commit
))) goto error
;
552 pthread_attr_init( &attr
);
553 pthread_attr_setstack( &attr
, teb
->DeallocationStack
,
554 (char *)teb
->Tib
.StackBase
- (char *)teb
->DeallocationStack
);
555 pthread_attr_setscope( &attr
, PTHREAD_SCOPE_SYSTEM
); /* force creating a kernel thread */
556 interlocked_xchg_add( &nb_threads
, 1 );
557 if (pthread_create( &pthread_id
, &attr
, (void * (*)(void *))start_thread
, info
))
559 interlocked_xchg_add( &nb_threads
, -1 );
560 pthread_attr_destroy( &attr
);
561 status
= STATUS_NO_MEMORY
;
564 pthread_attr_destroy( &attr
);
565 pthread_sigmask( SIG_SETMASK
, &sigset
, NULL
);
567 if (id
) id
->UniqueThread
= ULongToHandle(tid
);
568 if (handle_ptr
) *handle_ptr
= handle
;
569 else NtClose( handle
);
571 return STATUS_SUCCESS
;
574 if (teb
) signal_free_thread( teb
);
575 if (handle
) NtClose( handle
);
576 pthread_sigmask( SIG_SETMASK
, &sigset
, NULL
);
577 close( request_pipe
[1] );
582 /******************************************************************************
583 * RtlGetNtGlobalFlags (NTDLL.@)
585 ULONG WINAPI
RtlGetNtGlobalFlags(void)
587 if (!peb
) return 0; /* init not done yet */
588 return peb
->NtGlobalFlag
;
592 /***********************************************************************
593 * NtOpenThread (NTDLL.@)
594 * ZwOpenThread (NTDLL.@)
596 NTSTATUS WINAPI
NtOpenThread( HANDLE
*handle
, ACCESS_MASK access
,
597 const OBJECT_ATTRIBUTES
*attr
, const CLIENT_ID
*id
)
601 SERVER_START_REQ( open_thread
)
603 req
->tid
= HandleToULong(id
->UniqueThread
);
604 req
->access
= access
;
605 req
->attributes
= attr
? attr
->Attributes
: 0;
606 ret
= wine_server_call( req
);
607 *handle
= wine_server_ptr_handle( reply
->handle
);
614 /******************************************************************************
615 * NtSuspendThread (NTDLL.@)
616 * ZwSuspendThread (NTDLL.@)
618 NTSTATUS WINAPI
NtSuspendThread( HANDLE handle
, PULONG count
)
622 SERVER_START_REQ( suspend_thread
)
624 req
->handle
= wine_server_obj_handle( handle
);
625 if (!(ret
= wine_server_call( req
))) *count
= reply
->count
;
632 /******************************************************************************
633 * NtResumeThread (NTDLL.@)
634 * ZwResumeThread (NTDLL.@)
636 NTSTATUS WINAPI
NtResumeThread( HANDLE handle
, PULONG count
)
640 SERVER_START_REQ( resume_thread
)
642 req
->handle
= wine_server_obj_handle( handle
);
643 if (!(ret
= wine_server_call( req
))) *count
= reply
->count
;
650 /******************************************************************************
651 * NtAlertResumeThread (NTDLL.@)
652 * ZwAlertResumeThread (NTDLL.@)
654 NTSTATUS WINAPI
NtAlertResumeThread( HANDLE handle
, PULONG count
)
656 FIXME( "stub: should alert thread %p\n", handle
);
657 return NtResumeThread( handle
, count
);
661 /******************************************************************************
662 * NtAlertThread (NTDLL.@)
663 * ZwAlertThread (NTDLL.@)
665 NTSTATUS WINAPI
NtAlertThread( HANDLE handle
)
667 FIXME( "stub: %p\n", handle
);
668 return STATUS_NOT_IMPLEMENTED
;
672 /******************************************************************************
673 * NtTerminateThread (NTDLL.@)
674 * ZwTerminateThread (NTDLL.@)
676 NTSTATUS WINAPI
NtTerminateThread( HANDLE handle
, LONG exit_code
)
681 SERVER_START_REQ( terminate_thread
)
683 req
->handle
= wine_server_obj_handle( handle
);
684 req
->exit_code
= exit_code
;
685 ret
= wine_server_call( req
);
686 self
= !ret
&& reply
->self
;
690 if (self
) abort_thread( exit_code
);
695 /******************************************************************************
696 * NtQueueApcThread (NTDLL.@)
698 NTSTATUS WINAPI
NtQueueApcThread( HANDLE handle
, PNTAPCFUNC func
, ULONG_PTR arg1
,
699 ULONG_PTR arg2
, ULONG_PTR arg3
)
702 SERVER_START_REQ( queue_apc
)
704 req
->handle
= wine_server_obj_handle( handle
);
707 req
->call
.type
= APC_USER
;
708 req
->call
.user
.func
= wine_server_client_ptr( func
);
709 req
->call
.user
.args
[0] = arg1
;
710 req
->call
.user
.args
[1] = arg2
;
711 req
->call
.user
.args
[2] = arg3
;
713 else req
->call
.type
= APC_NONE
; /* wake up only */
714 ret
= wine_server_call( req
);
721 /***********************************************************************
722 * NtSetContextThread (NTDLL.@)
723 * ZwSetContextThread (NTDLL.@)
725 NTSTATUS WINAPI
NtSetContextThread( HANDLE handle
, const CONTEXT
*context
)
732 /* on i386 debug registers always require a server call */
733 self
= (handle
== GetCurrentThread());
734 if (self
&& (context
->ContextFlags
& (CONTEXT_DEBUG_REGISTERS
& ~CONTEXT_i386
)))
736 self
= (ntdll_get_thread_data()->dr0
== context
->Dr0
&&
737 ntdll_get_thread_data()->dr1
== context
->Dr1
&&
738 ntdll_get_thread_data()->dr2
== context
->Dr2
&&
739 ntdll_get_thread_data()->dr3
== context
->Dr3
&&
740 ntdll_get_thread_data()->dr6
== context
->Dr6
&&
741 ntdll_get_thread_data()->dr7
== context
->Dr7
);
747 context_t server_context
;
749 context_to_server( &server_context
, context
);
751 SERVER_START_REQ( set_thread_context
)
753 req
->handle
= wine_server_obj_handle( handle
);
755 wine_server_add_data( req
, &server_context
, sizeof(server_context
) );
756 ret
= wine_server_call( req
);
761 if (ret
== STATUS_PENDING
)
763 for (i
= 0; i
< 100; i
++)
765 SERVER_START_REQ( set_thread_context
)
767 req
->handle
= wine_server_obj_handle( handle
);
769 wine_server_add_data( req
, &server_context
, sizeof(server_context
) );
770 ret
= wine_server_call( req
);
773 if (ret
== STATUS_PENDING
)
775 LARGE_INTEGER timeout
;
776 timeout
.QuadPart
= -10000;
777 NtDelayExecution( FALSE
, &timeout
);
781 NtResumeThread( handle
, &dummy
);
782 if (ret
== STATUS_PENDING
) ret
= STATUS_ACCESS_DENIED
;
788 if (self
) set_cpu_context( context
);
789 return STATUS_SUCCESS
;
793 /* convert CPU-specific flags to generic server flags */
794 static inline unsigned int get_server_context_flags( DWORD flags
)
796 unsigned int ret
= 0;
798 flags
&= 0x3f; /* mask CPU id flags */
799 if (flags
& CONTEXT_CONTROL
) ret
|= SERVER_CTX_CONTROL
;
800 if (flags
& CONTEXT_INTEGER
) ret
|= SERVER_CTX_INTEGER
;
801 #ifdef CONTEXT_SEGMENTS
802 if (flags
& CONTEXT_SEGMENTS
) ret
|= SERVER_CTX_SEGMENTS
;
804 #ifdef CONTEXT_FLOATING_POINT
805 if (flags
& CONTEXT_FLOATING_POINT
) ret
|= SERVER_CTX_FLOATING_POINT
;
807 #ifdef CONTEXT_DEBUG_REGISTERS
808 if (flags
& CONTEXT_DEBUG_REGISTERS
) ret
|= SERVER_CTX_DEBUG_REGISTERS
;
810 #ifdef CONTEXT_EXTENDED_REGISTERS
811 if (flags
& CONTEXT_EXTENDED_REGISTERS
) ret
|= SERVER_CTX_EXTENDED_REGISTERS
;
816 /***********************************************************************
817 * NtGetContextThread (NTDLL.@)
818 * ZwGetContextThread (NTDLL.@)
820 NTSTATUS WINAPI
NtGetContextThread( HANDLE handle
, CONTEXT
*context
)
824 DWORD needed_flags
= context
->ContextFlags
;
825 BOOL self
= (handle
== GetCurrentThread());
828 /* on i386 debug registers always require a server call */
829 if (context
->ContextFlags
& (CONTEXT_DEBUG_REGISTERS
& ~CONTEXT_i386
)) self
= FALSE
;
834 unsigned int server_flags
= get_server_context_flags( context
->ContextFlags
);
835 context_t server_context
;
837 SERVER_START_REQ( get_thread_context
)
839 req
->handle
= wine_server_obj_handle( handle
);
840 req
->flags
= server_flags
;
842 wine_server_set_reply( req
, &server_context
, sizeof(server_context
) );
843 ret
= wine_server_call( req
);
848 if (ret
== STATUS_PENDING
)
850 for (i
= 0; i
< 100; i
++)
852 SERVER_START_REQ( get_thread_context
)
854 req
->handle
= wine_server_obj_handle( handle
);
855 req
->flags
= server_flags
;
857 wine_server_set_reply( req
, &server_context
, sizeof(server_context
) );
858 ret
= wine_server_call( req
);
861 if (ret
== STATUS_PENDING
)
863 LARGE_INTEGER timeout
;
864 timeout
.QuadPart
= -10000;
865 NtDelayExecution( FALSE
, &timeout
);
869 NtResumeThread( handle
, &dummy
);
870 if (ret
== STATUS_PENDING
) ret
= STATUS_ACCESS_DENIED
;
872 if (!ret
) ret
= context_from_server( context
, &server_context
);
874 needed_flags
&= ~context
->ContextFlags
;
882 RtlCaptureContext( &ctx
);
883 copy_context( context
, &ctx
, ctx
.ContextFlags
& needed_flags
);
884 context
->ContextFlags
|= ctx
.ContextFlags
& needed_flags
;
887 /* update the cached version of the debug registers */
888 if (context
->ContextFlags
& (CONTEXT_DEBUG_REGISTERS
& ~CONTEXT_i386
))
890 ntdll_get_thread_data()->dr0
= context
->Dr0
;
891 ntdll_get_thread_data()->dr1
= context
->Dr1
;
892 ntdll_get_thread_data()->dr2
= context
->Dr2
;
893 ntdll_get_thread_data()->dr3
= context
->Dr3
;
894 ntdll_get_thread_data()->dr6
= context
->Dr6
;
895 ntdll_get_thread_data()->dr7
= context
->Dr7
;
899 return STATUS_SUCCESS
;
903 /******************************************************************************
904 * NtQueryInformationThread (NTDLL.@)
905 * ZwQueryInformationThread (NTDLL.@)
907 NTSTATUS WINAPI
NtQueryInformationThread( HANDLE handle
, THREADINFOCLASS
class,
908 void *data
, ULONG length
, ULONG
*ret_len
)
914 case ThreadBasicInformation
:
916 THREAD_BASIC_INFORMATION info
;
917 const ULONG_PTR affinity_mask
= get_system_affinity_mask();
919 SERVER_START_REQ( get_thread_info
)
921 req
->handle
= wine_server_obj_handle( handle
);
923 if (!(status
= wine_server_call( req
)))
925 info
.ExitStatus
= reply
->exit_code
;
926 info
.TebBaseAddress
= wine_server_get_ptr( reply
->teb
);
927 info
.ClientId
.UniqueProcess
= ULongToHandle(reply
->pid
);
928 info
.ClientId
.UniqueThread
= ULongToHandle(reply
->tid
);
929 info
.AffinityMask
= reply
->affinity
& affinity_mask
;
930 info
.Priority
= reply
->priority
;
931 info
.BasePriority
= reply
->priority
; /* FIXME */
935 if (status
== STATUS_SUCCESS
)
937 if (data
) memcpy( data
, &info
, min( length
, sizeof(info
) ));
938 if (ret_len
) *ret_len
= min( length
, sizeof(info
) );
942 case ThreadAffinityMask
:
944 const ULONG_PTR affinity_mask
= get_system_affinity_mask();
945 ULONG_PTR affinity
= 0;
947 SERVER_START_REQ( get_thread_info
)
949 req
->handle
= wine_server_obj_handle( handle
);
951 if (!(status
= wine_server_call( req
)))
952 affinity
= reply
->affinity
& affinity_mask
;
955 if (status
== STATUS_SUCCESS
)
957 if (data
) memcpy( data
, &affinity
, min( length
, sizeof(affinity
) ));
958 if (ret_len
) *ret_len
= min( length
, sizeof(affinity
) );
964 KERNEL_USER_TIMES kusrt
;
965 /* We need to do a server call to get the creation time or exit time */
966 /* This works on any thread */
967 SERVER_START_REQ( get_thread_info
)
969 req
->handle
= wine_server_obj_handle( handle
);
971 status
= wine_server_call( req
);
972 if (status
== STATUS_SUCCESS
)
974 kusrt
.CreateTime
.QuadPart
= reply
->creation_time
;
975 kusrt
.ExitTime
.QuadPart
= reply
->exit_time
;
979 if (status
== STATUS_SUCCESS
)
981 /* We call times(2) for kernel time or user time */
982 /* We can only (portably) do this for the current thread */
983 if (handle
== GetCurrentThread())
986 long clocks_per_sec
= sysconf(_SC_CLK_TCK
);
989 kusrt
.KernelTime
.QuadPart
= (ULONGLONG
)time_buf
.tms_stime
* 10000000 / clocks_per_sec
;
990 kusrt
.UserTime
.QuadPart
= (ULONGLONG
)time_buf
.tms_utime
* 10000000 / clocks_per_sec
;
994 static BOOL reported
= FALSE
;
996 kusrt
.KernelTime
.QuadPart
= 0;
997 kusrt
.UserTime
.QuadPart
= 0;
999 TRACE("Cannot get kerneltime or usertime of other threads\n");
1002 FIXME("Cannot get kerneltime or usertime of other threads\n");
1006 if (data
) memcpy( data
, &kusrt
, min( length
, sizeof(kusrt
) ));
1007 if (ret_len
) *ret_len
= min( length
, sizeof(kusrt
) );
1011 case ThreadDescriptorTableEntry
:
1014 THREAD_DESCRIPTOR_INFORMATION
* tdi
= data
;
1015 if (length
< sizeof(*tdi
))
1016 status
= STATUS_INFO_LENGTH_MISMATCH
;
1017 else if (!(tdi
->Selector
& 4)) /* GDT selector */
1019 unsigned sel
= tdi
->Selector
& ~3; /* ignore RPL */
1020 status
= STATUS_SUCCESS
;
1021 if (!sel
) /* null selector */
1022 memset( &tdi
->Entry
, 0, sizeof(tdi
->Entry
) );
1025 tdi
->Entry
.BaseLow
= 0;
1026 tdi
->Entry
.HighWord
.Bits
.BaseMid
= 0;
1027 tdi
->Entry
.HighWord
.Bits
.BaseHi
= 0;
1028 tdi
->Entry
.LimitLow
= 0xffff;
1029 tdi
->Entry
.HighWord
.Bits
.LimitHi
= 0xf;
1030 tdi
->Entry
.HighWord
.Bits
.Dpl
= 3;
1031 tdi
->Entry
.HighWord
.Bits
.Sys
= 0;
1032 tdi
->Entry
.HighWord
.Bits
.Pres
= 1;
1033 tdi
->Entry
.HighWord
.Bits
.Granularity
= 1;
1034 tdi
->Entry
.HighWord
.Bits
.Default_Big
= 1;
1035 tdi
->Entry
.HighWord
.Bits
.Type
= 0x12;
1036 /* it has to be one of the system GDT selectors */
1037 if (sel
!= (wine_get_ds() & ~3) && sel
!= (wine_get_ss() & ~3))
1039 if (sel
== (wine_get_cs() & ~3))
1040 tdi
->Entry
.HighWord
.Bits
.Type
|= 8; /* code segment */
1041 else status
= STATUS_ACCESS_DENIED
;
1047 SERVER_START_REQ( get_selector_entry
)
1049 req
->handle
= wine_server_obj_handle( handle
);
1050 req
->entry
= tdi
->Selector
>> 3;
1051 status
= wine_server_call( req
);
1054 if (!(reply
->flags
& WINE_LDT_FLAGS_ALLOCATED
))
1055 status
= STATUS_ACCESS_VIOLATION
;
1058 wine_ldt_set_base ( &tdi
->Entry
, (void *)reply
->base
);
1059 wine_ldt_set_limit( &tdi
->Entry
, reply
->limit
);
1060 wine_ldt_set_flags( &tdi
->Entry
, reply
->flags
);
1066 if (status
== STATUS_SUCCESS
&& ret_len
)
1067 /* yes, that's a bit strange, but it's the way it is */
1068 *ret_len
= sizeof(LDT_ENTRY
);
1070 status
= STATUS_NOT_IMPLEMENTED
;
1074 case ThreadAmILastThread
:
1076 SERVER_START_REQ(get_thread_info
)
1078 req
->handle
= wine_server_obj_handle( handle
);
1080 status
= wine_server_call( req
);
1081 if (status
== STATUS_SUCCESS
)
1083 BOOLEAN last
= reply
->last
;
1084 if (data
) memcpy( data
, &last
, min( length
, sizeof(last
) ));
1085 if (ret_len
) *ret_len
= min( length
, sizeof(last
) );
1091 case ThreadPriority
:
1092 case ThreadBasePriority
:
1093 case ThreadImpersonationToken
:
1094 case ThreadEnableAlignmentFaultFixup
:
1095 case ThreadEventPair_Reusable
:
1096 case ThreadQuerySetWin32StartAddress
:
1097 case ThreadZeroTlsCell
:
1098 case ThreadPerformanceCount
:
1099 case ThreadIdealProcessor
:
1100 case ThreadPriorityBoost
:
1101 case ThreadSetTlsArrayAddress
:
1102 case ThreadIsIoPending
:
1104 FIXME( "info class %d not supported yet\n", class );
1105 return STATUS_NOT_IMPLEMENTED
;
1110 /******************************************************************************
1111 * NtSetInformationThread (NTDLL.@)
1112 * ZwSetInformationThread (NTDLL.@)
1114 NTSTATUS WINAPI
NtSetInformationThread( HANDLE handle
, THREADINFOCLASS
class,
1115 LPCVOID data
, ULONG length
)
1120 case ThreadZeroTlsCell
:
1121 if (handle
== GetCurrentThread())
1126 if (length
!= sizeof(DWORD
)) return STATUS_INVALID_PARAMETER
;
1127 index
= *(const DWORD
*)data
;
1128 if (index
< TLS_MINIMUM_AVAILABLE
)
1130 RtlAcquirePebLock();
1131 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
1133 TEB
*teb
= CONTAINING_RECORD(entry
, TEB
, TlsLinks
);
1134 teb
->TlsSlots
[index
] = 0;
1136 RtlReleasePebLock();
1140 index
-= TLS_MINIMUM_AVAILABLE
;
1141 if (index
>= 8 * sizeof(NtCurrentTeb()->Peb
->TlsExpansionBitmapBits
))
1142 return STATUS_INVALID_PARAMETER
;
1143 RtlAcquirePebLock();
1144 for (entry
= tls_links
.Flink
; entry
!= &tls_links
; entry
= entry
->Flink
)
1146 TEB
*teb
= CONTAINING_RECORD(entry
, TEB
, TlsLinks
);
1147 if (teb
->TlsExpansionSlots
) teb
->TlsExpansionSlots
[index
] = 0;
1149 RtlReleasePebLock();
1151 return STATUS_SUCCESS
;
1153 FIXME( "ZeroTlsCell not supported on other threads\n" );
1154 return STATUS_NOT_IMPLEMENTED
;
1156 case ThreadImpersonationToken
:
1158 const HANDLE
*phToken
= data
;
1159 if (length
!= sizeof(HANDLE
)) return STATUS_INVALID_PARAMETER
;
1160 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken
);
1161 SERVER_START_REQ( set_thread_info
)
1163 req
->handle
= wine_server_obj_handle( handle
);
1164 req
->token
= wine_server_obj_handle( *phToken
);
1165 req
->mask
= SET_THREAD_INFO_TOKEN
;
1166 status
= wine_server_call( req
);
1171 case ThreadBasePriority
:
1173 const DWORD
*pprio
= data
;
1174 if (length
!= sizeof(DWORD
)) return STATUS_INVALID_PARAMETER
;
1175 SERVER_START_REQ( set_thread_info
)
1177 req
->handle
= wine_server_obj_handle( handle
);
1178 req
->priority
= *pprio
;
1179 req
->mask
= SET_THREAD_INFO_PRIORITY
;
1180 status
= wine_server_call( req
);
1185 case ThreadAffinityMask
:
1187 const ULONG_PTR affinity_mask
= get_system_affinity_mask();
1190 if (length
!= sizeof(ULONG_PTR
)) return STATUS_INVALID_PARAMETER
;
1191 req_aff
= *(const ULONG_PTR
*)data
;
1192 if ((ULONG
)req_aff
== ~0u) req_aff
= affinity_mask
;
1193 else if (req_aff
& ~affinity_mask
) return STATUS_INVALID_PARAMETER
;
1194 else if (!req_aff
) return STATUS_INVALID_PARAMETER
;
1195 SERVER_START_REQ( set_thread_info
)
1197 req
->handle
= wine_server_obj_handle( handle
);
1198 req
->affinity
= req_aff
;
1199 req
->mask
= SET_THREAD_INFO_AFFINITY
;
1200 status
= wine_server_call( req
);
1205 case ThreadHideFromDebugger
:
1206 /* pretend the call succeeded to satisfy some code protectors */
1207 return STATUS_SUCCESS
;
1209 case ThreadBasicInformation
:
1211 case ThreadPriority
:
1212 case ThreadDescriptorTableEntry
:
1213 case ThreadEnableAlignmentFaultFixup
:
1214 case ThreadEventPair_Reusable
:
1215 case ThreadQuerySetWin32StartAddress
:
1216 case ThreadPerformanceCount
:
1217 case ThreadAmILastThread
:
1218 case ThreadIdealProcessor
:
1219 case ThreadPriorityBoost
:
1220 case ThreadSetTlsArrayAddress
:
1221 case ThreadIsIoPending
:
1223 FIXME( "info class %d not supported yet\n", class );
1224 return STATUS_NOT_IMPLEMENTED
;
1228 /******************************************************************************
1229 * NtGetCurrentProcessorNumber (NTDLL.@)
1231 * Return the processor, on which the thread is running
1234 ULONG WINAPI
NtGetCurrentProcessorNumber(void)
1238 #if defined(__linux__) && defined(__NR_getcpu)
1239 int res
= syscall(__NR_getcpu
, &processor
, NULL
, NULL
);
1240 if (res
!= -1) return processor
;
1243 if (NtCurrentTeb()->Peb
->NumberOfProcessors
> 1)
1245 ULONG_PTR thread_mask
, processor_mask
;
1248 status
= NtQueryInformationThread(GetCurrentThread(), ThreadAffinityMask
,
1249 &thread_mask
, sizeof(thread_mask
), NULL
);
1250 if (status
== STATUS_SUCCESS
)
1252 for (processor
= 0; processor
< NtCurrentTeb()->Peb
->NumberOfProcessors
; processor
++)
1254 processor_mask
= (1 << processor
);
1255 if (thread_mask
& processor_mask
)
1257 if (thread_mask
!= processor_mask
)
1258 FIXME("need multicore support (%d processors)\n",
1259 NtCurrentTeb()->Peb
->NumberOfProcessors
);
1266 /* fallback to the first processor */