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