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