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 WCHAR current_dir[MAX_NT_PATH_LENGTH];
52 static RTL_BITMAP tls_bitmap;
53 static RTL_BITMAP tls_expansion_bitmap;
54 static LIST_ENTRY tls_links;
57 /***********************************************************************
60 static inline NTSTATUS init_teb( TEB *teb )
62 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
64 teb->Tib.ExceptionList = (void *)~0UL;
65 teb->Tib.StackBase = (void *)~0UL;
66 teb->Tib.Self = &teb->Tib;
68 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
69 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
71 if (!(thread_data->teb_sel = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
72 thread_data->request_fd = -1;
73 thread_data->reply_fd = -1;
74 thread_data->wait_fd[0] = -1;
75 thread_data->wait_fd[1] = -1;
77 return STATUS_SUCCESS;
81 /***********************************************************************
84 static inline void free_teb( TEB *teb )
88 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
90 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
91 wine_ldt_free_fs( thread_data->teb_sel );
92 munmap( teb, SIGNAL_STACK_SIZE + sizeof(TEB) );
96 /***********************************************************************
99 * Setup the initial thread.
101 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
103 void thread_init(void)
108 struct ntdll_thread_data *thread_data;
109 struct wine_pthread_thread_info thread_info;
110 static struct debug_info debug_info; /* debug info for initial thread */
112 peb.NumberOfProcessors = 1;
113 peb.ProcessParameters = ¶ms;
114 peb.TlsBitmap = &tls_bitmap;
115 peb.TlsExpansionBitmap = &tls_expansion_bitmap;
117 params.CurrentDirectory.DosPath.Buffer = current_dir;
118 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
119 RtlInitializeBitMap( &tls_bitmap, peb.TlsBitmapBits, sizeof(peb.TlsBitmapBits) * 8 );
120 RtlInitializeBitMap( &tls_expansion_bitmap, peb.TlsExpansionBitmapBits,
121 sizeof(peb.TlsExpansionBitmapBits) * 8 );
122 InitializeListHead( &ldr.InLoadOrderModuleList );
123 InitializeListHead( &ldr.InMemoryOrderModuleList );
124 InitializeListHead( &ldr.InInitializationOrderModuleList );
125 InitializeListHead( &tls_links );
127 thread_info.teb_size = SIGNAL_STACK_SIZE + sizeof(TEB);
128 VIRTUAL_alloc_teb( &addr, thread_info.teb_size, TRUE );
131 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
132 thread_data->debug_info = &debug_info;
133 InsertHeadList( &tls_links, &teb->TlsLinks );
135 thread_info.stack_base = NULL;
136 thread_info.stack_size = 0;
137 thread_info.teb_base = teb;
138 thread_info.teb_sel = thread_data->teb_sel;
139 wine_pthread_init_current_teb( &thread_info );
140 wine_pthread_init_thread( &thread_info );
142 debug_info.str_pos = debug_info.strings;
143 debug_info.out_pos = debug_info.output;
146 /* setup the server connection */
147 server_init_process();
148 info_size = server_init_thread( thread_info.pid, thread_info.tid, NULL );
150 /* create the process heap */
151 if (!(peb.ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
153 MESSAGE( "wine: failed to create the process heap\n" );
157 /* allocate user parameters */
160 RTL_USER_PROCESS_PARAMETERS *params = NULL;
162 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)¶ms, 0, &info_size,
163 MEM_COMMIT, PAGE_READWRITE ) == STATUS_SUCCESS)
165 params->AllocationSize = info_size;
166 NtCurrentTeb()->Peb->ProcessParameters = params;
171 /* This is wine specific: we have no parent (we're started from unix)
172 * so, create a simple console with bare handles to unix stdio
174 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, ¶ms.hStdInput );
175 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms.hStdOutput );
176 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, ¶ms.hStdError );
181 /***********************************************************************
184 * Startup routine for a newly created thread.
186 static void start_thread( struct wine_pthread_thread_info *info )
188 TEB *teb = info->teb_base;
189 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
190 struct startup_info *startup_info = (struct startup_info *)info;
191 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
192 void *arg = startup_info->entry_arg;
193 struct debug_info debug_info;
196 debug_info.str_pos = debug_info.strings;
197 debug_info.out_pos = debug_info.output;
198 thread_data->debug_info = &debug_info;
200 wine_pthread_init_current_teb( info );
202 server_init_thread( info->pid, info->tid, func );
203 wine_pthread_init_thread( info );
205 /* allocate a memory view for the stack */
206 size = info->stack_size;
207 teb->DeallocationStack = info->stack_base;
208 NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
209 &size, MEM_SYSTEM, PAGE_READWRITE );
210 /* limit is lower than base since the stack grows down */
211 teb->Tib.StackBase = (char *)info->stack_base + info->stack_size;
212 teb->Tib.StackLimit = info->stack_base;
214 /* setup the guard page */
216 NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size,
217 PAGE_READWRITE | PAGE_GUARD, NULL );
218 RtlFreeHeap( GetProcessHeap(), 0, info );
221 InsertHeadList( &tls_links, &teb->TlsLinks );
228 /***********************************************************************
229 * RtlCreateUserThread (NTDLL.@)
231 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
232 BOOLEAN suspended, PVOID stack_addr,
233 SIZE_T stack_reserve, SIZE_T stack_commit,
234 PRTL_THREAD_START_ROUTINE start, void *param,
235 HANDLE *handle_ptr, CLIENT_ID *id )
237 struct ntdll_thread_data *thread_data = NULL;
238 struct startup_info *info = NULL;
246 if( ! is_current_process( process ) )
248 ERR("Unsupported on other process\n");
249 return STATUS_ACCESS_DENIED;
252 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
253 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
254 wine_server_send_fd( request_pipe[0] );
256 SERVER_START_REQ( new_thread )
258 req->suspend = suspended;
259 req->inherit = 0; /* FIXME */
260 req->request_fd = request_pipe[0];
261 if (!(status = wine_server_call( req )))
263 handle = reply->handle;
266 close( request_pipe[0] );
270 if (status) goto error;
272 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
274 status = STATUS_NO_MEMORY;
278 info->pthread_info.teb_size = SIGNAL_STACK_SIZE + sizeof(TEB);
279 if ((status = VIRTUAL_alloc_teb( &addr, info->pthread_info.teb_size, FALSE ))) goto error;
281 if ((status = init_teb( teb ))) goto error;
283 teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
284 teb->ClientId.UniqueThread = (HANDLE)tid;
286 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
287 thread_data->request_fd = request_pipe[1];
289 info->pthread_info.teb_base = teb;
290 info->pthread_info.teb_sel = thread_data->teb_sel;
292 if (!stack_reserve || !stack_commit)
294 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
295 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
296 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
298 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
299 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
300 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
302 info->pthread_info.stack_base = NULL;
303 info->pthread_info.stack_size = stack_reserve;
304 info->pthread_info.entry = start_thread;
305 info->entry_point = start;
306 info->entry_arg = param;
308 if (wine_pthread_create_thread( &info->pthread_info ) == -1)
310 status = STATUS_NO_MEMORY;
314 if (id) id->UniqueThread = (HANDLE)tid;
315 if (handle_ptr) *handle_ptr = handle;
316 else NtClose( handle );
318 return STATUS_SUCCESS;
321 if (thread_data) wine_ldt_free_fs( thread_data->teb_sel );
325 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
327 if (info) RtlFreeHeap( GetProcessHeap(), 0, info );
328 if (handle) NtClose( handle );
329 close( request_pipe[1] );
334 /***********************************************************************
335 * RtlExitUserThread (NTDLL.@)
337 void WINAPI RtlExitUserThread( ULONG status )
340 server_exit_thread( status );
344 /***********************************************************************
345 * NtOpenThread (NTDLL.@)
346 * ZwOpenThread (NTDLL.@)
348 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
349 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
353 SERVER_START_REQ( open_thread )
355 req->tid = (thread_id_t)id->UniqueThread;
356 req->access = access;
357 req->inherit = attr && (attr->Attributes & OBJ_INHERIT);
358 ret = wine_server_call( req );
359 *handle = reply->handle;
366 /******************************************************************************
367 * NtSuspendThread (NTDLL.@)
368 * ZwSuspendThread (NTDLL.@)
370 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
374 SERVER_START_REQ( suspend_thread )
376 req->handle = handle;
377 if (!(ret = wine_server_call( req ))) *count = reply->count;
384 /******************************************************************************
385 * NtResumeThread (NTDLL.@)
386 * ZwResumeThread (NTDLL.@)
388 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
392 SERVER_START_REQ( resume_thread )
394 req->handle = handle;
395 if (!(ret = wine_server_call( req ))) *count = reply->count;
402 /******************************************************************************
403 * NtAlertResumeThread (NTDLL.@)
404 * ZwAlertResumeThread (NTDLL.@)
406 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
408 FIXME( "stub: should alert thread %p\n", handle );
409 return NtResumeThread( handle, count );
413 /******************************************************************************
414 * NtAlertThread (NTDLL.@)
415 * ZwAlertThread (NTDLL.@)
417 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
419 FIXME( "stub: %p\n", handle );
420 return STATUS_NOT_IMPLEMENTED;
424 /******************************************************************************
425 * NtTerminateThread (NTDLL.@)
426 * ZwTerminateThread (NTDLL.@)
428 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
433 SERVER_START_REQ( terminate_thread )
435 req->handle = handle;
436 req->exit_code = exit_code;
437 ret = wine_server_call( req );
438 self = !ret && reply->self;
445 if (last) exit( exit_code );
446 else server_abort_thread( exit_code );
452 /******************************************************************************
453 * NtQueueApcThread (NTDLL.@)
455 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
456 ULONG_PTR arg2, ULONG_PTR arg3 )
459 SERVER_START_REQ( queue_apc )
461 req->handle = handle;
464 req->arg1 = (void *)arg1;
465 req->arg2 = (void *)arg2;
466 req->arg3 = (void *)arg3;
467 ret = wine_server_call( req );
474 /***********************************************************************
475 * NtSetContextThread (NTDLL.@)
476 * ZwSetContextThread (NTDLL.@)
478 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
482 SERVER_START_REQ( set_thread_context )
484 req->handle = handle;
485 req->flags = context->ContextFlags;
486 wine_server_add_data( req, context, sizeof(*context) );
487 ret = wine_server_call( req );
494 /***********************************************************************
495 * NtGetContextThread (NTDLL.@)
496 * ZwGetContextThread (NTDLL.@)
498 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
502 SERVER_START_REQ( get_thread_context )
504 req->handle = handle;
505 req->flags = context->ContextFlags;
506 wine_server_add_data( req, context, sizeof(*context) );
507 wine_server_set_reply( req, context, sizeof(*context) );
508 ret = wine_server_call( req );
515 /******************************************************************************
516 * NtQueryInformationThread (NTDLL.@)
517 * ZwQueryInformationThread (NTDLL.@)
519 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
520 void *data, ULONG length, ULONG *ret_len )
526 case ThreadBasicInformation:
528 THREAD_BASIC_INFORMATION info;
530 SERVER_START_REQ( get_thread_info )
532 req->handle = handle;
534 if (!(status = wine_server_call( req )))
536 info.ExitStatus = reply->exit_code;
537 info.TebBaseAddress = reply->teb;
538 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
539 info.ClientId.UniqueThread = (HANDLE)reply->tid;
540 info.AffinityMask = reply->affinity;
541 info.Priority = reply->priority;
542 info.BasePriority = reply->priority; /* FIXME */
546 if (status == STATUS_SUCCESS)
548 if (data) memcpy( data, &info, min( length, sizeof(info) ));
549 if (ret_len) *ret_len = min( length, sizeof(info) );
555 case ThreadBasePriority:
556 case ThreadAffinityMask:
557 case ThreadImpersonationToken:
558 case ThreadDescriptorTableEntry:
559 case ThreadEnableAlignmentFaultFixup:
560 case ThreadEventPair_Reusable:
561 case ThreadQuerySetWin32StartAddress:
562 case ThreadZeroTlsCell:
563 case ThreadPerformanceCount:
564 case ThreadAmILastThread:
565 case ThreadIdealProcessor:
566 case ThreadPriorityBoost:
567 case ThreadSetTlsArrayAddress:
568 case ThreadIsIoPending:
570 FIXME( "info class %d not supported yet\n", class );
571 return STATUS_NOT_IMPLEMENTED;
576 /******************************************************************************
577 * NtSetInformationThread (NTDLL.@)
578 * ZwSetInformationThread (NTDLL.@)
580 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
581 LPCVOID data, ULONG length )
586 case ThreadZeroTlsCell:
587 if (handle == GetCurrentThread())
592 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
593 index = *(const DWORD *)data;
594 if (index < TLS_MINIMUM_AVAILABLE)
597 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
599 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
600 teb->TlsSlots[index] = 0;
606 index -= TLS_MINIMUM_AVAILABLE;
607 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
608 return STATUS_INVALID_PARAMETER;
610 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
612 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
613 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
617 return STATUS_SUCCESS;
619 FIXME( "ZeroTlsCell not supported on other threads\n" );
620 return STATUS_NOT_IMPLEMENTED;
622 case ThreadImpersonationToken:
624 const HANDLE *phToken = data;
625 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
626 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
627 SERVER_START_REQ( set_thread_info )
629 req->handle = handle;
630 req->token = *phToken;
631 req->mask = SET_THREAD_INFO_TOKEN;
632 status = wine_server_call( req );
637 case ThreadBasicInformation:
640 case ThreadBasePriority:
641 case ThreadAffinityMask:
642 case ThreadDescriptorTableEntry:
643 case ThreadEnableAlignmentFaultFixup:
644 case ThreadEventPair_Reusable:
645 case ThreadQuerySetWin32StartAddress:
646 case ThreadPerformanceCount:
647 case ThreadAmILastThread:
648 case ThreadIdealProcessor:
649 case ThreadPriorityBoost:
650 case ThreadSetTlsArrayAddress:
651 case ThreadIsIoPending:
653 FIXME( "info class %d not supported yet\n", class );
654 return STATUS_NOT_IMPLEMENTED;
659 /**********************************************************************
660 * NtCurrentTeb (NTDLL.@)
662 #if defined(__i386__) && defined(__GNUC__)
664 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
666 #elif defined(__i386__) && defined(_MSC_VER)
668 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
672 /**********************************************************************/
674 TEB * WINAPI NtCurrentTeb(void)
676 return wine_pthread_get_current_teb();
679 #endif /* __i386__ */