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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "wine/port.h"
24 #include <sys/types.h>
25 #ifdef HAVE_SYS_MMAN_H
32 #include "wine/library.h"
33 #include "wine/server.h"
34 #include "wine/pthread.h"
35 #include "wine/debug.h"
36 #include "ntdll_misc.h"
38 WINE_DEFAULT_DEBUG_CHANNEL(thread);
40 /* info passed to a starting thread */
43 struct wine_pthread_thread_info pthread_info;
44 PRTL_THREAD_START_ROUTINE entry_point;
49 static PEB_LDR_DATA ldr;
50 static RTL_USER_PROCESS_PARAMETERS params; /* default parameters if no parent */
51 static RTL_BITMAP tls_bitmap;
52 static LIST_ENTRY tls_links;
55 /***********************************************************************
58 static TEB *alloc_teb( ULONG *size )
62 *size = SIGNAL_STACK_SIZE + sizeof(TEB);
63 teb = wine_anon_mmap( NULL, *size, PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
64 if (teb == (TEB *)-1) return NULL;
65 if (!(teb->teb_sel = wine_ldt_alloc_fs()))
70 teb->Tib.ExceptionList = (void *)~0UL;
71 teb->Tib.StackBase = (void *)~0UL;
72 teb->Tib.Self = &teb->Tib;
74 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
75 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
80 /***********************************************************************
83 static inline void free_teb( TEB *teb )
88 NtFreeVirtualMemory( GetCurrentProcess(), &addr, &size, MEM_RELEASE );
89 wine_ldt_free_fs( teb->teb_sel );
90 munmap( teb, SIGNAL_STACK_SIZE + sizeof(TEB) );
94 /***********************************************************************
97 * Setup the initial thread.
99 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
101 void thread_init(void)
106 struct wine_pthread_thread_info thread_info;
107 static struct debug_info debug_info; /* debug info for initial thread */
109 peb.NumberOfProcessors = 1;
110 peb.ProcessParameters = ¶ms;
111 peb.TlsBitmap = &tls_bitmap;
113 RtlInitializeBitMap( &tls_bitmap, peb.TlsBitmapBits, sizeof(peb.TlsBitmapBits) * 8 );
114 InitializeListHead( &ldr.InLoadOrderModuleList );
115 InitializeListHead( &ldr.InMemoryOrderModuleList );
116 InitializeListHead( &ldr.InInitializationOrderModuleList );
117 InitializeListHead( &tls_links );
119 teb = alloc_teb( &size );
120 teb->request_fd = -1;
122 teb->wait_fd[0] = -1;
123 teb->wait_fd[1] = -1;
124 teb->debug_info = &debug_info;
125 InsertHeadList( &tls_links, &teb->TlsLinks );
127 thread_info.stack_base = NULL;
128 thread_info.stack_size = 0;
129 thread_info.teb_base = teb;
130 thread_info.teb_size = size;
131 thread_info.teb_sel = teb->teb_sel;
132 wine_pthread_init_current_teb( &thread_info );
133 wine_pthread_init_thread( &thread_info );
135 debug_info.str_pos = debug_info.strings;
136 debug_info.out_pos = debug_info.output;
140 /* setup the server connection */
141 server_init_process();
142 server_init_thread( thread_info.pid, thread_info.tid, NULL );
144 /* create a memory view for the TEB */
145 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, teb, &size,
146 MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
148 /* create the process heap */
149 if (!(peb.ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
151 MESSAGE( "wine: failed to create the process heap\n" );
157 /***********************************************************************
160 * Startup routine for a newly created thread.
162 static void start_thread( struct wine_pthread_thread_info *info )
164 TEB *teb = info->teb_base;
165 struct startup_info *startup_info = (struct startup_info *)info;
166 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
167 void *arg = startup_info->entry_arg;
168 struct debug_info debug_info;
171 debug_info.str_pos = debug_info.strings;
172 debug_info.out_pos = debug_info.output;
173 teb->debug_info = &debug_info;
175 wine_pthread_init_current_teb( info );
177 server_init_thread( info->pid, info->tid, func );
178 wine_pthread_init_thread( info );
180 /* allocate a memory view for the stack */
181 size = info->stack_size;
182 NtAllocateVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, info->stack_base,
183 &size, MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
184 /* limit is lower than base since the stack grows down */
185 teb->Tib.StackBase = (char *)info->stack_base + info->stack_size;
186 teb->Tib.StackLimit = info->stack_base;
188 /* setup the guard page */
190 NtProtectVirtualMemory( GetCurrentProcess(), &teb->DeallocationStack, &size,
191 PAGE_EXECUTE_READWRITE | PAGE_GUARD, NULL );
192 RtlFreeHeap( GetProcessHeap(), 0, info );
195 InsertHeadList( &tls_links, &teb->TlsLinks );
202 /***********************************************************************
203 * RtlCreateUserThread (NTDLL.@)
205 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
206 BOOLEAN suspended, PVOID stack_addr,
207 SIZE_T stack_reserve, SIZE_T stack_commit,
208 PRTL_THREAD_START_ROUTINE start, void *param,
209 HANDLE *handle_ptr, CLIENT_ID *id )
211 struct startup_info *info = NULL;
219 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
220 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
221 wine_server_send_fd( request_pipe[0] );
223 SERVER_START_REQ( new_thread )
225 req->suspend = suspended;
226 req->inherit = 0; /* FIXME */
227 req->request_fd = request_pipe[0];
228 if (!(status = wine_server_call( req )))
230 handle = reply->handle;
233 close( request_pipe[0] );
237 if (status) goto error;
239 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
241 status = STATUS_NO_MEMORY;
245 if (!(teb = alloc_teb( &size )))
247 status = STATUS_NO_MEMORY;
250 teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
251 teb->ClientId.UniqueThread = (HANDLE)tid;
253 teb->exit_code = STILL_ACTIVE;
254 teb->request_fd = request_pipe[1];
256 teb->wait_fd[0] = -1;
257 teb->wait_fd[1] = -1;
258 teb->htask16 = NtCurrentTeb()->htask16;
260 NtAllocateVirtualMemory( GetCurrentProcess(), &info->pthread_info.teb_base, teb, &size,
261 MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
262 info->pthread_info.teb_size = size;
263 info->pthread_info.teb_sel = teb->teb_sel;
265 if (!stack_reserve || !stack_commit)
267 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
268 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
269 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
271 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
272 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
273 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
275 info->pthread_info.stack_base = NULL;
276 info->pthread_info.stack_size = stack_reserve;
277 info->pthread_info.entry = start_thread;
278 info->entry_point = start;
279 info->entry_arg = param;
281 if (wine_pthread_create_thread( &info->pthread_info ) == -1)
283 status = STATUS_NO_MEMORY;
287 if (id) id->UniqueThread = (HANDLE)tid;
288 if (handle_ptr) *handle_ptr = handle;
289 else NtClose( handle );
291 return STATUS_SUCCESS;
294 if (teb) free_teb( teb );
295 if (info) RtlFreeHeap( GetProcessHeap(), 0, info );
296 if (handle) NtClose( handle );
297 close( request_pipe[1] );
302 /***********************************************************************
303 * NtOpenThread (NTDLL.@)
304 * ZwOpenThread (NTDLL.@)
306 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
307 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
311 SERVER_START_REQ( open_thread )
313 req->tid = (thread_id_t)id->UniqueThread;
314 req->access = access;
315 req->inherit = attr && (attr->Attributes & OBJ_INHERIT);
316 ret = wine_server_call( req );
317 *handle = reply->handle;
324 /******************************************************************************
325 * NtSuspendThread (NTDLL.@)
326 * ZwSuspendThread (NTDLL.@)
328 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
332 SERVER_START_REQ( suspend_thread )
334 req->handle = handle;
335 if (!(ret = wine_server_call( req ))) *count = reply->count;
342 /******************************************************************************
343 * NtResumeThread (NTDLL.@)
344 * ZwResumeThread (NTDLL.@)
346 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
350 SERVER_START_REQ( resume_thread )
352 req->handle = handle;
353 if (!(ret = wine_server_call( req ))) *count = reply->count;
360 /******************************************************************************
361 * NtTerminateThread (NTDLL.@)
362 * ZwTerminateThread (NTDLL.@)
364 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
369 SERVER_START_REQ( terminate_thread )
371 req->handle = handle;
372 req->exit_code = exit_code;
373 ret = wine_server_call( req );
374 self = !ret && reply->self;
381 if (last) exit( exit_code );
382 else server_abort_thread( exit_code );
388 /******************************************************************************
389 * NtQueueApcThread (NTDLL.@)
391 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
392 ULONG_PTR arg2, ULONG_PTR arg3 )
395 SERVER_START_REQ( queue_apc )
397 req->handle = handle;
400 req->arg1 = (void *)arg1;
401 req->arg2 = (void *)arg2;
402 req->arg3 = (void *)arg3;
403 ret = wine_server_call( req );
410 /***********************************************************************
411 * NtSetContextThread (NTDLL.@)
412 * ZwSetContextThread (NTDLL.@)
414 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
418 SERVER_START_REQ( set_thread_context )
420 req->handle = handle;
421 req->flags = context->ContextFlags;
422 wine_server_add_data( req, context, sizeof(*context) );
423 ret = wine_server_call( req );
430 /***********************************************************************
431 * NtGetContextThread (NTDLL.@)
432 * ZwGetContextThread (NTDLL.@)
434 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
438 SERVER_START_REQ( get_thread_context )
440 req->handle = handle;
441 req->flags = context->ContextFlags;
442 wine_server_add_data( req, context, sizeof(*context) );
443 wine_server_set_reply( req, context, sizeof(*context) );
444 ret = wine_server_call( req );
451 /******************************************************************************
452 * NtQueryInformationThread (NTDLL.@)
453 * ZwQueryInformationThread (NTDLL.@)
455 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
456 void *data, ULONG length, ULONG *ret_len )
462 case ThreadBasicInformation:
464 THREAD_BASIC_INFORMATION info;
466 SERVER_START_REQ( get_thread_info )
468 req->handle = handle;
470 if (!(status = wine_server_call( req )))
472 info.ExitStatus = reply->exit_code;
473 info.TebBaseAddress = reply->teb;
474 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
475 info.ClientId.UniqueThread = (HANDLE)reply->tid;
476 info.AffinityMask = reply->affinity;
477 info.Priority = reply->priority;
478 info.BasePriority = reply->priority; /* FIXME */
482 if (status == STATUS_SUCCESS)
484 if (data) memcpy( data, &info, min( length, sizeof(info) ));
485 if (ret_len) *ret_len = min( length, sizeof(info) );
491 case ThreadBasePriority:
492 case ThreadAffinityMask:
493 case ThreadImpersonationToken:
494 case ThreadDescriptorTableEntry:
495 case ThreadEnableAlignmentFaultFixup:
496 case ThreadEventPair_Reusable:
497 case ThreadQuerySetWin32StartAddress:
498 case ThreadZeroTlsCell:
499 case ThreadPerformanceCount:
500 case ThreadAmILastThread:
501 case ThreadIdealProcessor:
502 case ThreadPriorityBoost:
503 case ThreadSetTlsArrayAddress:
504 case ThreadIsIoPending:
506 FIXME( "info class %d not supported yet\n", class );
507 return STATUS_NOT_IMPLEMENTED;
512 /******************************************************************************
513 * NtSetInformationThread (NTDLL.@)
514 * ZwSetInformationThread (NTDLL.@)
516 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
517 LPCVOID data, ULONG length )
521 case ThreadZeroTlsCell:
522 if (handle == GetCurrentThread())
527 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
528 index = *(const DWORD *)data;
529 if (index >= 64) return STATUS_INVALID_PARAMETER;
531 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
533 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
534 teb->TlsSlots[index] = 0;
537 return STATUS_SUCCESS;
539 FIXME( "ZeroTlsCell not supported on other threads\n" );
540 return STATUS_NOT_IMPLEMENTED;
542 case ThreadImpersonationToken:
544 const HANDLE *phToken = data;
545 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
546 FIXME("Set ThreadImpersonationToken handle to %p\n", *phToken );
547 return STATUS_SUCCESS;
549 case ThreadBasicInformation:
552 case ThreadBasePriority:
553 case ThreadAffinityMask:
554 case ThreadDescriptorTableEntry:
555 case ThreadEnableAlignmentFaultFixup:
556 case ThreadEventPair_Reusable:
557 case ThreadQuerySetWin32StartAddress:
558 case ThreadPerformanceCount:
559 case ThreadAmILastThread:
560 case ThreadIdealProcessor:
561 case ThreadPriorityBoost:
562 case ThreadSetTlsArrayAddress:
563 case ThreadIsIoPending:
565 FIXME( "info class %d not supported yet\n", class );
566 return STATUS_NOT_IMPLEMENTED;
571 /**********************************************************************
572 * NtCurrentTeb (NTDLL.@)
574 #if defined(__i386__) && defined(__GNUC__)
576 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
578 #elif defined(__i386__) && defined(_MSC_VER)
580 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
584 /**********************************************************************/
586 TEB * WINAPI NtCurrentTeb(void)
588 return wine_pthread_get_current_teb();
591 #endif /* __i386__ */