Remove local declarations already in included public headers.
[wine/multimedia.git] / dlls / ntdll / thread.c
blob42bddadfc4a526340a7c81e664f8d52f4feb4951
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <sys/types.h>
25 #ifdef HAVE_SYS_MMAN_H
26 #include <sys/mman.h>
27 #endif
29 #include "ntstatus.h"
30 #include "thread.h"
31 #include "winternl.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 */
41 struct startup_info
43 struct wine_pthread_thread_info pthread_info;
44 PRTL_THREAD_START_ROUTINE entry_point;
45 void *entry_arg;
48 static PEB peb;
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 /***********************************************************************
58 * init_teb
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;
67 teb->Peb = &peb;
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 /***********************************************************************
82 * free_teb
84 static inline void free_teb( TEB *teb )
86 ULONG size = 0;
87 void *addr = 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 /***********************************************************************
97 * thread_init
99 * Setup the initial thread.
101 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
103 void thread_init(void)
105 TEB *teb;
106 void *addr;
107 ULONG info_size;
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 = &params;
114 peb.TlsBitmap = &tls_bitmap;
115 peb.TlsExpansionBitmap = &tls_expansion_bitmap;
116 peb.LdrData = &ldr;
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 );
129 teb = addr;
130 init_teb( teb );
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;
144 debug_init();
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" );
154 exit(1);
157 /* allocate user parameters */
158 if (info_size)
160 RTL_USER_PROCESS_PARAMETERS *params = NULL;
162 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&params, 0, &info_size,
163 MEM_COMMIT, PAGE_READWRITE ) == STATUS_SUCCESS)
165 params->AllocationSize = info_size;
166 NtCurrentTeb()->Peb->ProcessParameters = params;
169 else
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, &params.hStdInput );
175 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params.hStdOutput );
176 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params.hStdError );
181 /***********************************************************************
182 * start_thread
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;
194 ULONG size;
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 );
201 SIGNAL_Init();
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 */
215 size = 1;
216 NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size,
217 PAGE_READWRITE | PAGE_GUARD, NULL );
218 RtlFreeHeap( GetProcessHeap(), 0, info );
220 RtlAcquirePebLock();
221 InsertHeadList( &tls_links, &teb->TlsLinks );
222 RtlReleasePebLock();
224 func( arg );
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;
239 void *addr;
240 HANDLE handle = 0;
241 TEB *teb;
242 DWORD tid = 0;
243 int request_pipe[2];
244 NTSTATUS status;
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;
264 tid = reply->tid;
266 close( request_pipe[0] );
268 SERVER_END_REQ;
270 if (status) goto error;
272 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
274 status = STATUS_NO_MEMORY;
275 goto error;
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;
280 teb = addr;
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;
311 goto error;
314 if (id) id->UniqueThread = (HANDLE)tid;
315 if (handle_ptr) *handle_ptr = handle;
316 else NtClose( handle );
318 return STATUS_SUCCESS;
320 error:
321 if (thread_data) wine_ldt_free_fs( thread_data->teb_sel );
322 if (addr)
324 ULONG size = 0;
325 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
327 if (info) RtlFreeHeap( GetProcessHeap(), 0, info );
328 if (handle) NtClose( handle );
329 close( request_pipe[1] );
330 return status;
334 /***********************************************************************
335 * RtlExitUserThread (NTDLL.@)
337 void WINAPI RtlExitUserThread( ULONG status )
339 LdrShutdownThread();
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 )
351 NTSTATUS ret;
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;
361 SERVER_END_REQ;
362 return ret;
366 /******************************************************************************
367 * NtSuspendThread (NTDLL.@)
368 * ZwSuspendThread (NTDLL.@)
370 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
372 NTSTATUS ret;
374 SERVER_START_REQ( suspend_thread )
376 req->handle = handle;
377 if (!(ret = wine_server_call( req ))) *count = reply->count;
379 SERVER_END_REQ;
380 return ret;
384 /******************************************************************************
385 * NtResumeThread (NTDLL.@)
386 * ZwResumeThread (NTDLL.@)
388 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
390 NTSTATUS ret;
392 SERVER_START_REQ( resume_thread )
394 req->handle = handle;
395 if (!(ret = wine_server_call( req ))) *count = reply->count;
397 SERVER_END_REQ;
398 return ret;
402 /******************************************************************************
403 * NtTerminateThread (NTDLL.@)
404 * ZwTerminateThread (NTDLL.@)
406 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
408 NTSTATUS ret;
409 BOOL self, last;
411 SERVER_START_REQ( terminate_thread )
413 req->handle = handle;
414 req->exit_code = exit_code;
415 ret = wine_server_call( req );
416 self = !ret && reply->self;
417 last = reply->last;
419 SERVER_END_REQ;
421 if (self)
423 if (last) exit( exit_code );
424 else server_abort_thread( exit_code );
426 return ret;
430 /******************************************************************************
431 * NtQueueApcThread (NTDLL.@)
433 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
434 ULONG_PTR arg2, ULONG_PTR arg3 )
436 NTSTATUS ret;
437 SERVER_START_REQ( queue_apc )
439 req->handle = handle;
440 req->user = 1;
441 req->func = func;
442 req->arg1 = (void *)arg1;
443 req->arg2 = (void *)arg2;
444 req->arg3 = (void *)arg3;
445 ret = wine_server_call( req );
447 SERVER_END_REQ;
448 return ret;
452 /***********************************************************************
453 * NtSetContextThread (NTDLL.@)
454 * ZwSetContextThread (NTDLL.@)
456 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
458 NTSTATUS ret;
460 SERVER_START_REQ( set_thread_context )
462 req->handle = handle;
463 req->flags = context->ContextFlags;
464 wine_server_add_data( req, context, sizeof(*context) );
465 ret = wine_server_call( req );
467 SERVER_END_REQ;
468 return ret;
472 /***********************************************************************
473 * NtGetContextThread (NTDLL.@)
474 * ZwGetContextThread (NTDLL.@)
476 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
478 NTSTATUS ret;
480 SERVER_START_REQ( get_thread_context )
482 req->handle = handle;
483 req->flags = context->ContextFlags;
484 wine_server_add_data( req, context, sizeof(*context) );
485 wine_server_set_reply( req, context, sizeof(*context) );
486 ret = wine_server_call( req );
488 SERVER_END_REQ;
489 return ret;
493 /******************************************************************************
494 * NtQueryInformationThread (NTDLL.@)
495 * ZwQueryInformationThread (NTDLL.@)
497 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
498 void *data, ULONG length, ULONG *ret_len )
500 NTSTATUS status;
502 switch(class)
504 case ThreadBasicInformation:
506 THREAD_BASIC_INFORMATION info;
508 SERVER_START_REQ( get_thread_info )
510 req->handle = handle;
511 req->tid_in = 0;
512 if (!(status = wine_server_call( req )))
514 info.ExitStatus = reply->exit_code;
515 info.TebBaseAddress = reply->teb;
516 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
517 info.ClientId.UniqueThread = (HANDLE)reply->tid;
518 info.AffinityMask = reply->affinity;
519 info.Priority = reply->priority;
520 info.BasePriority = reply->priority; /* FIXME */
523 SERVER_END_REQ;
524 if (status == STATUS_SUCCESS)
526 if (data) memcpy( data, &info, min( length, sizeof(info) ));
527 if (ret_len) *ret_len = min( length, sizeof(info) );
530 return status;
531 case ThreadTimes:
532 case ThreadPriority:
533 case ThreadBasePriority:
534 case ThreadAffinityMask:
535 case ThreadImpersonationToken:
536 case ThreadDescriptorTableEntry:
537 case ThreadEnableAlignmentFaultFixup:
538 case ThreadEventPair_Reusable:
539 case ThreadQuerySetWin32StartAddress:
540 case ThreadZeroTlsCell:
541 case ThreadPerformanceCount:
542 case ThreadAmILastThread:
543 case ThreadIdealProcessor:
544 case ThreadPriorityBoost:
545 case ThreadSetTlsArrayAddress:
546 case ThreadIsIoPending:
547 default:
548 FIXME( "info class %d not supported yet\n", class );
549 return STATUS_NOT_IMPLEMENTED;
554 /******************************************************************************
555 * NtSetInformationThread (NTDLL.@)
556 * ZwSetInformationThread (NTDLL.@)
558 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
559 LPCVOID data, ULONG length )
561 NTSTATUS status;
562 switch(class)
564 case ThreadZeroTlsCell:
565 if (handle == GetCurrentThread())
567 LIST_ENTRY *entry;
568 DWORD index;
570 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
571 index = *(const DWORD *)data;
572 if (index < TLS_MINIMUM_AVAILABLE)
574 RtlAcquirePebLock();
575 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
577 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
578 teb->TlsSlots[index] = 0;
580 RtlReleasePebLock();
582 else
584 index -= TLS_MINIMUM_AVAILABLE;
585 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
586 return STATUS_INVALID_PARAMETER;
587 RtlAcquirePebLock();
588 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
590 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
591 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
593 RtlReleasePebLock();
595 return STATUS_SUCCESS;
597 FIXME( "ZeroTlsCell not supported on other threads\n" );
598 return STATUS_NOT_IMPLEMENTED;
600 case ThreadImpersonationToken:
602 const HANDLE *phToken = data;
603 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
604 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
605 SERVER_START_REQ( set_thread_info )
607 req->handle = handle;
608 req->token = *phToken;
609 req->mask = SET_THREAD_INFO_TOKEN;
610 status = wine_server_call( req );
612 SERVER_END_REQ;
613 return status;
615 case ThreadBasicInformation:
616 case ThreadTimes:
617 case ThreadPriority:
618 case ThreadBasePriority:
619 case ThreadAffinityMask:
620 case ThreadDescriptorTableEntry:
621 case ThreadEnableAlignmentFaultFixup:
622 case ThreadEventPair_Reusable:
623 case ThreadQuerySetWin32StartAddress:
624 case ThreadPerformanceCount:
625 case ThreadAmILastThread:
626 case ThreadIdealProcessor:
627 case ThreadPriorityBoost:
628 case ThreadSetTlsArrayAddress:
629 case ThreadIsIoPending:
630 default:
631 FIXME( "info class %d not supported yet\n", class );
632 return STATUS_NOT_IMPLEMENTED;
637 /**********************************************************************
638 * NtCurrentTeb (NTDLL.@)
640 #if defined(__i386__) && defined(__GNUC__)
642 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
644 #elif defined(__i386__) && defined(_MSC_VER)
646 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
648 #else
650 /**********************************************************************/
652 TEB * WINAPI NtCurrentTeb(void)
654 return wine_pthread_get_current_teb();
657 #endif /* __i386__ */