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 RTL_BITMAP tls_expansion_bitmap;
53 static LIST_ENTRY tls_links;
56 /***********************************************************************
59 static TEB *alloc_teb( ULONG *size )
63 *size = SIGNAL_STACK_SIZE + sizeof(TEB);
64 teb = wine_anon_mmap( NULL, *size, PROT_READ | PROT_WRITE | PROT_EXEC, 0 );
65 if (teb == (TEB *)-1) return NULL;
66 if (!(teb->teb_sel = wine_ldt_alloc_fs()))
71 teb->Tib.ExceptionList = (void *)~0UL;
72 teb->Tib.StackBase = (void *)~0UL;
73 teb->Tib.Self = &teb->Tib;
75 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
76 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
81 /***********************************************************************
84 static inline void free_teb( TEB *teb )
89 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
90 wine_ldt_free_fs( teb->teb_sel );
91 munmap( teb, SIGNAL_STACK_SIZE + sizeof(TEB) );
95 /***********************************************************************
98 * Setup the initial thread.
100 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
102 void thread_init(void)
107 struct wine_pthread_thread_info thread_info;
108 static struct debug_info debug_info; /* debug info for initial thread */
110 peb.NumberOfProcessors = 1;
111 peb.ProcessParameters = ¶ms;
112 peb.TlsBitmap = &tls_bitmap;
113 peb.TlsExpansionBitmap = &tls_expansion_bitmap;
115 RtlInitializeBitMap( &tls_bitmap, peb.TlsBitmapBits, sizeof(peb.TlsBitmapBits) * 8 );
116 RtlInitializeBitMap( &tls_expansion_bitmap, peb.TlsExpansionBitmapBits,
117 sizeof(peb.TlsExpansionBitmapBits) * 8 );
118 InitializeListHead( &ldr.InLoadOrderModuleList );
119 InitializeListHead( &ldr.InMemoryOrderModuleList );
120 InitializeListHead( &ldr.InInitializationOrderModuleList );
121 InitializeListHead( &tls_links );
123 teb = alloc_teb( &size );
124 teb->request_fd = -1;
126 teb->wait_fd[0] = -1;
127 teb->wait_fd[1] = -1;
128 teb->debug_info = &debug_info;
129 InsertHeadList( &tls_links, &teb->TlsLinks );
131 thread_info.stack_base = NULL;
132 thread_info.stack_size = 0;
133 thread_info.teb_base = teb;
134 thread_info.teb_size = size;
135 thread_info.teb_sel = teb->teb_sel;
136 wine_pthread_init_current_teb( &thread_info );
137 wine_pthread_init_thread( &thread_info );
139 debug_info.str_pos = debug_info.strings;
140 debug_info.out_pos = debug_info.output;
144 /* setup the server connection */
145 server_init_process();
146 server_init_thread( thread_info.pid, thread_info.tid, NULL );
148 /* create a memory view for the TEB */
150 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &size,
151 MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
153 /* create the process heap */
154 if (!(peb.ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
156 MESSAGE( "wine: failed to create the process heap\n" );
162 /***********************************************************************
165 * Startup routine for a newly created thread.
167 static void start_thread( struct wine_pthread_thread_info *info )
169 TEB *teb = info->teb_base;
170 struct startup_info *startup_info = (struct startup_info *)info;
171 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
172 void *arg = startup_info->entry_arg;
173 struct debug_info debug_info;
176 debug_info.str_pos = debug_info.strings;
177 debug_info.out_pos = debug_info.output;
178 teb->debug_info = &debug_info;
180 wine_pthread_init_current_teb( info );
182 server_init_thread( info->pid, info->tid, func );
183 wine_pthread_init_thread( info );
185 /* allocate a memory view for the stack */
186 size = info->stack_size;
187 teb->DeallocationStack = info->stack_base;
188 NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
189 &size, MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
190 /* limit is lower than base since the stack grows down */
191 teb->Tib.StackBase = (char *)info->stack_base + info->stack_size;
192 teb->Tib.StackLimit = info->stack_base;
194 /* setup the guard page */
196 NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size,
197 PAGE_EXECUTE_READWRITE | PAGE_GUARD, NULL );
198 RtlFreeHeap( GetProcessHeap(), 0, info );
201 InsertHeadList( &tls_links, &teb->TlsLinks );
208 /***********************************************************************
209 * RtlCreateUserThread (NTDLL.@)
211 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
212 BOOLEAN suspended, PVOID stack_addr,
213 SIZE_T stack_reserve, SIZE_T stack_commit,
214 PRTL_THREAD_START_ROUTINE start, void *param,
215 HANDLE *handle_ptr, CLIENT_ID *id )
217 struct startup_info *info = NULL;
225 if( ! is_current_process( process ) )
227 ERR("Unsupported on other process\n");
228 return STATUS_ACCESS_DENIED;
231 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
232 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
233 wine_server_send_fd( request_pipe[0] );
235 SERVER_START_REQ( new_thread )
237 req->suspend = suspended;
238 req->inherit = 0; /* FIXME */
239 req->request_fd = request_pipe[0];
240 if (!(status = wine_server_call( req )))
242 handle = reply->handle;
245 close( request_pipe[0] );
249 if (status) goto error;
251 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
253 status = STATUS_NO_MEMORY;
257 if (!(teb = alloc_teb( &size )))
259 status = STATUS_NO_MEMORY;
262 teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
263 teb->ClientId.UniqueThread = (HANDLE)tid;
265 teb->request_fd = request_pipe[1];
267 teb->wait_fd[0] = -1;
268 teb->wait_fd[1] = -1;
270 info->pthread_info.teb_base = teb;
271 NtAllocateVirtualMemory( NtCurrentProcess(), &info->pthread_info.teb_base, 0, &size,
272 MEM_SYSTEM, PAGE_EXECUTE_READWRITE );
273 info->pthread_info.teb_size = size;
274 info->pthread_info.teb_sel = teb->teb_sel;
276 if (!stack_reserve || !stack_commit)
278 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
279 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
280 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
282 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
283 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
284 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
286 info->pthread_info.stack_base = NULL;
287 info->pthread_info.stack_size = stack_reserve;
288 info->pthread_info.entry = start_thread;
289 info->entry_point = start;
290 info->entry_arg = param;
292 if (wine_pthread_create_thread( &info->pthread_info ) == -1)
294 status = STATUS_NO_MEMORY;
298 if (id) id->UniqueThread = (HANDLE)tid;
299 if (handle_ptr) *handle_ptr = handle;
300 else NtClose( handle );
302 return STATUS_SUCCESS;
305 if (teb) free_teb( teb );
306 if (info) RtlFreeHeap( GetProcessHeap(), 0, info );
307 if (handle) NtClose( handle );
308 close( request_pipe[1] );
313 /***********************************************************************
314 * NtOpenThread (NTDLL.@)
315 * ZwOpenThread (NTDLL.@)
317 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
318 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
322 SERVER_START_REQ( open_thread )
324 req->tid = (thread_id_t)id->UniqueThread;
325 req->access = access;
326 req->inherit = attr && (attr->Attributes & OBJ_INHERIT);
327 ret = wine_server_call( req );
328 *handle = reply->handle;
335 /******************************************************************************
336 * NtSuspendThread (NTDLL.@)
337 * ZwSuspendThread (NTDLL.@)
339 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
343 SERVER_START_REQ( suspend_thread )
345 req->handle = handle;
346 if (!(ret = wine_server_call( req ))) *count = reply->count;
353 /******************************************************************************
354 * NtResumeThread (NTDLL.@)
355 * ZwResumeThread (NTDLL.@)
357 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
361 SERVER_START_REQ( resume_thread )
363 req->handle = handle;
364 if (!(ret = wine_server_call( req ))) *count = reply->count;
371 /******************************************************************************
372 * NtTerminateThread (NTDLL.@)
373 * ZwTerminateThread (NTDLL.@)
375 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
380 SERVER_START_REQ( terminate_thread )
382 req->handle = handle;
383 req->exit_code = exit_code;
384 ret = wine_server_call( req );
385 self = !ret && reply->self;
392 if (last) exit( exit_code );
393 else server_abort_thread( exit_code );
399 /******************************************************************************
400 * NtQueueApcThread (NTDLL.@)
402 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
403 ULONG_PTR arg2, ULONG_PTR arg3 )
406 SERVER_START_REQ( queue_apc )
408 req->handle = handle;
411 req->arg1 = (void *)arg1;
412 req->arg2 = (void *)arg2;
413 req->arg3 = (void *)arg3;
414 ret = wine_server_call( req );
421 /***********************************************************************
422 * NtSetContextThread (NTDLL.@)
423 * ZwSetContextThread (NTDLL.@)
425 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
429 SERVER_START_REQ( set_thread_context )
431 req->handle = handle;
432 req->flags = context->ContextFlags;
433 wine_server_add_data( req, context, sizeof(*context) );
434 ret = wine_server_call( req );
441 /***********************************************************************
442 * NtGetContextThread (NTDLL.@)
443 * ZwGetContextThread (NTDLL.@)
445 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
449 SERVER_START_REQ( get_thread_context )
451 req->handle = handle;
452 req->flags = context->ContextFlags;
453 wine_server_add_data( req, context, sizeof(*context) );
454 wine_server_set_reply( req, context, sizeof(*context) );
455 ret = wine_server_call( req );
462 /******************************************************************************
463 * NtQueryInformationThread (NTDLL.@)
464 * ZwQueryInformationThread (NTDLL.@)
466 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
467 void *data, ULONG length, ULONG *ret_len )
473 case ThreadBasicInformation:
475 THREAD_BASIC_INFORMATION info;
477 SERVER_START_REQ( get_thread_info )
479 req->handle = handle;
481 if (!(status = wine_server_call( req )))
483 info.ExitStatus = reply->exit_code;
484 info.TebBaseAddress = reply->teb;
485 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
486 info.ClientId.UniqueThread = (HANDLE)reply->tid;
487 info.AffinityMask = reply->affinity;
488 info.Priority = reply->priority;
489 info.BasePriority = reply->priority; /* FIXME */
493 if (status == STATUS_SUCCESS)
495 if (data) memcpy( data, &info, min( length, sizeof(info) ));
496 if (ret_len) *ret_len = min( length, sizeof(info) );
502 case ThreadBasePriority:
503 case ThreadAffinityMask:
504 case ThreadImpersonationToken:
505 case ThreadDescriptorTableEntry:
506 case ThreadEnableAlignmentFaultFixup:
507 case ThreadEventPair_Reusable:
508 case ThreadQuerySetWin32StartAddress:
509 case ThreadZeroTlsCell:
510 case ThreadPerformanceCount:
511 case ThreadAmILastThread:
512 case ThreadIdealProcessor:
513 case ThreadPriorityBoost:
514 case ThreadSetTlsArrayAddress:
515 case ThreadIsIoPending:
517 FIXME( "info class %d not supported yet\n", class );
518 return STATUS_NOT_IMPLEMENTED;
523 /******************************************************************************
524 * NtSetInformationThread (NTDLL.@)
525 * ZwSetInformationThread (NTDLL.@)
527 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
528 LPCVOID data, ULONG length )
532 case ThreadZeroTlsCell:
533 if (handle == GetCurrentThread())
538 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
539 index = *(const DWORD *)data;
540 if (index < TLS_MINIMUM_AVAILABLE)
543 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
545 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
546 teb->TlsSlots[index] = 0;
552 index -= TLS_MINIMUM_AVAILABLE;
553 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
554 return STATUS_INVALID_PARAMETER;
556 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
558 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
559 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
563 return STATUS_SUCCESS;
565 FIXME( "ZeroTlsCell not supported on other threads\n" );
566 return STATUS_NOT_IMPLEMENTED;
568 case ThreadImpersonationToken:
570 const HANDLE *phToken = data;
571 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
572 FIXME("Set ThreadImpersonationToken handle to %p\n", *phToken );
573 return STATUS_SUCCESS;
575 case ThreadBasicInformation:
578 case ThreadBasePriority:
579 case ThreadAffinityMask:
580 case ThreadDescriptorTableEntry:
581 case ThreadEnableAlignmentFaultFixup:
582 case ThreadEventPair_Reusable:
583 case ThreadQuerySetWin32StartAddress:
584 case ThreadPerformanceCount:
585 case ThreadAmILastThread:
586 case ThreadIdealProcessor:
587 case ThreadPriorityBoost:
588 case ThreadSetTlsArrayAddress:
589 case ThreadIsIoPending:
591 FIXME( "info class %d not supported yet\n", class );
592 return STATUS_NOT_IMPLEMENTED;
597 /**********************************************************************
598 * NtCurrentTeb (NTDLL.@)
600 #if defined(__i386__) && defined(__GNUC__)
602 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
604 #elif defined(__i386__) && defined(_MSC_VER)
606 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
610 /**********************************************************************/
612 TEB * WINAPI NtCurrentTeb(void)
614 return wine_pthread_get_current_teb();
617 #endif /* __i386__ */