Force minimum stack size to 1Mb for Xlib.
[wine.git] / dlls / kernel / thread.c
blob6d59e0330b38e4820202e9d037f59ab25f7fe12e
1 /*
2 * Win32 threads
4 * Copyright 1996 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 <assert.h>
25 #include <fcntl.h>
26 #include <stdarg.h>
27 #include <signal.h>
28 #include <sys/types.h>
29 #ifdef HAVE_SYS_TIMES_H
30 #include <sys/times.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
36 #include "ntstatus.h"
37 #include "windef.h"
38 #include "winbase.h"
39 #include "winerror.h"
40 #include "winnls.h"
41 #include "module.h"
42 #include "thread.h"
43 #include "wine/winbase16.h"
44 #include "wine/library.h"
45 #include "wine/pthread.h"
46 #include "wine/server.h"
47 #include "wine/debug.h"
49 WINE_DEFAULT_DEBUG_CHANNEL(thread);
50 WINE_DECLARE_DEBUG_CHANNEL(relay);
53 /***********************************************************************
54 * THREAD_InitStack
56 * Allocate the stack of a thread.
58 TEB *THREAD_InitStack( TEB *teb, DWORD stack_size )
60 DWORD old_prot;
61 DWORD page_size = getpagesize();
62 void *base;
64 stack_size = (stack_size + (page_size - 1)) & ~(page_size - 1);
65 if (stack_size < 1024 * 1024) stack_size = 1024 * 1024; /* Xlib needs a large stack */
67 if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE )))
68 return NULL;
70 teb->DeallocationStack = base;
71 teb->Tib.StackBase = (char *)base + stack_size;
72 teb->Tib.StackLimit = base; /* note: limit is lower than base since the stack grows down */
74 /* Setup guard pages */
76 VirtualProtect( base, 1, PAGE_EXECUTE_READWRITE | PAGE_GUARD, &old_prot );
77 return teb;
81 struct new_thread_info
83 LPTHREAD_START_ROUTINE func;
84 void *arg;
87 /***********************************************************************
88 * THREAD_Start
90 * Start execution of a newly created thread. Does not return.
92 static void CALLBACK THREAD_Start( void *ptr )
94 struct new_thread_info *info = ptr;
95 LPTHREAD_START_ROUTINE func = info->func;
96 void *arg = info->arg;
98 RtlFreeHeap( GetProcessHeap(), 0, info );
100 if (TRACE_ON(relay))
101 DPRINTF("%04lx:Starting thread (entryproc=%p)\n", GetCurrentThreadId(), func );
103 __TRY
105 MODULE_DllThreadAttach( NULL );
106 ExitThread( func( arg ) );
108 __EXCEPT(UnhandledExceptionFilter)
110 TerminateThread( GetCurrentThread(), GetExceptionCode() );
112 __ENDTRY
116 /***********************************************************************
117 * CreateThread (KERNEL32.@)
119 HANDLE WINAPI CreateThread( SECURITY_ATTRIBUTES *sa, SIZE_T stack,
120 LPTHREAD_START_ROUTINE start, LPVOID param,
121 DWORD flags, LPDWORD id )
123 HANDLE handle;
124 CLIENT_ID client_id;
125 NTSTATUS status;
126 SIZE_T stack_reserve = 0, stack_commit = 0;
127 struct new_thread_info *info;
129 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
131 SetLastError( ERROR_NOT_ENOUGH_MEMORY );
132 return 0;
134 info->func = start;
135 info->arg = param;
137 if (flags & STACK_SIZE_PARAM_IS_A_RESERVATION) stack_reserve = stack;
138 else stack_commit = stack;
140 status = RtlCreateUserThread( GetCurrentProcess(), NULL, (flags & CREATE_SUSPENDED) != 0,
141 NULL, stack_reserve, stack_commit,
142 THREAD_Start, info, &handle, &client_id );
143 if (status == STATUS_SUCCESS)
145 if (id) *id = (DWORD)client_id.UniqueThread;
146 if (sa && (sa->nLength >= sizeof(*sa)) && sa->bInheritHandle)
147 SetHandleInformation( handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT );
149 else
151 RtlFreeHeap( GetProcessHeap(), 0, info );
152 SetLastError( RtlNtStatusToDosError(status) );
153 handle = 0;
155 return handle;
159 /***********************************************************************
160 * OpenThread [KERNEL32.@] Retrieves a handle to a thread from its thread id
162 HANDLE WINAPI OpenThread( DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId )
164 HANDLE ret = 0;
165 SERVER_START_REQ( open_thread )
167 req->tid = dwThreadId;
168 req->access = dwDesiredAccess;
169 req->inherit = bInheritHandle;
170 if (!wine_server_call_err( req )) ret = reply->handle;
172 SERVER_END_REQ;
173 return ret;
177 /***********************************************************************
178 * ExitThread [KERNEL32.@] Ends a thread
180 * RETURNS
181 * None
183 void WINAPI ExitThread( DWORD code ) /* [in] Exit code for this thread */
185 BOOL last;
186 SERVER_START_REQ( terminate_thread )
188 /* send the exit code to the server */
189 req->handle = GetCurrentThread();
190 req->exit_code = code;
191 wine_server_call( req );
192 last = reply->last;
194 SERVER_END_REQ;
196 if (last)
198 LdrShutdownProcess();
199 exit( code );
201 else
203 struct wine_pthread_thread_info info;
204 sigset_t block_set;
205 ULONG size;
207 LdrShutdownThread();
208 RtlAcquirePebLock();
209 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
210 RtlReleasePebLock();
212 info.stack_base = NtCurrentTeb()->DeallocationStack;
213 info.teb_base = NtCurrentTeb();
214 info.teb_sel = wine_get_fs();
215 info.exit_status = code;
217 size = 0;
218 NtFreeVirtualMemory( GetCurrentProcess(), &info.stack_base, &size, MEM_RELEASE | MEM_SYSTEM );
219 info.stack_size = size;
221 size = 0;
222 NtFreeVirtualMemory( GetCurrentProcess(), &info.teb_base, &size, MEM_RELEASE | MEM_SYSTEM );
223 info.teb_size = size;
225 /* block the async signals */
226 sigemptyset( &block_set );
227 sigaddset( &block_set, SIGALRM );
228 sigaddset( &block_set, SIGIO );
229 sigaddset( &block_set, SIGINT );
230 sigaddset( &block_set, SIGHUP );
231 sigaddset( &block_set, SIGUSR1 );
232 sigaddset( &block_set, SIGUSR2 );
233 sigaddset( &block_set, SIGTERM );
234 sigprocmask( SIG_BLOCK, &block_set, NULL );
236 close( NtCurrentTeb()->wait_fd[0] );
237 close( NtCurrentTeb()->wait_fd[1] );
238 close( NtCurrentTeb()->reply_fd );
239 close( NtCurrentTeb()->request_fd );
241 wine_pthread_exit_thread( &info );
246 /**********************************************************************
247 * TerminateThread [KERNEL32.@] Terminates a thread
249 * RETURNS
250 * Success: TRUE
251 * Failure: FALSE
253 BOOL WINAPI TerminateThread( HANDLE handle, /* [in] Handle to thread */
254 DWORD exit_code) /* [in] Exit code for thread */
256 NTSTATUS status = NtTerminateThread( handle, exit_code );
257 if (status) SetLastError( RtlNtStatusToDosError(status) );
258 return !status;
262 /***********************************************************************
263 * FreeLibraryAndExitThread (KERNEL32.@)
265 void WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
267 FreeLibrary(hLibModule);
268 ExitThread(dwExitCode);
272 /**********************************************************************
273 * GetExitCodeThread (KERNEL32.@)
275 * Gets termination status of thread.
277 * RETURNS
278 * Success: TRUE
279 * Failure: FALSE
281 BOOL WINAPI GetExitCodeThread(
282 HANDLE hthread, /* [in] Handle to thread */
283 LPDWORD exitcode) /* [out] Address to receive termination status */
285 THREAD_BASIC_INFORMATION info;
286 NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
287 &info, sizeof(info), NULL );
289 if (status)
291 SetLastError( RtlNtStatusToDosError(status) );
292 return FALSE;
294 if (exitcode) *exitcode = info.ExitStatus;
295 return TRUE;
299 /***********************************************************************
300 * SetThreadContext [KERNEL32.@] Sets context of thread.
302 * RETURNS
303 * Success: TRUE
304 * Failure: FALSE
306 BOOL WINAPI SetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
307 const CONTEXT *context ) /* [in] Address of context structure */
309 NTSTATUS status = NtSetContextThread( handle, context );
310 if (status) SetLastError( RtlNtStatusToDosError(status) );
311 return !status;
315 /***********************************************************************
316 * GetThreadContext [KERNEL32.@] Retrieves context of thread.
318 * RETURNS
319 * Success: TRUE
320 * Failure: FALSE
322 BOOL WINAPI GetThreadContext( HANDLE handle, /* [in] Handle to thread with context */
323 CONTEXT *context ) /* [out] Address of context structure */
325 NTSTATUS status = NtGetContextThread( handle, context );
326 if (status) SetLastError( RtlNtStatusToDosError(status) );
327 return !status;
331 /**********************************************************************
332 * SuspendThread [KERNEL32.@] Suspends a thread.
334 * RETURNS
335 * Success: Previous suspend count
336 * Failure: 0xFFFFFFFF
338 DWORD WINAPI SuspendThread( HANDLE hthread ) /* [in] Handle to the thread */
340 DWORD ret;
341 NTSTATUS status = NtSuspendThread( hthread, &ret );
343 if (status)
345 ret = ~0U;
346 SetLastError( RtlNtStatusToDosError(status) );
348 return ret;
352 /**********************************************************************
353 * ResumeThread [KERNEL32.@] Resumes a thread.
355 * Decrements a thread's suspend count. When count is zero, the
356 * execution of the thread is resumed.
358 * RETURNS
359 * Success: Previous suspend count
360 * Failure: 0xFFFFFFFF
361 * Already running: 0
363 DWORD WINAPI ResumeThread( HANDLE hthread ) /* [in] Identifies thread to restart */
365 DWORD ret;
366 NTSTATUS status = NtResumeThread( hthread, &ret );
368 if (status)
370 ret = ~0U;
371 SetLastError( RtlNtStatusToDosError(status) );
373 return ret;
377 /**********************************************************************
378 * GetThreadPriority [KERNEL32.@] Returns priority for thread.
380 * RETURNS
381 * Success: Thread's priority level.
382 * Failure: THREAD_PRIORITY_ERROR_RETURN
384 INT WINAPI GetThreadPriority(
385 HANDLE hthread) /* [in] Handle to thread */
387 THREAD_BASIC_INFORMATION info;
388 NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
389 &info, sizeof(info), NULL );
391 if (status)
393 SetLastError( RtlNtStatusToDosError(status) );
394 return THREAD_PRIORITY_ERROR_RETURN;
396 return info.Priority;
400 /**********************************************************************
401 * SetThreadPriority [KERNEL32.@] Sets priority for thread.
403 * RETURNS
404 * Success: TRUE
405 * Failure: FALSE
407 BOOL WINAPI SetThreadPriority(
408 HANDLE hthread, /* [in] Handle to thread */
409 INT priority) /* [in] Thread priority level */
411 BOOL ret;
412 SERVER_START_REQ( set_thread_info )
414 req->handle = hthread;
415 req->priority = priority;
416 req->mask = SET_THREAD_INFO_PRIORITY;
417 ret = !wine_server_call_err( req );
419 SERVER_END_REQ;
420 return ret;
424 /**********************************************************************
425 * GetThreadPriorityBoost [KERNEL32.@] Returns priority boost for thread.
427 * Always reports that priority boost is disabled.
429 * RETURNS
430 * Success: TRUE.
431 * Failure: FALSE
433 BOOL WINAPI GetThreadPriorityBoost(
434 HANDLE hthread, /* [in] Handle to thread */
435 PBOOL pstate) /* [out] pointer to var that receives the boost state */
437 if (pstate) *pstate = FALSE;
438 return NO_ERROR;
442 /**********************************************************************
443 * SetThreadPriorityBoost [KERNEL32.@] Sets priority boost for thread.
445 * Priority boost is not implemented. Thsi function always returns
446 * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
448 * RETURNS
449 * Always returns FALSE to indicate a failure
451 BOOL WINAPI SetThreadPriorityBoost(
452 HANDLE hthread, /* [in] Handle to thread */
453 BOOL disable) /* [in] TRUE to disable priority boost */
455 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
456 return FALSE;
460 /**********************************************************************
461 * SetThreadAffinityMask (KERNEL32.@)
463 DWORD WINAPI SetThreadAffinityMask( HANDLE hThread, DWORD dwThreadAffinityMask )
465 DWORD ret;
466 SERVER_START_REQ( set_thread_info )
468 req->handle = hThread;
469 req->affinity = dwThreadAffinityMask;
470 req->mask = SET_THREAD_INFO_AFFINITY;
471 ret = !wine_server_call_err( req );
472 /* FIXME: should return previous value */
474 SERVER_END_REQ;
475 return ret;
479 /**********************************************************************
480 * SetThreadIdealProcessor [KERNEL32.@] Obtains timing information.
482 * RETURNS
483 * Success: Value of last call to SetThreadIdealProcessor
484 * Failure: -1
486 DWORD WINAPI SetThreadIdealProcessor(
487 HANDLE hThread, /* [in] Specifies the thread of interest */
488 DWORD dwIdealProcessor) /* [in] Specifies the new preferred processor */
490 FIXME("(%p): stub\n",hThread);
491 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
492 return -1L;
496 /* callback for QueueUserAPC */
497 static void CALLBACK call_user_apc( ULONG_PTR arg1, ULONG_PTR arg2, ULONG_PTR arg3 )
499 PAPCFUNC func = (PAPCFUNC)arg1;
500 func( arg2 );
503 /***********************************************************************
504 * QueueUserAPC (KERNEL32.@)
506 DWORD WINAPI QueueUserAPC( PAPCFUNC func, HANDLE hthread, ULONG_PTR data )
508 NTSTATUS status = NtQueueApcThread( hthread, call_user_apc, (ULONG_PTR)func, data, 0 );
510 if (status) SetLastError( RtlNtStatusToDosError(status) );
511 return !status;
515 /**********************************************************************
516 * GetThreadTimes [KERNEL32.@] Obtains timing information.
518 * RETURNS
519 * Success: TRUE
520 * Failure: FALSE
522 BOOL WINAPI GetThreadTimes(
523 HANDLE thread, /* [in] Specifies the thread of interest */
524 LPFILETIME creationtime, /* [out] When the thread was created */
525 LPFILETIME exittime, /* [out] When the thread was destroyed */
526 LPFILETIME kerneltime, /* [out] Time thread spent in kernel mode */
527 LPFILETIME usertime) /* [out] Time thread spent in user mode */
529 BOOL ret = TRUE;
531 if (creationtime || exittime)
533 /* We need to do a server call to get the creation time or exit time */
534 /* This works on any thread */
536 SERVER_START_REQ( get_thread_info )
538 req->handle = thread;
539 req->tid_in = 0;
540 if ((ret = !wine_server_call_err( req )))
542 if (creationtime)
543 RtlSecondsSince1970ToTime( reply->creation_time, (LARGE_INTEGER*)creationtime );
544 if (exittime)
545 RtlSecondsSince1970ToTime( reply->exit_time, (LARGE_INTEGER*)exittime );
548 SERVER_END_REQ;
550 if (ret && (kerneltime || usertime))
552 /* We call times(2) for kernel time or user time */
553 /* We can only (portably) do this for the current thread */
554 if (thread == GetCurrentThread())
556 ULONGLONG time;
557 struct tms time_buf;
558 long clocks_per_sec = sysconf(_SC_CLK_TCK);
560 times(&time_buf);
561 if (kerneltime)
563 time = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
564 kerneltime->dwHighDateTime = time >> 32;
565 kerneltime->dwLowDateTime = (DWORD)time;
567 if (usertime)
569 time = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
570 usertime->dwHighDateTime = time >> 32;
571 usertime->dwLowDateTime = (DWORD)time;
574 else
576 if (kerneltime) kerneltime->dwHighDateTime = kerneltime->dwLowDateTime = 0;
577 if (usertime) usertime->dwHighDateTime = usertime->dwLowDateTime = 0;
578 FIXME("Cannot get kerneltime or usertime of other threads\n");
581 return ret;
585 /**********************************************************************
586 * VWin32_BoostThreadGroup [KERNEL.535]
588 VOID WINAPI VWin32_BoostThreadGroup( DWORD threadId, INT boost )
590 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
594 /**********************************************************************
595 * VWin32_BoostThreadStatic [KERNEL.536]
597 VOID WINAPI VWin32_BoostThreadStatic( DWORD threadId, INT boost )
599 FIXME("(0x%08lx,%d): stub\n", threadId, boost);
603 /***********************************************************************
604 * GetCurrentThread [KERNEL32.@] Gets pseudohandle for current thread
606 * RETURNS
607 * Pseudohandle for the current thread
609 #undef GetCurrentThread
610 HANDLE WINAPI GetCurrentThread(void)
612 return (HANDLE)0xfffffffe;
616 #ifdef __i386__
618 /***********************************************************************
619 * SetLastError (KERNEL.147)
620 * SetLastError (KERNEL32.@)
622 /* void WINAPI SetLastError( DWORD error ); */
623 __ASM_GLOBAL_FUNC( SetLastError,
624 "movl 4(%esp),%eax\n\t"
625 ".byte 0x64\n\t"
626 "movl %eax,0x60\n\t"
627 "ret $4" );
629 /***********************************************************************
630 * GetLastError (KERNEL.148)
631 * GetLastError (KERNEL32.@)
633 /* DWORD WINAPI GetLastError(void); */
634 __ASM_GLOBAL_FUNC( GetLastError, ".byte 0x64\n\tmovl 0x60,%eax\n\tret" );
636 /***********************************************************************
637 * GetCurrentProcessId (KERNEL.471)
638 * GetCurrentProcessId (KERNEL32.@)
640 /* DWORD WINAPI GetCurrentProcessId(void) */
641 __ASM_GLOBAL_FUNC( GetCurrentProcessId, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" );
643 /***********************************************************************
644 * GetCurrentThreadId (KERNEL.462)
645 * GetCurrentThreadId (KERNEL32.@)
647 /* DWORD WINAPI GetCurrentThreadId(void) */
648 __ASM_GLOBAL_FUNC( GetCurrentThreadId, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" );
650 #else /* __i386__ */
652 /**********************************************************************
653 * SetLastError (KERNEL.147)
654 * SetLastError (KERNEL32.@)
656 * Sets the last-error code.
658 void WINAPI SetLastError( DWORD error ) /* [in] Per-thread error code */
660 NtCurrentTeb()->last_error = error;
663 /**********************************************************************
664 * GetLastError (KERNEL.148)
665 * GetLastError (KERNEL32.@)
667 * Returns last-error code.
669 DWORD WINAPI GetLastError(void)
671 return NtCurrentTeb()->last_error;
674 /***********************************************************************
675 * GetCurrentProcessId (KERNEL.471)
676 * GetCurrentProcessId (KERNEL32.@)
678 * Returns process identifier.
680 DWORD WINAPI GetCurrentProcessId(void)
682 return (DWORD)NtCurrentTeb()->ClientId.UniqueProcess;
685 /***********************************************************************
686 * GetCurrentThreadId (KERNEL.462)
687 * GetCurrentThreadId (KERNEL32.@)
689 * Returns thread identifier.
691 DWORD WINAPI GetCurrentThreadId(void)
693 return (DWORD)NtCurrentTeb()->ClientId.UniqueThread;
696 #endif /* __i386__ */