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