Eliminated warnings.
[wine] / scheduler / thread.c
1 /*
2  * Win32 threads
3  *
4  * Copyright 1996 Alexandre Julliard
5  */
6
7 #include "config.h"
8
9 #include <assert.h>
10 #include <fcntl.h>
11 #include <sys/types.h>
12 #include <sys/socket.h>
13 #ifdef HAVE_SYS_MMAN_H
14 #include <sys/mman.h>
15 #endif
16 #include <unistd.h>
17 #include "wine/winbase16.h"
18 #include "thread.h"
19 #include "process.h"
20 #include "task.h"
21 #include "module.h"
22 #include "user.h"
23 #include "winerror.h"
24 #include "heap.h"
25 #include "selectors.h"
26 #include "winnt.h"
27 #include "server.h"
28 #include "services.h"
29 #include "stackframe.h"
30 #include "debugtools.h"
31 #include "queue.h"
32 #include "hook.h"
33
34 DEFAULT_DEBUG_CHANNEL(thread)
35
36 /* TEB of the initial thread */
37 static TEB initial_teb;
38
39 /* Global thread list (FIXME: not thread-safe) */
40 TEB *THREAD_First = &initial_teb;
41
42 /***********************************************************************
43  *           THREAD_IsWin16
44  */
45 BOOL THREAD_IsWin16( TEB *teb )
46 {
47     return !teb || !(teb->flags & TEBF_WIN32);
48 }
49
50 /***********************************************************************
51  *           THREAD_IdToTEB
52  *
53  * Convert a thread id to a TEB, making sure it is valid.
54  */
55 TEB *THREAD_IdToTEB( DWORD id )
56 {
57     TEB *teb = THREAD_First;
58
59     if (!id) return NtCurrentTeb();
60     while (teb)
61     {
62         if ((DWORD)teb->tid == id) return teb;
63         teb = teb->next;
64     }
65     /* Allow task handles to be used; convert to main thread */
66     if ( IsTask16( id ) )
67     {
68         TDB *pTask = (TDB *)GlobalLock16( id );
69         if (pTask) return pTask->teb;
70     }
71     SetLastError( ERROR_INVALID_PARAMETER );
72     return NULL;
73 }
74
75
76 /***********************************************************************
77  *           THREAD_InitTEB
78  *
79  * Initialization of a newly created TEB.
80  */
81 static BOOL THREAD_InitTEB( TEB *teb, DWORD stack_size, BOOL alloc_stack16,
82                             LPSECURITY_ATTRIBUTES sa )
83 {
84     DWORD old_prot;
85
86     /* Allocate the stack */
87
88     /* FIXME:
89      * If stacksize smaller than 1 MB, allocate 1MB 
90      * (one program wanted only 10 kB, which is recommendable, but some WINE
91      *  functions, noteably in the files subdir, push HUGE structures and
92      *  arrays on the stack. They probably shouldn't.)
93      * If stacksize larger than 16 MB, warn the user. (We could shrink the stack
94      * but this could give more or less unexplainable crashes.)
95      */
96     if (stack_size<1024*1024)
97         stack_size = 1024 * 1024;
98     if (stack_size >= 16*1024*1024)
99         WARN("Thread stack size is %ld MB.\n",stack_size/1024/1024);
100     teb->stack_base = VirtualAlloc(NULL, stack_size + SIGNAL_STACK_SIZE +
101                                    (alloc_stack16 ? 0x10000 : 0),
102                                    MEM_COMMIT, PAGE_EXECUTE_READWRITE );
103     if (!teb->stack_base) goto error;
104     /* Set a guard page at the bottom of the stack */
105     VirtualProtect( teb->stack_base, 1, PAGE_EXECUTE_READWRITE | PAGE_GUARD, &old_prot );
106     teb->stack_top    = (char *)teb->stack_base + stack_size;
107     teb->stack_low    = teb->stack_base;
108     teb->signal_stack = teb->stack_top;  /* start of signal stack */
109
110     /* Allocate the 16-bit stack selector */
111
112     if (alloc_stack16)
113     {
114         teb->stack_sel = SELECTOR_AllocBlock( teb->stack_top, 0x10000, SEGMENT_DATA,
115                                               FALSE, FALSE );
116         if (!teb->stack_sel) goto error;
117         teb->cur_stack = PTR_SEG_OFF_TO_SEGPTR( teb->stack_sel, 
118                                                 0x10000 - sizeof(STACK16FRAME) );
119         teb->signal_stack = (char *)teb->signal_stack + 0x10000;
120     }
121
122     /* Create the thread event */
123
124     if (!(teb->event = CreateEventA( NULL, FALSE, FALSE, NULL ))) goto error;
125     teb->event = ConvertToGlobalHandle( teb->event );
126     return TRUE;
127
128 error:
129     if (teb->event) CloseHandle( teb->event );
130     if (teb->stack_sel) SELECTOR_FreeBlock( teb->stack_sel, 1 );
131     if (teb->stack_base) VirtualFree( teb->stack_base, 0, MEM_RELEASE );
132     return FALSE;
133 }
134
135
136 /***********************************************************************
137  *           THREAD_FreeTEB
138  *
139  * Free data structures associated with a thread.
140  * Must be called from the context of another thread.
141  */
142 void CALLBACK THREAD_FreeTEB( ULONG_PTR arg )
143 {
144     TEB *teb = (TEB *)arg;
145     TEB **pptr = &THREAD_First;
146
147     TRACE("(%p) called\n", teb );
148     SERVICE_Delete( teb->cleanup );
149
150     PROCESS_CallUserSignalProc( USIG_THREAD_EXIT, 0 );
151     
152     CloseHandle( teb->event );
153     while (*pptr && (*pptr != teb)) pptr = &(*pptr)->next;
154     if (*pptr) *pptr = teb->next;
155
156     /* Free the associated memory */
157
158     if (teb->stack_sel) SELECTOR_FreeBlock( teb->stack_sel, 1 );
159     SELECTOR_FreeBlock( teb->teb_sel, 1 );
160     close( teb->socket );
161     if (teb->buffer) munmap( teb->buffer, teb->buffer_size );
162     VirtualFree( teb->stack_base, 0, MEM_RELEASE );
163     HeapFree( SystemHeap, 0, teb );
164 }
165
166
167 /***********************************************************************
168  *           THREAD_CreateInitialThread
169  *
170  * Create the initial thread.
171  */
172 TEB *THREAD_CreateInitialThread( PDB *pdb, int server_fd )
173 {
174     initial_teb.except      = (void *)-1;
175     initial_teb.self        = &initial_teb;
176     initial_teb.flags       = /* TEBF_WIN32 */ 0;
177     initial_teb.tls_ptr     = initial_teb.tls_array;
178     initial_teb.process     = pdb;
179     initial_teb.exit_code   = 0x103; /* STILL_ACTIVE */
180     initial_teb.socket      = server_fd;
181
182     /* Allocate the TEB selector (%fs register) */
183
184     if (!(initial_teb.teb_sel = SELECTOR_AllocBlock( &initial_teb, 0x1000,
185                                                      SEGMENT_DATA, TRUE, FALSE )))
186     {
187         MESSAGE("Could not allocate fs register for initial thread\n" );
188         return NULL;
189     }
190     SYSDEPS_SetCurThread( &initial_teb );
191
192     /* Now proceed with normal initialization */
193
194     if (CLIENT_InitThread()) return NULL;
195     if (!THREAD_InitTEB( &initial_teb, 0, TRUE, NULL )) return NULL;
196     return &initial_teb;
197 }
198
199
200 /***********************************************************************
201  *           THREAD_Create
202  */
203 TEB *THREAD_Create( PDB *pdb, DWORD flags, DWORD stack_size, BOOL alloc_stack16,
204                      LPSECURITY_ATTRIBUTES sa, int *server_handle )
205 {
206     struct new_thread_request *req = get_req_buffer();
207     int fd[2];
208     HANDLE cleanup_object;
209
210     TEB *teb = HeapAlloc( SystemHeap, HEAP_ZERO_MEMORY, sizeof(TEB) );
211     if (!teb) return NULL;
212     teb->except      = (void *)-1;
213     teb->htask16     = pdb->task;
214     teb->self        = teb;
215     teb->flags       = (pdb->flags & PDB32_WIN16_PROC)? 0 : TEBF_WIN32;
216     teb->tls_ptr     = teb->tls_array;
217     teb->process     = pdb;
218     teb->exit_code   = 0x103; /* STILL_ACTIVE */
219     teb->socket      = -1;
220
221     /* Allocate the TEB selector (%fs register) */
222
223     *server_handle = -1;
224     teb->teb_sel = SELECTOR_AllocBlock( teb, 0x1000, SEGMENT_DATA, TRUE, FALSE );
225     if (!teb->teb_sel) goto error;
226
227     /* Create the socket pair for server communication */
228
229     if (socketpair( AF_UNIX, SOCK_STREAM, 0, fd ) == -1)
230     {
231         SetLastError( ERROR_TOO_MANY_OPEN_FILES );  /* FIXME */
232         goto error;
233     }
234     teb->socket = fd[0];
235     fcntl( fd[0], F_SETFD, 1 ); /* set close on exec flag */
236
237     /* Create the thread on the server side */
238
239     req->pid     = teb->process->server_pid;
240     req->suspend = ((flags & CREATE_SUSPENDED) != 0);
241     req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
242     if (server_call_fd( REQ_NEW_THREAD, fd[1], NULL )) goto error;
243     teb->tid = req->tid;
244     *server_handle = req->handle;
245
246     /* Do the rest of the initialization */
247
248     if (!THREAD_InitTEB( teb, stack_size, alloc_stack16, sa )) goto error;
249     teb->next = THREAD_First;
250     THREAD_First = teb;
251
252     /* Install cleanup handler */
253     if ( !DuplicateHandle( GetCurrentProcess(), *server_handle, 
254                            GetCurrentProcess(), &cleanup_object, 
255                            0, FALSE, DUPLICATE_SAME_ACCESS ) ) goto error;
256     teb->cleanup = SERVICE_AddObject( cleanup_object, THREAD_FreeTEB, (ULONG_PTR)teb );
257
258     return teb;
259
260 error:
261     if (*server_handle != -1) CloseHandle( *server_handle );
262     if (teb->teb_sel) SELECTOR_FreeBlock( teb->teb_sel, 1 );
263     if (teb->socket != -1) close( teb->socket );
264     HeapFree( SystemHeap, 0, teb );
265     return NULL;
266 }
267
268
269 /***********************************************************************
270  *           THREAD_Start
271  *
272  * Start execution of a newly created thread. Does not return.
273  */
274 static void THREAD_Start(void)
275 {
276     LPTHREAD_START_ROUTINE func = (LPTHREAD_START_ROUTINE)NtCurrentTeb()->entry_point;
277     PROCESS_CallUserSignalProc( USIG_THREAD_INIT, 0 );
278     PE_InitTls();
279     MODULE_DllThreadAttach( NULL );
280
281     if (NtCurrentTeb()->process->flags & PDB32_DEBUGGED) DEBUG_SendCreateThreadEvent( func );
282
283     ExitThread( func( NtCurrentTeb()->entry_arg ) );
284 }
285
286
287 /***********************************************************************
288  *           CreateThread   (KERNEL32.63)
289  */
290 HANDLE WINAPI CreateThread( SECURITY_ATTRIBUTES *sa, DWORD stack,
291                             LPTHREAD_START_ROUTINE start, LPVOID param,
292                             DWORD flags, LPDWORD id )
293 {
294     int handle = -1;
295     TEB *teb = THREAD_Create( PROCESS_Current(), flags, stack, TRUE, sa, &handle );
296     if (!teb) return 0;
297     teb->flags      |= TEBF_WIN32;
298     teb->entry_point = start;
299     teb->entry_arg   = param;
300     teb->startup     = THREAD_Start;
301     if (SYSDEPS_SpawnThread( teb ) == -1)
302     {
303         CloseHandle( handle );
304         return 0;
305     }
306     if (id) *id = (DWORD)teb->tid;
307     return handle;
308 }
309
310
311 /***********************************************************************
312  * ExitThread [KERNEL32.215]  Ends a thread
313  *
314  * RETURNS
315  *    None
316  */
317 void WINAPI ExitThread( DWORD code ) /* [in] Exit code for this thread */
318 {
319     MODULE_DllThreadDetach( NULL );
320     TerminateThread( GetCurrentThread(), code );
321 }
322
323
324 /***********************************************************************
325  * GetCurrentThread [KERNEL32.200]  Gets pseudohandle for current thread
326  *
327  * RETURNS
328  *    Pseudohandle for the current thread
329  */
330 HANDLE WINAPI GetCurrentThread(void)
331 {
332     return CURRENT_THREAD_PSEUDOHANDLE;
333 }
334
335
336 /**********************************************************************
337  * GetLastError [KERNEL.148] [KERNEL32.227]  Returns last-error code.
338  *
339  * RETURNS
340  *     Calling thread's last error code value.
341  */
342 DWORD WINAPI GetLastError(void)
343 {
344     return NtCurrentTeb()->last_error;
345 }
346
347
348 /**********************************************************************
349  * SetLastErrorEx [USER32.485]  Sets the last-error code.
350  *
351  * RETURNS
352  *    None.
353  */
354 void WINAPI SetLastErrorEx(
355     DWORD error, /* [in] Per-thread error code */
356     DWORD type)  /* [in] Error type */
357 {
358     TRACE("(0x%08lx, 0x%08lx)\n", error,type);
359     switch(type) {
360         case 0:
361             break;
362         case SLE_ERROR:
363         case SLE_MINORERROR:
364         case SLE_WARNING:
365             /* Fall through for now */
366         default:
367             FIXME("(error=%08lx, type=%08lx): Unhandled type\n", error,type);
368             break;
369     }
370     SetLastError( error );
371 }
372
373
374 /**********************************************************************
375  * TlsAlloc [KERNEL32.530]  Allocates a TLS index.
376  *
377  * Allocates a thread local storage index
378  *
379  * RETURNS
380  *    Success: TLS Index
381  *    Failure: 0xFFFFFFFF
382  */
383 DWORD WINAPI TlsAlloc( void )
384 {
385     PDB *process = PROCESS_Current();
386     DWORD i, mask, ret = 0;
387     DWORD *bits = process->tls_bits;
388     EnterCriticalSection( &process->crit_section );
389     if (*bits == 0xffffffff)
390     {
391         bits++;
392         ret = 32;
393         if (*bits == 0xffffffff)
394         {
395             LeaveCriticalSection( &process->crit_section );
396             SetLastError( ERROR_NO_MORE_ITEMS );
397             return 0xffffffff;
398         }
399     }
400     for (i = 0, mask = 1; i < 32; i++, mask <<= 1) if (!(*bits & mask)) break;
401     *bits |= mask;
402     LeaveCriticalSection( &process->crit_section );
403     return ret + i;
404 }
405
406
407 /**********************************************************************
408  * TlsFree [KERNEL32.531]  Releases a TLS index.
409  *
410  * Releases a thread local storage index, making it available for reuse
411  * 
412  * RETURNS
413  *    Success: TRUE
414  *    Failure: FALSE
415  */
416 BOOL WINAPI TlsFree(
417     DWORD index) /* [in] TLS Index to free */
418 {
419     PDB *process = PROCESS_Current();
420     DWORD mask;
421     DWORD *bits = process->tls_bits;
422     if (index >= 64)
423     {
424         SetLastError( ERROR_INVALID_PARAMETER );
425         return FALSE;
426     }
427     EnterCriticalSection( &process->crit_section );
428     if (index >= 32) bits++;
429     mask = (1 << (index & 31));
430     if (!(*bits & mask))  /* already free? */
431     {
432         LeaveCriticalSection( &process->crit_section );
433         SetLastError( ERROR_INVALID_PARAMETER );
434         return FALSE;
435     }
436     *bits &= ~mask;
437     NtCurrentTeb()->tls_array[index] = 0;
438     /* FIXME: should zero all other thread values */
439     LeaveCriticalSection( &process->crit_section );
440     return TRUE;
441 }
442
443
444 /**********************************************************************
445  * TlsGetValue [KERNEL32.532]  Gets value in a thread's TLS slot
446  *
447  * RETURNS
448  *    Success: Value stored in calling thread's TLS slot for index
449  *    Failure: 0 and GetLastError returns NO_ERROR
450  */
451 LPVOID WINAPI TlsGetValue(
452     DWORD index) /* [in] TLS index to retrieve value for */
453 {
454     if (index >= 64)
455     {
456         SetLastError( ERROR_INVALID_PARAMETER );
457         return NULL;
458     }
459     SetLastError( ERROR_SUCCESS );
460     return NtCurrentTeb()->tls_array[index];
461 }
462
463
464 /**********************************************************************
465  * TlsSetValue [KERNEL32.533]  Stores a value in the thread's TLS slot.
466  *
467  * RETURNS
468  *    Success: TRUE
469  *    Failure: FALSE
470  */
471 BOOL WINAPI TlsSetValue(
472     DWORD index,  /* [in] TLS index to set value for */
473     LPVOID value) /* [in] Value to be stored */
474 {
475     if (index >= 64)
476     {
477         SetLastError( ERROR_INVALID_PARAMETER );
478         return FALSE;
479     }
480     NtCurrentTeb()->tls_array[index] = value;
481     return TRUE;
482 }
483
484
485 /***********************************************************************
486  * SetThreadContext [KERNEL32.670]  Sets context of thread.
487  *
488  * RETURNS
489  *    Success: TRUE
490  *    Failure: FALSE
491  */
492 BOOL WINAPI SetThreadContext(
493     HANDLE handle,  /* [in]  Handle to thread with context */
494     CONTEXT *context) /* [out] Address of context structure */
495 {
496     FIXME("not implemented\n" );
497     return TRUE;
498 }
499
500 /***********************************************************************
501  * GetThreadContext [KERNEL32.294]  Retrieves context of thread.
502  *
503  * RETURNS
504  *    Success: TRUE
505  *    Failure: FALSE
506  */
507 BOOL WINAPI GetThreadContext(
508     HANDLE handle,  /* [in]  Handle to thread with context */
509     CONTEXT *context) /* [out] Address of context structure */
510 {
511 #ifdef __i386__
512     WORD cs, ds;
513
514     FIXME("returning dummy info\n" );
515
516     /* make up some plausible values for segment registers */
517     GET_CS(cs);
518     GET_DS(ds);
519     context->SegCs   = cs;
520     context->SegDs   = ds;
521     context->SegEs   = ds;
522     context->SegGs   = ds;
523     context->SegSs   = ds;
524     context->SegFs   = ds;
525 #endif
526     return TRUE;
527 }
528
529
530 /**********************************************************************
531  * GetThreadPriority [KERNEL32.296]  Returns priority for thread.
532  *
533  * RETURNS
534  *    Success: Thread's priority level.
535  *    Failure: THREAD_PRIORITY_ERROR_RETURN
536  */
537 INT WINAPI GetThreadPriority(
538     HANDLE hthread) /* [in] Handle to thread */
539 {
540     INT ret = THREAD_PRIORITY_ERROR_RETURN;
541     struct get_thread_info_request *req = get_req_buffer();
542     req->handle = hthread;
543     if (!server_call( REQ_GET_THREAD_INFO )) ret = req->priority;
544     return ret;
545 }
546
547
548 /**********************************************************************
549  * SetThreadPriority [KERNEL32.514]  Sets priority for thread.
550  *
551  * RETURNS
552  *    Success: TRUE
553  *    Failure: FALSE
554  */
555 BOOL WINAPI SetThreadPriority(
556     HANDLE hthread, /* [in] Handle to thread */
557     INT priority)   /* [in] Thread priority level */
558 {
559     struct set_thread_info_request *req = get_req_buffer();
560     req->handle   = hthread;
561     req->priority = priority;
562     req->mask     = SET_THREAD_INFO_PRIORITY;
563     return !server_call( REQ_SET_THREAD_INFO );
564 }
565
566
567 /**********************************************************************
568  *           SetThreadAffinityMask   (KERNEL32.669)
569  */
570 DWORD WINAPI SetThreadAffinityMask( HANDLE hThread, DWORD dwThreadAffinityMask )
571 {
572     struct set_thread_info_request *req = get_req_buffer();
573     req->handle   = hThread;
574     req->affinity = dwThreadAffinityMask;
575     req->mask     = SET_THREAD_INFO_AFFINITY;
576     if (server_call( REQ_SET_THREAD_INFO )) return 0;
577     return 1;  /* FIXME: should return previous value */
578 }
579
580
581 /**********************************************************************
582  * TerminateThread [KERNEL32.685]  Terminates a thread
583  *
584  * RETURNS
585  *    Success: TRUE
586  *    Failure: FALSE
587  */
588 BOOL WINAPI TerminateThread(
589     HANDLE handle, /* [in] Handle to thread */
590     DWORD exitcode)  /* [in] Exit code for thread */
591 {
592     struct terminate_thread_request *req = get_req_buffer();
593     req->handle    = handle;
594     req->exit_code = exitcode;
595     return !server_call( REQ_TERMINATE_THREAD );
596 }
597
598
599 /**********************************************************************
600  * GetExitCodeThread [KERNEL32.???]  Gets termination status of thread.
601  * 
602  * RETURNS
603  *    Success: TRUE
604  *    Failure: FALSE
605  */
606 BOOL WINAPI GetExitCodeThread(
607     HANDLE hthread, /* [in]  Handle to thread */
608     LPDWORD exitcode) /* [out] Address to receive termination status */
609 {
610     BOOL ret = FALSE;
611     struct get_thread_info_request *req = get_req_buffer();
612     req->handle = hthread;
613     if (!server_call( REQ_GET_THREAD_INFO ))
614     {
615         if (exitcode) *exitcode = req->exit_code;
616         ret = TRUE;
617     }
618     return ret;
619 }
620
621
622 /**********************************************************************
623  * ResumeThread [KERNEL32.587]  Resumes a thread.
624  *
625  * Decrements a thread's suspend count.  When count is zero, the
626  * execution of the thread is resumed.
627  *
628  * RETURNS
629  *    Success: Previous suspend count
630  *    Failure: 0xFFFFFFFF
631  *    Already running: 0
632  */
633 DWORD WINAPI ResumeThread(
634     HANDLE hthread) /* [in] Identifies thread to restart */
635 {
636     DWORD ret = 0xffffffff;
637     struct resume_thread_request *req = get_req_buffer();
638     req->handle = hthread;
639     if (!server_call( REQ_RESUME_THREAD )) ret = req->count;
640     return ret;
641 }
642
643
644 /**********************************************************************
645  * SuspendThread [KERNEL32.681]  Suspends a thread.
646  *
647  * RETURNS
648  *    Success: Previous suspend count
649  *    Failure: 0xFFFFFFFF
650  */
651 DWORD WINAPI SuspendThread(
652     HANDLE hthread) /* [in] Handle to the thread */
653 {
654     DWORD ret = 0xffffffff;
655     struct suspend_thread_request *req = get_req_buffer();
656     req->handle = hthread;
657     if (!server_call( REQ_SUSPEND_THREAD )) ret = req->count;
658     return ret;
659 }
660
661
662 /***********************************************************************
663  *              QueueUserAPC  (KERNEL32.566)
664  */
665 DWORD WINAPI QueueUserAPC( PAPCFUNC func, HANDLE hthread, ULONG_PTR data )
666 {
667     struct queue_apc_request *req = get_req_buffer();
668     req->handle = hthread;
669     req->func   = func;
670     req->param  = (void *)data;
671     return !server_call( REQ_QUEUE_APC );
672 }
673
674
675 /**********************************************************************
676  * GetThreadTimes [KERNEL32.???]  Obtains timing information.
677  *
678  * NOTES
679  *    What are the fields where these values are stored?
680  *
681  * RETURNS
682  *    Success: TRUE
683  *    Failure: FALSE
684  */
685 BOOL WINAPI GetThreadTimes( 
686     HANDLE thread,         /* [in]  Specifies the thread of interest */
687     LPFILETIME creationtime, /* [out] When the thread was created */
688     LPFILETIME exittime,     /* [out] When the thread was destroyed */
689     LPFILETIME kerneltime,   /* [out] Time thread spent in kernel mode */
690     LPFILETIME usertime)     /* [out] Time thread spent in user mode */
691 {
692     FIXME("(0x%08x): stub\n",thread);
693     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
694     return FALSE;
695 }
696
697
698 /**********************************************************************
699  * AttachThreadInput [KERNEL32.8]  Attaches input of 1 thread to other
700  *
701  * Attaches the input processing mechanism of one thread to that of
702  * another thread.
703  *
704  * RETURNS
705  *    Success: TRUE
706  *    Failure: FALSE
707  *
708  * TODO:
709  *    1. Reset the Key State (currenly per thread key state is not maintained)
710  */
711 BOOL WINAPI AttachThreadInput( 
712     DWORD idAttach,   /* [in] Thread to attach */
713     DWORD idAttachTo, /* [in] Thread to attach to */
714     BOOL fAttach)   /* [in] Attach or detach */
715 {
716     MESSAGEQUEUE *pSrcMsgQ = 0, *pTgtMsgQ = 0;
717     BOOL16 bRet = 0;
718
719     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
720
721     /* A thread cannot attach to itself */
722     if ( idAttach == idAttachTo )
723         goto CLEANUP;
724
725     /* According to the docs this method should fail if a
726      * "Journal record" hook is installed. (attaches all input queues together)
727      */
728     if ( HOOK_IsHooked( WH_JOURNALRECORD ) )
729         goto CLEANUP;
730         
731     /* Retrieve message queues corresponding to the thread id's */
732     pTgtMsgQ = (MESSAGEQUEUE *)QUEUE_Lock( GetThreadQueue16( idAttach ) );
733     pSrcMsgQ = (MESSAGEQUEUE *)QUEUE_Lock( GetThreadQueue16( idAttachTo ) );
734
735     /* Ensure we have message queues and that Src and Tgt threads
736      * are not system threads.
737      */
738     if ( !pSrcMsgQ || !pTgtMsgQ || !pSrcMsgQ->pQData || !pTgtMsgQ->pQData )
739         goto CLEANUP;
740
741     if (fAttach)   /* Attach threads */
742     {
743         /* Only attach if currently detached  */
744         if ( pTgtMsgQ->pQData != pSrcMsgQ->pQData )
745         {
746             /* First release the target threads perQData */
747             PERQDATA_Release( pTgtMsgQ->pQData );
748         
749             /* Share a reference to the source threads perQDATA */
750             PERQDATA_Addref( pSrcMsgQ->pQData );
751             pTgtMsgQ->pQData = pSrcMsgQ->pQData;
752         }
753     }
754     else    /* Detach threads */
755     {
756         /* Only detach if currently attached */
757         if ( pTgtMsgQ->pQData == pSrcMsgQ->pQData )
758         {
759             /* First release the target threads perQData */
760             PERQDATA_Release( pTgtMsgQ->pQData );
761         
762             /* Give the target thread its own private perQDATA once more */
763             pTgtMsgQ->pQData = PERQDATA_CreateInstance();
764         }
765     }
766
767     /* TODO: Reset the Key State */
768
769     bRet = 1;      /* Success */
770     
771 CLEANUP:
772
773     /* Unlock the queues before returning */
774     if ( pSrcMsgQ )
775         QUEUE_Unlock( pSrcMsgQ );
776     if ( pTgtMsgQ )
777         QUEUE_Unlock( pTgtMsgQ );
778     
779     return bRet;
780 }
781
782 /**********************************************************************
783  * VWin32_BoostThreadGroup [KERNEL.535]
784  */
785 VOID WINAPI VWin32_BoostThreadGroup( DWORD threadId, INT boost )
786 {
787     FIXME("(0x%08lx,%d): stub\n", threadId, boost);
788 }
789
790 /**********************************************************************
791  * VWin32_BoostThreadStatic [KERNEL.536]
792  */
793 VOID WINAPI VWin32_BoostThreadStatic( DWORD threadId, INT boost )
794 {
795     FIXME("(0x%08lx,%d): stub\n", threadId, boost);
796 }
797
798 /**********************************************************************
799  * SetThreadLocale [KERNEL32.671]  Sets the calling threads current locale.
800  *
801  * RETURNS
802  *    Success: TRUE
803  *    Failure: FALSE
804  *
805  * NOTES
806  *  Implemented in NT only (3.1 and above according to MS
807  */
808 BOOL WINAPI SetThreadLocale(
809     LCID lcid)     /* [in] Locale identifier */
810 {
811     SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
812     return FALSE;
813 }
814
815
816 /**********************************************************************
817  * SetLastError [KERNEL.147] [KERNEL32.497]  Sets the last-error code.
818  *
819  * RETURNS
820  *    None.
821  */
822 #undef SetLastError
823 void WINAPI SetLastError( DWORD error ) /* [in] Per-thread error code */
824 {
825     NtCurrentTeb()->last_error = error;
826 }
827
828
829 /***********************************************************************
830  * GetCurrentThreadId [KERNEL32.201]  Returns thread identifier.
831  *
832  * RETURNS
833  *    Thread identifier of calling thread
834  */
835 #undef GetCurrentThreadId
836 DWORD WINAPI GetCurrentThreadId(void)
837 {
838     return (DWORD)NtCurrentTeb()->tid;
839 }