Implemented kernel32:SetThreadPriority on top of ntdll's equivalent
[wine/multimedia.git] / dlls / ntdll / thread.c
bloba6b5d168bc4146d6300f92cc3f21c0ecd968d713
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;
56 struct wine_pthread_functions pthread_functions = { NULL };
58 /***********************************************************************
59 * init_teb
61 static inline NTSTATUS init_teb( TEB *teb )
63 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
65 teb->Tib.ExceptionList = (void *)~0UL;
66 teb->Tib.StackBase = (void *)~0UL;
67 teb->Tib.Self = &teb->Tib;
68 teb->Peb = &peb;
69 teb->StaticUnicodeString.Buffer = teb->StaticUnicodeBuffer;
70 teb->StaticUnicodeString.MaximumLength = sizeof(teb->StaticUnicodeBuffer);
72 if (!(thread_data->teb_sel = wine_ldt_alloc_fs())) return STATUS_TOO_MANY_THREADS;
73 thread_data->request_fd = -1;
74 thread_data->reply_fd = -1;
75 thread_data->wait_fd[0] = -1;
76 thread_data->wait_fd[1] = -1;
78 return STATUS_SUCCESS;
82 /***********************************************************************
83 * free_teb
85 static inline void free_teb( TEB *teb )
87 ULONG size = 0;
88 void *addr = teb;
89 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
91 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
92 wine_ldt_free_fs( thread_data->teb_sel );
93 munmap( teb, SIGNAL_STACK_SIZE + sizeof(TEB) );
97 /***********************************************************************
98 * thread_init
100 * Setup the initial thread.
102 * NOTES: The first allocated TEB on NT is at 0x7ffde000.
104 void thread_init(void)
106 TEB *teb;
107 void *addr;
108 ULONG info_size;
109 struct ntdll_thread_data *thread_data;
110 struct wine_pthread_thread_info thread_info;
111 static struct debug_info debug_info; /* debug info for initial thread */
113 peb.NumberOfProcessors = 1;
114 peb.ProcessParameters = &params;
115 peb.TlsBitmap = &tls_bitmap;
116 peb.TlsExpansionBitmap = &tls_expansion_bitmap;
117 peb.LdrData = &ldr;
118 params.CurrentDirectory.DosPath.Buffer = current_dir;
119 params.CurrentDirectory.DosPath.MaximumLength = sizeof(current_dir);
120 RtlInitializeBitMap( &tls_bitmap, peb.TlsBitmapBits, sizeof(peb.TlsBitmapBits) * 8 );
121 RtlInitializeBitMap( &tls_expansion_bitmap, peb.TlsExpansionBitmapBits,
122 sizeof(peb.TlsExpansionBitmapBits) * 8 );
123 InitializeListHead( &ldr.InLoadOrderModuleList );
124 InitializeListHead( &ldr.InMemoryOrderModuleList );
125 InitializeListHead( &ldr.InInitializationOrderModuleList );
126 InitializeListHead( &tls_links );
128 thread_info.teb_size = SIGNAL_STACK_SIZE + sizeof(TEB);
129 VIRTUAL_alloc_teb( &addr, thread_info.teb_size, TRUE );
130 teb = addr;
131 init_teb( teb );
132 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
133 thread_data->debug_info = &debug_info;
134 InsertHeadList( &tls_links, &teb->TlsLinks );
136 thread_info.stack_base = NULL;
137 thread_info.stack_size = 0;
138 thread_info.teb_base = teb;
139 thread_info.teb_sel = thread_data->teb_sel;
140 wine_pthread_get_functions( &pthread_functions, sizeof(pthread_functions) );
141 pthread_functions.init_current_teb( &thread_info );
142 pthread_functions.init_thread( &thread_info );
144 debug_info.str_pos = debug_info.strings;
145 debug_info.out_pos = debug_info.output;
146 debug_init();
148 /* setup the server connection */
149 server_init_process();
150 info_size = server_init_thread( thread_info.pid, thread_info.tid, NULL );
152 /* create the process heap */
153 if (!(peb.ProcessHeap = RtlCreateHeap( HEAP_GROWABLE, NULL, 0, 0, NULL, NULL )))
155 MESSAGE( "wine: failed to create the process heap\n" );
156 exit(1);
159 /* allocate user parameters */
160 if (info_size)
162 RTL_USER_PROCESS_PARAMETERS *params = NULL;
164 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&params, 0, &info_size,
165 MEM_COMMIT, PAGE_READWRITE ) == STATUS_SUCCESS)
167 params->AllocationSize = info_size;
168 NtCurrentTeb()->Peb->ProcessParameters = params;
171 else
173 /* This is wine specific: we have no parent (we're started from unix)
174 * so, create a simple console with bare handles to unix stdio
176 wine_server_fd_to_handle( 0, GENERIC_READ|SYNCHRONIZE, TRUE, &params.hStdInput );
177 wine_server_fd_to_handle( 1, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params.hStdOutput );
178 wine_server_fd_to_handle( 2, GENERIC_WRITE|SYNCHRONIZE, TRUE, &params.hStdError );
183 /***********************************************************************
184 * start_thread
186 * Startup routine for a newly created thread.
188 static void start_thread( struct wine_pthread_thread_info *info )
190 TEB *teb = info->teb_base;
191 struct ntdll_thread_data *thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
192 struct startup_info *startup_info = (struct startup_info *)info;
193 PRTL_THREAD_START_ROUTINE func = startup_info->entry_point;
194 void *arg = startup_info->entry_arg;
195 struct debug_info debug_info;
196 ULONG size;
198 debug_info.str_pos = debug_info.strings;
199 debug_info.out_pos = debug_info.output;
200 thread_data->debug_info = &debug_info;
202 pthread_functions.init_current_teb( info );
203 SIGNAL_Init();
204 server_init_thread( info->pid, info->tid, func );
205 pthread_functions.init_thread( info );
207 /* allocate a memory view for the stack */
208 size = info->stack_size;
209 teb->DeallocationStack = info->stack_base;
210 NtAllocateVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, 0,
211 &size, MEM_SYSTEM, PAGE_READWRITE );
212 /* limit is lower than base since the stack grows down */
213 teb->Tib.StackBase = (char *)info->stack_base + info->stack_size;
214 teb->Tib.StackLimit = info->stack_base;
216 /* setup the guard page */
217 size = 1;
218 NtProtectVirtualMemory( NtCurrentProcess(), &teb->DeallocationStack, &size,
219 PAGE_READWRITE | PAGE_GUARD, NULL );
220 RtlFreeHeap( GetProcessHeap(), 0, info );
222 RtlAcquirePebLock();
223 InsertHeadList( &tls_links, &teb->TlsLinks );
224 RtlReleasePebLock();
226 func( arg );
230 /***********************************************************************
231 * RtlCreateUserThread (NTDLL.@)
233 NTSTATUS WINAPI RtlCreateUserThread( HANDLE process, const SECURITY_DESCRIPTOR *descr,
234 BOOLEAN suspended, PVOID stack_addr,
235 SIZE_T stack_reserve, SIZE_T stack_commit,
236 PRTL_THREAD_START_ROUTINE start, void *param,
237 HANDLE *handle_ptr, CLIENT_ID *id )
239 struct ntdll_thread_data *thread_data = NULL;
240 struct startup_info *info = NULL;
241 void *addr;
242 HANDLE handle = 0;
243 TEB *teb;
244 DWORD tid = 0;
245 int request_pipe[2];
246 NTSTATUS status;
248 if( ! is_current_process( process ) )
250 ERR("Unsupported on other process\n");
251 return STATUS_ACCESS_DENIED;
254 if (pipe( request_pipe ) == -1) return STATUS_TOO_MANY_OPENED_FILES;
255 fcntl( request_pipe[1], F_SETFD, 1 ); /* set close on exec flag */
256 wine_server_send_fd( request_pipe[0] );
258 SERVER_START_REQ( new_thread )
260 req->suspend = suspended;
261 req->inherit = 0; /* FIXME */
262 req->request_fd = request_pipe[0];
263 if (!(status = wine_server_call( req )))
265 handle = reply->handle;
266 tid = reply->tid;
268 close( request_pipe[0] );
270 SERVER_END_REQ;
272 if (status) goto error;
274 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
276 status = STATUS_NO_MEMORY;
277 goto error;
280 info->pthread_info.teb_size = SIGNAL_STACK_SIZE + sizeof(TEB);
281 if ((status = VIRTUAL_alloc_teb( &addr, info->pthread_info.teb_size, FALSE ))) goto error;
282 teb = addr;
283 if ((status = init_teb( teb ))) goto error;
285 teb->ClientId.UniqueProcess = (HANDLE)GetCurrentProcessId();
286 teb->ClientId.UniqueThread = (HANDLE)tid;
288 thread_data = (struct ntdll_thread_data *)teb->SystemReserved2;
289 thread_data->request_fd = request_pipe[1];
291 info->pthread_info.teb_base = teb;
292 info->pthread_info.teb_sel = thread_data->teb_sel;
294 if (!stack_reserve || !stack_commit)
296 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( NtCurrentTeb()->Peb->ImageBaseAddress );
297 if (!stack_reserve) stack_reserve = nt->OptionalHeader.SizeOfStackReserve;
298 if (!stack_commit) stack_commit = nt->OptionalHeader.SizeOfStackCommit;
300 if (stack_reserve < stack_commit) stack_reserve = stack_commit;
301 stack_reserve = (stack_reserve + 0xffff) & ~0xffff; /* round to 64K boundary */
302 if (stack_reserve < 1024 * 1024) stack_reserve = 1024 * 1024; /* Xlib needs a large stack */
304 info->pthread_info.stack_base = NULL;
305 info->pthread_info.stack_size = stack_reserve;
306 info->pthread_info.entry = start_thread;
307 info->entry_point = start;
308 info->entry_arg = param;
310 if (pthread_functions.create_thread( &info->pthread_info ) == -1)
312 status = STATUS_NO_MEMORY;
313 goto error;
316 if (id) id->UniqueThread = (HANDLE)tid;
317 if (handle_ptr) *handle_ptr = handle;
318 else NtClose( handle );
320 return STATUS_SUCCESS;
322 error:
323 if (thread_data) wine_ldt_free_fs( thread_data->teb_sel );
324 if (addr)
326 ULONG size = 0;
327 NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size, MEM_RELEASE );
329 if (info) RtlFreeHeap( GetProcessHeap(), 0, info );
330 if (handle) NtClose( handle );
331 close( request_pipe[1] );
332 return status;
336 /***********************************************************************
337 * RtlExitUserThread (NTDLL.@)
339 void WINAPI RtlExitUserThread( ULONG status )
341 LdrShutdownThread();
342 server_exit_thread( status );
346 /***********************************************************************
347 * NtOpenThread (NTDLL.@)
348 * ZwOpenThread (NTDLL.@)
350 NTSTATUS WINAPI NtOpenThread( HANDLE *handle, ACCESS_MASK access,
351 const OBJECT_ATTRIBUTES *attr, const CLIENT_ID *id )
353 NTSTATUS ret;
355 SERVER_START_REQ( open_thread )
357 req->tid = (thread_id_t)id->UniqueThread;
358 req->access = access;
359 req->inherit = attr && (attr->Attributes & OBJ_INHERIT);
360 ret = wine_server_call( req );
361 *handle = reply->handle;
363 SERVER_END_REQ;
364 return ret;
368 /******************************************************************************
369 * NtSuspendThread (NTDLL.@)
370 * ZwSuspendThread (NTDLL.@)
372 NTSTATUS WINAPI NtSuspendThread( HANDLE handle, PULONG count )
374 NTSTATUS ret;
376 SERVER_START_REQ( suspend_thread )
378 req->handle = handle;
379 if (!(ret = wine_server_call( req ))) *count = reply->count;
381 SERVER_END_REQ;
382 return ret;
386 /******************************************************************************
387 * NtResumeThread (NTDLL.@)
388 * ZwResumeThread (NTDLL.@)
390 NTSTATUS WINAPI NtResumeThread( HANDLE handle, PULONG count )
392 NTSTATUS ret;
394 SERVER_START_REQ( resume_thread )
396 req->handle = handle;
397 if (!(ret = wine_server_call( req ))) *count = reply->count;
399 SERVER_END_REQ;
400 return ret;
404 /******************************************************************************
405 * NtAlertResumeThread (NTDLL.@)
406 * ZwAlertResumeThread (NTDLL.@)
408 NTSTATUS WINAPI NtAlertResumeThread( HANDLE handle, PULONG count )
410 FIXME( "stub: should alert thread %p\n", handle );
411 return NtResumeThread( handle, count );
415 /******************************************************************************
416 * NtAlertThread (NTDLL.@)
417 * ZwAlertThread (NTDLL.@)
419 NTSTATUS WINAPI NtAlertThread( HANDLE handle )
421 FIXME( "stub: %p\n", handle );
422 return STATUS_NOT_IMPLEMENTED;
426 /******************************************************************************
427 * NtTerminateThread (NTDLL.@)
428 * ZwTerminateThread (NTDLL.@)
430 NTSTATUS WINAPI NtTerminateThread( HANDLE handle, LONG exit_code )
432 NTSTATUS ret;
433 BOOL self, last;
435 SERVER_START_REQ( terminate_thread )
437 req->handle = handle;
438 req->exit_code = exit_code;
439 ret = wine_server_call( req );
440 self = !ret && reply->self;
441 last = reply->last;
443 SERVER_END_REQ;
445 if (self)
447 if (last) exit( exit_code );
448 else server_abort_thread( exit_code );
450 return ret;
454 /******************************************************************************
455 * NtQueueApcThread (NTDLL.@)
457 NTSTATUS WINAPI NtQueueApcThread( HANDLE handle, PNTAPCFUNC func, ULONG_PTR arg1,
458 ULONG_PTR arg2, ULONG_PTR arg3 )
460 NTSTATUS ret;
461 SERVER_START_REQ( queue_apc )
463 req->handle = handle;
464 req->user = 1;
465 req->func = func;
466 req->arg1 = (void *)arg1;
467 req->arg2 = (void *)arg2;
468 req->arg3 = (void *)arg3;
469 ret = wine_server_call( req );
471 SERVER_END_REQ;
472 return ret;
476 /***********************************************************************
477 * NtSetContextThread (NTDLL.@)
478 * ZwSetContextThread (NTDLL.@)
480 NTSTATUS WINAPI NtSetContextThread( HANDLE handle, const CONTEXT *context )
482 NTSTATUS ret;
484 SERVER_START_REQ( set_thread_context )
486 req->handle = handle;
487 req->flags = context->ContextFlags;
488 wine_server_add_data( req, context, sizeof(*context) );
489 ret = wine_server_call( req );
491 SERVER_END_REQ;
492 return ret;
496 /***********************************************************************
497 * NtGetContextThread (NTDLL.@)
498 * ZwGetContextThread (NTDLL.@)
500 NTSTATUS WINAPI NtGetContextThread( HANDLE handle, CONTEXT *context )
502 NTSTATUS ret;
504 SERVER_START_REQ( get_thread_context )
506 req->handle = handle;
507 req->flags = context->ContextFlags;
508 wine_server_add_data( req, context, sizeof(*context) );
509 wine_server_set_reply( req, context, sizeof(*context) );
510 ret = wine_server_call( req );
512 SERVER_END_REQ;
513 return ret;
517 /******************************************************************************
518 * NtQueryInformationThread (NTDLL.@)
519 * ZwQueryInformationThread (NTDLL.@)
521 NTSTATUS WINAPI NtQueryInformationThread( HANDLE handle, THREADINFOCLASS class,
522 void *data, ULONG length, ULONG *ret_len )
524 NTSTATUS status;
526 switch(class)
528 case ThreadBasicInformation:
530 THREAD_BASIC_INFORMATION info;
532 SERVER_START_REQ( get_thread_info )
534 req->handle = handle;
535 req->tid_in = 0;
536 if (!(status = wine_server_call( req )))
538 info.ExitStatus = reply->exit_code;
539 info.TebBaseAddress = reply->teb;
540 info.ClientId.UniqueProcess = (HANDLE)reply->pid;
541 info.ClientId.UniqueThread = (HANDLE)reply->tid;
542 info.AffinityMask = reply->affinity;
543 info.Priority = reply->priority;
544 info.BasePriority = reply->priority; /* FIXME */
547 SERVER_END_REQ;
548 if (status == STATUS_SUCCESS)
550 if (data) memcpy( data, &info, min( length, sizeof(info) ));
551 if (ret_len) *ret_len = min( length, sizeof(info) );
554 return status;
555 case ThreadTimes:
556 case ThreadPriority:
557 case ThreadBasePriority:
558 case ThreadAffinityMask:
559 case ThreadImpersonationToken:
560 case ThreadDescriptorTableEntry:
561 case ThreadEnableAlignmentFaultFixup:
562 case ThreadEventPair_Reusable:
563 case ThreadQuerySetWin32StartAddress:
564 case ThreadZeroTlsCell:
565 case ThreadPerformanceCount:
566 case ThreadAmILastThread:
567 case ThreadIdealProcessor:
568 case ThreadPriorityBoost:
569 case ThreadSetTlsArrayAddress:
570 case ThreadIsIoPending:
571 default:
572 FIXME( "info class %d not supported yet\n", class );
573 return STATUS_NOT_IMPLEMENTED;
578 /******************************************************************************
579 * NtSetInformationThread (NTDLL.@)
580 * ZwSetInformationThread (NTDLL.@)
582 NTSTATUS WINAPI NtSetInformationThread( HANDLE handle, THREADINFOCLASS class,
583 LPCVOID data, ULONG length )
585 NTSTATUS status;
586 switch(class)
588 case ThreadZeroTlsCell:
589 if (handle == GetCurrentThread())
591 LIST_ENTRY *entry;
592 DWORD index;
594 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
595 index = *(const DWORD *)data;
596 if (index < TLS_MINIMUM_AVAILABLE)
598 RtlAcquirePebLock();
599 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
601 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
602 teb->TlsSlots[index] = 0;
604 RtlReleasePebLock();
606 else
608 index -= TLS_MINIMUM_AVAILABLE;
609 if (index >= 8 * sizeof(NtCurrentTeb()->Peb->TlsExpansionBitmapBits))
610 return STATUS_INVALID_PARAMETER;
611 RtlAcquirePebLock();
612 for (entry = tls_links.Flink; entry != &tls_links; entry = entry->Flink)
614 TEB *teb = CONTAINING_RECORD(entry, TEB, TlsLinks);
615 if (teb->TlsExpansionSlots) teb->TlsExpansionSlots[index] = 0;
617 RtlReleasePebLock();
619 return STATUS_SUCCESS;
621 FIXME( "ZeroTlsCell not supported on other threads\n" );
622 return STATUS_NOT_IMPLEMENTED;
624 case ThreadImpersonationToken:
626 const HANDLE *phToken = data;
627 if (length != sizeof(HANDLE)) return STATUS_INVALID_PARAMETER;
628 TRACE("Setting ThreadImpersonationToken handle to %p\n", *phToken );
629 SERVER_START_REQ( set_thread_info )
631 req->handle = handle;
632 req->token = *phToken;
633 req->mask = SET_THREAD_INFO_TOKEN;
634 status = wine_server_call( req );
636 SERVER_END_REQ;
638 return status;
639 case ThreadBasePriority:
641 const DWORD *pprio = data;
642 if (length != sizeof(DWORD)) return STATUS_INVALID_PARAMETER;
643 SERVER_START_REQ( set_thread_info )
645 req->handle = handle;
646 req->priority = *pprio;
647 req->mask = SET_THREAD_INFO_PRIORITY;
648 status = wine_server_call( req );
650 SERVER_END_REQ;
652 return status;
653 case ThreadBasicInformation:
654 case ThreadTimes:
655 case ThreadPriority:
656 case ThreadAffinityMask:
657 case ThreadDescriptorTableEntry:
658 case ThreadEnableAlignmentFaultFixup:
659 case ThreadEventPair_Reusable:
660 case ThreadQuerySetWin32StartAddress:
661 case ThreadPerformanceCount:
662 case ThreadAmILastThread:
663 case ThreadIdealProcessor:
664 case ThreadPriorityBoost:
665 case ThreadSetTlsArrayAddress:
666 case ThreadIsIoPending:
667 default:
668 FIXME( "info class %d not supported yet\n", class );
669 return STATUS_NOT_IMPLEMENTED;
674 /**********************************************************************
675 * NtCurrentTeb (NTDLL.@)
677 #if defined(__i386__) && defined(__GNUC__)
679 __ASM_GLOBAL_FUNC( NtCurrentTeb, ".byte 0x64\n\tmovl 0x18,%eax\n\tret" );
681 #elif defined(__i386__) && defined(_MSC_VER)
683 /* Nothing needs to be done. MS C "magically" exports the inline version from winnt.h */
685 #else
687 /**********************************************************************/
689 TEB * WINAPI NtCurrentTeb(void)
691 return pthread_functions.get_current_teb();
694 #endif /* __i386__ */