Avoid killing threads with TerminateThread, this can cause deadlocks.
[wine] / dlls / kernel / thread.c
1 /*
2  * Win32 threads
3  *
4  * Copyright 1996 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
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
35
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/exception.h"
45 #include "wine/library.h"
46 #include "wine/pthread.h"
47 #include "wine/server.h"
48 #include "wine/debug.h"
49
50 WINE_DEFAULT_DEBUG_CHANNEL(thread);
51 WINE_DECLARE_DEBUG_CHANNEL(relay);
52
53
54 /***********************************************************************
55  *           THREAD_InitStack
56  *
57  * Allocate the stack of a thread.
58  */
59 TEB *THREAD_InitStack( TEB *teb, DWORD stack_size )
60 {
61     DWORD old_prot;
62     DWORD page_size = getpagesize();
63     void *base;
64
65     stack_size = (stack_size + (page_size - 1)) & ~(page_size - 1);
66     if (stack_size < 1024 * 1024) stack_size = 1024 * 1024;  /* Xlib needs a large stack */
67
68     if (!(base = VirtualAlloc( NULL, stack_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE )))
69         return NULL;
70
71     teb->DeallocationStack = base;
72     teb->Tib.StackBase     = (char *)base + stack_size;
73     teb->Tib.StackLimit    = base;  /* note: limit is lower than base since the stack grows down */
74
75     /* Setup guard pages */
76
77     VirtualProtect( base, 1, PAGE_EXECUTE_READWRITE | PAGE_GUARD, &old_prot );
78     return teb;
79 }
80
81
82 struct new_thread_info
83 {
84     LPTHREAD_START_ROUTINE func;
85     void                  *arg;
86 };
87
88 /***********************************************************************
89  *           THREAD_Start
90  *
91  * Start execution of a newly created thread. Does not return.
92  */
93 static void CALLBACK THREAD_Start( void *ptr )
94 {
95     struct new_thread_info *info = ptr;
96     LPTHREAD_START_ROUTINE func = info->func;
97     void *arg = info->arg;
98
99     RtlFreeHeap( GetProcessHeap(), 0, info );
100
101     if (TRACE_ON(relay))
102         DPRINTF("%04lx:Starting thread (entryproc=%p)\n", GetCurrentThreadId(), func );
103
104     __TRY
105     {
106         MODULE_DllThreadAttach( NULL );
107         ExitThread( func( arg ) );
108     }
109     __EXCEPT(UnhandledExceptionFilter)
110     {
111         TerminateThread( GetCurrentThread(), GetExceptionCode() );
112     }
113     __ENDTRY
114 }
115
116
117 /***********************************************************************
118  *           CreateThread   (KERNEL32.@)
119  */
120 HANDLE WINAPI CreateThread( SECURITY_ATTRIBUTES *sa, SIZE_T stack,
121                             LPTHREAD_START_ROUTINE start, LPVOID param,
122                             DWORD flags, LPDWORD id )
123 {
124     HANDLE handle;
125     CLIENT_ID client_id;
126     NTSTATUS status;
127     SIZE_T stack_reserve = 0, stack_commit = 0;
128     struct new_thread_info *info;
129
130     if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*info) )))
131     {
132         SetLastError( ERROR_NOT_ENOUGH_MEMORY );
133         return 0;
134     }
135     info->func = start;
136     info->arg  = param;
137
138     if (flags & STACK_SIZE_PARAM_IS_A_RESERVATION) stack_reserve = stack;
139     else stack_commit = stack;
140
141     status = RtlCreateUserThread( GetCurrentProcess(), NULL, (flags & CREATE_SUSPENDED) != 0,
142                                   NULL, stack_reserve, stack_commit,
143                                   THREAD_Start, info, &handle, &client_id );
144     if (status == STATUS_SUCCESS)
145     {
146         if (id) *id = (DWORD)client_id.UniqueThread;
147         if (sa && (sa->nLength >= sizeof(*sa)) && sa->bInheritHandle)
148             SetHandleInformation( handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT );
149     }
150     else
151     {
152         RtlFreeHeap( GetProcessHeap(), 0, info );
153         SetLastError( RtlNtStatusToDosError(status) );
154         handle = 0;
155     }
156     return handle;
157 }
158
159
160 /***********************************************************************
161  * OpenThread  [KERNEL32.@]   Retrieves a handle to a thread from its thread id
162  */
163 HANDLE WINAPI OpenThread( DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId )
164 {
165     HANDLE ret = 0;
166     SERVER_START_REQ( open_thread )
167     {
168         req->tid     = dwThreadId;
169         req->access  = dwDesiredAccess;
170         req->inherit = bInheritHandle;
171         if (!wine_server_call_err( req )) ret = reply->handle;
172     }
173     SERVER_END_REQ;
174     return ret;
175 }
176
177
178 /***********************************************************************
179  * ExitThread [KERNEL32.@]  Ends a thread
180  *
181  * RETURNS
182  *    None
183  */
184 void WINAPI ExitThread( DWORD code ) /* [in] Exit code for this thread */
185 {
186     BOOL last;
187     SERVER_START_REQ( terminate_thread )
188     {
189         /* send the exit code to the server */
190         req->handle    = GetCurrentThread();
191         req->exit_code = code;
192         wine_server_call( req );
193         last = reply->last;
194     }
195     SERVER_END_REQ;
196
197     if (last)
198     {
199         LdrShutdownProcess();
200         exit( code );
201     }
202     else
203     {
204         struct wine_pthread_thread_info info;
205         sigset_t block_set;
206         ULONG size;
207
208         LdrShutdownThread();
209         RtlAcquirePebLock();
210         RemoveEntryList( &NtCurrentTeb()->TlsLinks );
211         RtlReleasePebLock();
212
213         info.stack_base  = NtCurrentTeb()->DeallocationStack;
214         info.teb_base    = NtCurrentTeb();
215         info.teb_sel     = wine_get_fs();
216         info.exit_status = code;
217
218         size = 0;
219         NtFreeVirtualMemory( GetCurrentProcess(), &info.stack_base, &size, MEM_RELEASE | MEM_SYSTEM );
220         info.stack_size = size;
221
222         size = 0;
223         NtFreeVirtualMemory( GetCurrentProcess(), &info.teb_base, &size, MEM_RELEASE | MEM_SYSTEM );
224         info.teb_size = size;
225
226         /* block the async signals */
227         sigemptyset( &block_set );
228         sigaddset( &block_set, SIGALRM );
229         sigaddset( &block_set, SIGIO );
230         sigaddset( &block_set, SIGINT );
231         sigaddset( &block_set, SIGHUP );
232         sigaddset( &block_set, SIGUSR1 );
233         sigaddset( &block_set, SIGUSR2 );
234         sigaddset( &block_set, SIGTERM );
235         sigprocmask( SIG_BLOCK, &block_set, NULL );
236
237         close( NtCurrentTeb()->wait_fd[0] );
238         close( NtCurrentTeb()->wait_fd[1] );
239         close( NtCurrentTeb()->reply_fd );
240         close( NtCurrentTeb()->request_fd );
241
242         wine_pthread_exit_thread( &info );
243     }
244 }
245
246
247 /**********************************************************************
248  * TerminateThread [KERNEL32.@]  Terminates a thread
249  *
250  * RETURNS
251  *    Success: TRUE
252  *    Failure: FALSE
253  */
254 BOOL WINAPI TerminateThread( HANDLE handle,    /* [in] Handle to thread */
255                              DWORD exit_code)  /* [in] Exit code for thread */
256 {
257     NTSTATUS status = NtTerminateThread( handle, exit_code );
258     if (status) SetLastError( RtlNtStatusToDosError(status) );
259     return !status;
260 }
261
262
263 /***********************************************************************
264  *           FreeLibraryAndExitThread (KERNEL32.@)
265  */
266 void WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
267 {
268     FreeLibrary(hLibModule);
269     ExitThread(dwExitCode);
270 }
271
272
273 /**********************************************************************
274  *              GetExitCodeThread (KERNEL32.@)
275  *
276  * Gets termination status of thread.
277  *
278  * RETURNS
279  *    Success: TRUE
280  *    Failure: FALSE
281  */
282 BOOL WINAPI GetExitCodeThread(
283     HANDLE hthread, /* [in]  Handle to thread */
284     LPDWORD exitcode) /* [out] Address to receive termination status */
285 {
286     THREAD_BASIC_INFORMATION info;
287     NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
288                                                 &info, sizeof(info), NULL );
289
290     if (status)
291     {
292         SetLastError( RtlNtStatusToDosError(status) );
293         return FALSE;
294     }
295     if (exitcode) *exitcode = info.ExitStatus;
296     return TRUE;
297 }
298
299
300 /***********************************************************************
301  * SetThreadContext [KERNEL32.@]  Sets context of thread.
302  *
303  * RETURNS
304  *    Success: TRUE
305  *    Failure: FALSE
306  */
307 BOOL WINAPI SetThreadContext( HANDLE handle,           /* [in]  Handle to thread with context */
308                               const CONTEXT *context ) /* [in] Address of context structure */
309 {
310     NTSTATUS status = NtSetContextThread( handle, context );
311     if (status) SetLastError( RtlNtStatusToDosError(status) );
312     return !status;
313 }
314
315
316 /***********************************************************************
317  * GetThreadContext [KERNEL32.@]  Retrieves context of thread.
318  *
319  * RETURNS
320  *    Success: TRUE
321  *    Failure: FALSE
322  */
323 BOOL WINAPI GetThreadContext( HANDLE handle,     /* [in]  Handle to thread with context */
324                               CONTEXT *context ) /* [out] Address of context structure */
325 {
326     NTSTATUS status = NtGetContextThread( handle, context );
327     if (status) SetLastError( RtlNtStatusToDosError(status) );
328     return !status;
329 }
330
331
332 /**********************************************************************
333  * SuspendThread [KERNEL32.@]  Suspends a thread.
334  *
335  * RETURNS
336  *    Success: Previous suspend count
337  *    Failure: 0xFFFFFFFF
338  */
339 DWORD WINAPI SuspendThread( HANDLE hthread ) /* [in] Handle to the thread */
340 {
341     DWORD ret;
342     NTSTATUS status = NtSuspendThread( hthread, &ret );
343
344     if (status)
345     {
346         ret = ~0U;
347         SetLastError( RtlNtStatusToDosError(status) );
348     }
349     return ret;
350 }
351
352
353 /**********************************************************************
354  * ResumeThread [KERNEL32.@]  Resumes a thread.
355  *
356  * Decrements a thread's suspend count.  When count is zero, the
357  * execution of the thread is resumed.
358  *
359  * RETURNS
360  *    Success: Previous suspend count
361  *    Failure: 0xFFFFFFFF
362  *    Already running: 0
363  */
364 DWORD WINAPI ResumeThread( HANDLE hthread ) /* [in] Identifies thread to restart */
365 {
366     DWORD ret;
367     NTSTATUS status = NtResumeThread( hthread, &ret );
368
369     if (status)
370     {
371         ret = ~0U;
372         SetLastError( RtlNtStatusToDosError(status) );
373     }
374     return ret;
375 }
376
377
378 /**********************************************************************
379  * GetThreadPriority [KERNEL32.@]  Returns priority for thread.
380  *
381  * RETURNS
382  *    Success: Thread's priority level.
383  *    Failure: THREAD_PRIORITY_ERROR_RETURN
384  */
385 INT WINAPI GetThreadPriority(
386     HANDLE hthread) /* [in] Handle to thread */
387 {
388     THREAD_BASIC_INFORMATION info;
389     NTSTATUS status = NtQueryInformationThread( hthread, ThreadBasicInformation,
390                                                 &info, sizeof(info), NULL );
391
392     if (status)
393     {
394         SetLastError( RtlNtStatusToDosError(status) );
395         return THREAD_PRIORITY_ERROR_RETURN;
396     }
397     return info.Priority;
398 }
399
400
401 /**********************************************************************
402  * SetThreadPriority [KERNEL32.@]  Sets priority for thread.
403  *
404  * RETURNS
405  *    Success: TRUE
406  *    Failure: FALSE
407  */
408 BOOL WINAPI SetThreadPriority(
409     HANDLE hthread, /* [in] Handle to thread */
410     INT priority)   /* [in] Thread priority level */
411 {
412     BOOL ret;
413     SERVER_START_REQ( set_thread_info )
414     {
415         req->handle   = hthread;
416         req->priority = priority;
417         req->mask     = SET_THREAD_INFO_PRIORITY;
418         ret = !wine_server_call_err( req );
419     }
420     SERVER_END_REQ;
421     return ret;
422 }
423
424
425 /**********************************************************************
426  * GetThreadPriorityBoost [KERNEL32.@]  Returns priority boost for thread.
427  *
428  * Always reports that priority boost is disabled.
429  *
430  * RETURNS
431  *    Success: TRUE.
432  *    Failure: FALSE
433  */
434 BOOL WINAPI GetThreadPriorityBoost(
435     HANDLE hthread, /* [in] Handle to thread */
436     PBOOL pstate)   /* [out] pointer to var that receives the boost state */
437 {
438     if (pstate) *pstate = FALSE;
439     return NO_ERROR;
440 }
441
442
443 /**********************************************************************
444  * SetThreadPriorityBoost [KERNEL32.@]  Sets priority boost for thread.
445  *
446  * Priority boost is not implemented. Thsi function always returns
447  * FALSE and sets last error to ERROR_CALL_NOT_IMPLEMENTED
448  *
449  * RETURNS
450  *    Always returns FALSE to indicate a failure
451  */
452 BOOL WINAPI SetThreadPriorityBoost(
453     HANDLE hthread, /* [in] Handle to thread */
454     BOOL disable)   /* [in] TRUE to disable priority boost */
455 {
456     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
457     return FALSE;
458 }
459
460
461 /**********************************************************************
462  *           SetThreadAffinityMask   (KERNEL32.@)
463  */
464 DWORD WINAPI SetThreadAffinityMask( HANDLE hThread, DWORD dwThreadAffinityMask )
465 {
466     DWORD ret;
467     SERVER_START_REQ( set_thread_info )
468     {
469         req->handle   = hThread;
470         req->affinity = dwThreadAffinityMask;
471         req->mask     = SET_THREAD_INFO_AFFINITY;
472         ret = !wine_server_call_err( req );
473         /* FIXME: should return previous value */
474     }
475     SERVER_END_REQ;
476     return ret;
477 }
478
479
480 /**********************************************************************
481  * SetThreadIdealProcessor [KERNEL32.@]  Obtains timing information.
482  *
483  * RETURNS
484  *    Success: Value of last call to SetThreadIdealProcessor
485  *    Failure: -1
486  */
487 DWORD WINAPI SetThreadIdealProcessor(
488     HANDLE hThread,          /* [in] Specifies the thread of interest */
489     DWORD dwIdealProcessor)  /* [in] Specifies the new preferred processor */
490 {
491     FIXME("(%p): stub\n",hThread);
492     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
493     return -1L;
494 }
495
496
497 /* callback for QueueUserAPC */
498 static void CALLBACK call_user_apc( ULONG_PTR arg1, ULONG_PTR arg2, ULONG_PTR arg3 )
499 {
500     PAPCFUNC func = (PAPCFUNC)arg1;
501     func( arg2 );
502 }
503
504 /***********************************************************************
505  *              QueueUserAPC  (KERNEL32.@)
506  */
507 DWORD WINAPI QueueUserAPC( PAPCFUNC func, HANDLE hthread, ULONG_PTR data )
508 {
509     NTSTATUS status = NtQueueApcThread( hthread, call_user_apc, (ULONG_PTR)func, data, 0 );
510
511     if (status) SetLastError( RtlNtStatusToDosError(status) );
512     return !status;
513 }
514
515
516 /**********************************************************************
517  * GetThreadTimes [KERNEL32.@]  Obtains timing information.
518  *
519  * RETURNS
520  *    Success: TRUE
521  *    Failure: FALSE
522  */
523 BOOL WINAPI GetThreadTimes(
524     HANDLE thread,         /* [in]  Specifies the thread of interest */
525     LPFILETIME creationtime, /* [out] When the thread was created */
526     LPFILETIME exittime,     /* [out] When the thread was destroyed */
527     LPFILETIME kerneltime,   /* [out] Time thread spent in kernel mode */
528     LPFILETIME usertime)     /* [out] Time thread spent in user mode */
529 {
530     BOOL ret = TRUE;
531
532     if (creationtime || exittime)
533     {
534         /* We need to do a server call to get the creation time or exit time */
535         /* This works on any thread */
536
537         SERVER_START_REQ( get_thread_info )
538         {
539             req->handle = thread;
540             req->tid_in = 0;
541             if ((ret = !wine_server_call_err( req )))
542             {
543                 if (creationtime)
544                     RtlSecondsSince1970ToTime( reply->creation_time, (LARGE_INTEGER*)creationtime );
545                 if (exittime)
546                     RtlSecondsSince1970ToTime( reply->exit_time, (LARGE_INTEGER*)exittime );
547             }
548         }
549         SERVER_END_REQ;
550     }
551     if (ret && (kerneltime || usertime))
552     {
553         /* We call times(2) for kernel time or user time */
554         /* We can only (portably) do this for the current thread */
555         if (thread == GetCurrentThread())
556         {
557             ULONGLONG time;
558             struct tms time_buf;
559             long clocks_per_sec = sysconf(_SC_CLK_TCK);
560
561             times(&time_buf);
562             if (kerneltime)
563             {
564                 time = (ULONGLONG)time_buf.tms_stime * 10000000 / clocks_per_sec;
565                 kerneltime->dwHighDateTime = time >> 32;
566                 kerneltime->dwLowDateTime = (DWORD)time;
567             }
568             if (usertime)
569             {
570                 time = (ULONGLONG)time_buf.tms_utime * 10000000 / clocks_per_sec;
571                 usertime->dwHighDateTime = time >> 32;
572                 usertime->dwLowDateTime = (DWORD)time;
573             }
574         }
575         else
576         {
577             if (kerneltime) kerneltime->dwHighDateTime = kerneltime->dwLowDateTime = 0;
578             if (usertime) usertime->dwHighDateTime = usertime->dwLowDateTime = 0;
579             FIXME("Cannot get kerneltime or usertime of other threads\n");
580         }
581     }
582     return ret;
583 }
584
585
586 /**********************************************************************
587  * VWin32_BoostThreadGroup [KERNEL.535]
588  */
589 VOID WINAPI VWin32_BoostThreadGroup( DWORD threadId, INT boost )
590 {
591     FIXME("(0x%08lx,%d): stub\n", threadId, boost);
592 }
593
594
595 /**********************************************************************
596  * VWin32_BoostThreadStatic [KERNEL.536]
597  */
598 VOID WINAPI VWin32_BoostThreadStatic( DWORD threadId, INT boost )
599 {
600     FIXME("(0x%08lx,%d): stub\n", threadId, boost);
601 }
602
603
604 /***********************************************************************
605  * GetCurrentThread [KERNEL32.@]  Gets pseudohandle for current thread
606  *
607  * RETURNS
608  *    Pseudohandle for the current thread
609  */
610 #undef GetCurrentThread
611 HANDLE WINAPI GetCurrentThread(void)
612 {
613     return (HANDLE)0xfffffffe;
614 }
615
616
617 #ifdef __i386__
618
619 /***********************************************************************
620  *              SetLastError (KERNEL.147)
621  *              SetLastError (KERNEL32.@)
622  */
623 /* void WINAPI SetLastError( DWORD error ); */
624 __ASM_GLOBAL_FUNC( SetLastError,
625                    "movl 4(%esp),%eax\n\t"
626                    ".byte 0x64\n\t"
627                    "movl %eax,0x34\n\t"
628                    "ret $4" );
629
630 /***********************************************************************
631  *              GetLastError (KERNEL.148)
632  *              GetLastError (KERNEL32.@)
633  */
634 /* DWORD WINAPI GetLastError(void); */
635 __ASM_GLOBAL_FUNC( GetLastError, ".byte 0x64\n\tmovl 0x34,%eax\n\tret" );
636
637 /***********************************************************************
638  *              GetCurrentProcessId (KERNEL.471)
639  *              GetCurrentProcessId (KERNEL32.@)
640  */
641 /* DWORD WINAPI GetCurrentProcessId(void) */
642 __ASM_GLOBAL_FUNC( GetCurrentProcessId, ".byte 0x64\n\tmovl 0x20,%eax\n\tret" );
643
644 /***********************************************************************
645  *              GetCurrentThreadId (KERNEL.462)
646  *              GetCurrentThreadId (KERNEL32.@)
647  */
648 /* DWORD WINAPI GetCurrentThreadId(void) */
649 __ASM_GLOBAL_FUNC( GetCurrentThreadId, ".byte 0x64\n\tmovl 0x24,%eax\n\tret" );
650
651 #else  /* __i386__ */
652
653 /**********************************************************************
654  *              SetLastError (KERNEL.147)
655  *              SetLastError (KERNEL32.@)
656  *
657  * Sets the last-error code.
658  */
659 void WINAPI SetLastError( DWORD error ) /* [in] Per-thread error code */
660 {
661     NtCurrentTeb()->LastErrorValue = error;
662 }
663
664 /**********************************************************************
665  *              GetLastError (KERNEL.148)
666  *              GetLastError (KERNEL32.@)
667  *
668  * Returns last-error code.
669  */
670 DWORD WINAPI GetLastError(void)
671 {
672     return NtCurrentTeb()->LastErrorValue;
673 }
674
675 /***********************************************************************
676  *              GetCurrentProcessId (KERNEL.471)
677  *              GetCurrentProcessId (KERNEL32.@)
678  *
679  * Returns process identifier.
680  */
681 DWORD WINAPI GetCurrentProcessId(void)
682 {
683     return (DWORD)NtCurrentTeb()->ClientId.UniqueProcess;
684 }
685
686 /***********************************************************************
687  *              GetCurrentThreadId (KERNEL.462)
688  *              GetCurrentThreadId (KERNEL32.@)
689  *
690  * Returns thread identifier.
691  */
692 DWORD WINAPI GetCurrentThreadId(void)
693 {
694     return (DWORD)NtCurrentTeb()->ClientId.UniqueThread;
695 }
696
697 #endif  /* __i386__ */