We need to give room for the null termination when translating the
[wine] / server / thread.c
1 /*
2  * Server-side thread management
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  */
6
7 #include "config.h"
8
9 #include <assert.h>
10 #include <fcntl.h>
11 #include <signal.h>
12 #include <stdarg.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #ifdef HAVE_SYS_MMAN_H
17 #include <sys/mman.h>
18 #endif
19 #include <sys/types.h>
20 #ifdef HAVE_SYS_SOCKET_H
21 # include <sys/socket.h>
22 #endif
23 #include <sys/uio.h>
24 #include <unistd.h>
25 #include <stdarg.h>
26
27 #include "winbase.h"
28
29 #include "handle.h"
30 #include "process.h"
31 #include "thread.h"
32 #include "request.h"
33
34
35 /* thread queues */
36
37 struct thread_wait
38 {
39     int                     count;      /* count of objects */
40     int                     flags;
41     struct timeval          timeout;
42     struct timeout_user    *user;
43     sleep_reply             reply;      /* function to build the reply */
44     struct wait_queue_entry queues[1];
45 };
46
47 /* asynchronous procedure calls */
48
49 struct thread_apc
50 {
51     struct thread_apc  *next;     /* queue linked list */
52     struct thread_apc  *prev;
53     struct object      *owner;    /* object that queued this apc */
54     void               *func;     /* function to call in client */
55     enum apc_type       type;     /* type of apc function */
56     int                 nb_args;  /* number of arguments */
57     void               *args[1];  /* function arguments */
58 };
59
60
61 /* thread operations */
62
63 static void dump_thread( struct object *obj, int verbose );
64 static int thread_signaled( struct object *obj, struct thread *thread );
65 extern void thread_poll_event( struct object *obj, int event );
66 static void destroy_thread( struct object *obj );
67 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only );
68
69 static const struct object_ops thread_ops =
70 {
71     sizeof(struct thread),      /* size */
72     dump_thread,                /* dump */
73     add_queue,                  /* add_queue */
74     remove_queue,               /* remove_queue */
75     thread_signaled,            /* signaled */
76     no_satisfied,               /* satisfied */
77     NULL,                       /* get_poll_events */
78     thread_poll_event,          /* poll_event */
79     no_get_fd,                  /* get_fd */
80     no_flush,                   /* flush */
81     no_get_file_info,           /* get_file_info */
82     destroy_thread              /* destroy */
83 };
84
85 static struct thread *first_thread;
86 static struct thread *booting_thread;
87
88 /* allocate the buffer for the communication with the client */
89 static int alloc_client_buffer( struct thread *thread )
90 {
91     struct get_thread_buffer_request *req;
92     int fd, fd_pipe[2];
93
94     if (pipe( fd_pipe ) == -1)
95     {
96         file_set_error();
97         return 0;
98     }
99     if ((fd = create_anonymous_file()) == -1) goto error;
100     if (ftruncate( fd, MAX_REQUEST_LENGTH ) == -1) goto error;
101     if ((thread->buffer = mmap( 0, MAX_REQUEST_LENGTH, PROT_READ | PROT_WRITE,
102                                 MAP_SHARED, fd, 0 )) == (void*)-1) goto error;
103     thread->buffer_info = (struct server_buffer_info *)((char *)thread->buffer + MAX_REQUEST_LENGTH) - 1;
104     if (!(thread->request_fd = create_request_socket( thread ))) goto error;
105     thread->reply_fd = fd_pipe[1];
106     /* build the first request into the buffer and send it */
107     req = thread->buffer;
108     req->pid  = get_process_id( thread->process );
109     req->tid  = get_thread_id( thread );
110     req->boot = (thread == booting_thread);
111     req->version = SERVER_PROTOCOL_VERSION;
112
113     /* add it here since send_client_fd may call kill_thread */
114     add_process_thread( thread->process, thread );
115
116     send_client_fd( thread, fd_pipe[0], 0 );
117     send_client_fd( thread, fd, 0 );
118     send_reply( thread );
119     close( fd_pipe[0] );
120     close( fd );
121     return 1;
122
123  error:
124     file_set_error();
125     if (fd != -1) close( fd );
126     close( fd_pipe[0] );
127     close( fd_pipe[1] );
128     return 0;
129 }
130
131 /* create a new thread */
132 struct thread *create_thread( int fd, struct process *process )
133 {
134     struct thread *thread;
135
136     int flags = fcntl( fd, F_GETFL, 0 );
137     fcntl( fd, F_SETFL, flags | O_NONBLOCK );
138
139     if (!(thread = alloc_object( &thread_ops, fd ))) return NULL;
140
141     thread->unix_pid    = 0;  /* not known yet */
142     thread->context     = NULL;
143     thread->teb         = NULL;
144     thread->mutex       = NULL;
145     thread->debug_ctx   = NULL;
146     thread->debug_event = NULL;
147     thread->queue       = NULL;
148     thread->info        = NULL;
149     thread->wait        = NULL;
150     thread->system_apc.head = NULL;
151     thread->system_apc.tail = NULL;
152     thread->user_apc.head   = NULL;
153     thread->user_apc.tail   = NULL;
154     thread->error       = 0;
155     thread->pass_fd     = -1;
156     thread->request_fd  = NULL;
157     thread->reply_fd    = -1;
158     thread->state       = RUNNING;
159     thread->attached    = 0;
160     thread->exit_code   = 0;
161     thread->next        = NULL;
162     thread->prev        = NULL;
163     thread->priority    = THREAD_PRIORITY_NORMAL;
164     thread->affinity    = 1;
165     thread->suspend     = 0;
166     thread->buffer      = (void *)-1;
167     thread->last_req    = REQ_GET_THREAD_BUFFER;
168     thread->process     = (struct process *)grab_object( process );
169
170     if (!current) current = thread;
171
172     if (!booting_thread)  /* first thread ever */
173     {
174         booting_thread = thread;
175         lock_master_socket(1);
176     }
177
178     if ((thread->next = first_thread) != NULL) thread->next->prev = thread;
179     first_thread = thread;
180
181     set_select_events( &thread->obj, POLLIN );  /* start listening to events */
182     if (!alloc_client_buffer( thread )) goto error;
183     return thread;
184
185  error:
186     release_object( thread );
187     return NULL;
188 }
189
190 /* handle a client event */
191 void thread_poll_event( struct object *obj, int event )
192 {
193     struct thread *thread = (struct thread *)obj;
194     assert( obj->ops == &thread_ops );
195
196     if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
197     else
198     {
199         if (event & POLLOUT) write_request( thread );
200         if (event & POLLIN) read_request( thread );
201     }
202 }
203
204 /* destroy a thread when its refcount is 0 */
205 static void destroy_thread( struct object *obj )
206 {
207     struct thread_apc *apc;
208     struct thread *thread = (struct thread *)obj;
209     assert( obj->ops == &thread_ops );
210
211     assert( !thread->debug_ctx );  /* cannot still be debugging something */
212     release_object( thread->process );
213     if (thread->next) thread->next->prev = thread->prev;
214     if (thread->prev) thread->prev->next = thread->next;
215     else first_thread = thread->next;
216     while ((apc = thread_dequeue_apc( thread, 0 ))) free( apc );
217     if (thread->info) release_object( thread->info );
218     if (thread->queue) release_object( thread->queue );
219     if (thread->buffer != (void *)-1) munmap( thread->buffer, MAX_REQUEST_LENGTH );
220     if (thread->reply_fd != -1) close( thread->reply_fd );
221     if (thread->pass_fd != -1) close( thread->pass_fd );
222     if (thread->request_fd) release_object( thread->request_fd );
223 }
224
225 /* dump a thread on stdout for debugging purposes */
226 static void dump_thread( struct object *obj, int verbose )
227 {
228     struct thread *thread = (struct thread *)obj;
229     assert( obj->ops == &thread_ops );
230
231     fprintf( stderr, "Thread pid=%d teb=%p state=%d\n",
232              thread->unix_pid, thread->teb, thread->state );
233 }
234
235 static int thread_signaled( struct object *obj, struct thread *thread )
236 {
237     struct thread *mythread = (struct thread *)obj;
238     return (mythread->state == TERMINATED);
239 }
240
241 /* get a thread pointer from a thread id (and increment the refcount) */
242 struct thread *get_thread_from_id( void *id )
243 {
244     struct thread *t = first_thread;
245     while (t && (t != id)) t = t->next;
246     if (t) grab_object( t );
247     return t;
248 }
249
250 /* get a thread from a handle (and increment the refcount) */
251 struct thread *get_thread_from_handle( handle_t handle, unsigned int access )
252 {
253     return (struct thread *)get_handle_obj( current->process, handle,
254                                             access, &thread_ops );
255 }
256
257 /* find a thread from a Unix pid */
258 struct thread *get_thread_from_pid( int pid )
259 {
260     struct thread *t = first_thread;
261     while (t && (t->unix_pid != pid)) t = t->next;
262     return t;
263 }
264
265 /* set all information about a thread */
266 static void set_thread_info( struct thread *thread,
267                              struct set_thread_info_request *req )
268 {
269     if (req->mask & SET_THREAD_INFO_PRIORITY)
270         thread->priority = req->priority;
271     if (req->mask & SET_THREAD_INFO_AFFINITY)
272     {
273         if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
274         else thread->affinity = req->affinity;
275     }
276 }
277
278 /* suspend a thread */
279 int suspend_thread( struct thread *thread, int check_limit )
280 {
281     int old_count = thread->suspend;
282     if (thread->suspend < MAXIMUM_SUSPEND_COUNT || !check_limit)
283     {
284         if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
285     }
286     else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
287     return old_count;
288 }
289
290 /* resume a thread */
291 int resume_thread( struct thread *thread )
292 {
293     int old_count = thread->suspend;
294     if (thread->suspend > 0)
295     {
296         if (!(--thread->suspend + thread->process->suspend)) continue_thread( thread );
297     }
298     return old_count;
299 }
300
301 /* suspend all threads but the current */
302 void suspend_all_threads( void )
303 {
304     struct thread *thread;
305     for ( thread = first_thread; thread; thread = thread->next )
306         if ( thread != current )
307             suspend_thread( thread, 0 );
308 }
309
310 /* resume all threads but the current */
311 void resume_all_threads( void )
312 {
313     struct thread *thread;
314     for ( thread = first_thread; thread; thread = thread->next )
315         if ( thread != current )
316             resume_thread( thread );
317 }
318
319 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
320 int add_queue( struct object *obj, struct wait_queue_entry *entry )
321 {
322     grab_object( obj );
323     entry->obj    = obj;
324     entry->prev   = obj->tail;
325     entry->next   = NULL;
326     if (obj->tail) obj->tail->next = entry;
327     else obj->head = entry;
328     obj->tail = entry;
329     return 1;
330 }
331
332 /* remove a thread from an object wait queue */
333 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
334 {
335     if (entry->next) entry->next->prev = entry->prev;
336     else obj->tail = entry->prev;
337     if (entry->prev) entry->prev->next = entry->next;
338     else obj->head = entry->next;
339     release_object( obj );
340 }
341
342 /* finish waiting */
343 static void end_wait( struct thread *thread )
344 {
345     struct thread_wait *wait = thread->wait;
346     struct wait_queue_entry *entry;
347     int i;
348
349     assert( wait );
350     for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
351         entry->obj->ops->remove_queue( entry->obj, entry );
352     if (wait->user) remove_timeout_user( wait->user );
353     free( wait );
354     thread->wait = NULL;
355 }
356
357 /* build the thread wait structure */
358 static int wait_on( int count, struct object *objects[], int flags,
359                     int sec, int usec, sleep_reply func )
360 {
361     struct thread_wait *wait;
362     struct wait_queue_entry *entry;
363     int i;
364
365     if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
366     current->wait = wait;
367     wait->count   = count;
368     wait->flags   = flags;
369     wait->user    = NULL;
370     wait->reply   = func;
371     if (flags & SELECT_TIMEOUT)
372     {
373         wait->timeout.tv_sec = sec;
374         wait->timeout.tv_usec = usec;
375     }
376
377     for (i = 0, entry = wait->queues; i < count; i++, entry++)
378     {
379         struct object *obj = objects[i];
380         entry->thread = current;
381         if (!obj->ops->add_queue( obj, entry ))
382         {
383             wait->count = i;
384             end_wait( current );
385             return 0;
386         }
387     }
388     return 1;
389 }
390
391 /* check if the thread waiting condition is satisfied */
392 static int check_wait( struct thread *thread, struct object **object )
393 {
394     int i, signaled;
395     struct thread_wait *wait = thread->wait;
396     struct wait_queue_entry *entry = wait->queues;
397
398     assert( wait );
399     *object = NULL;
400     if (wait->flags & SELECT_ALL)
401     {
402         int not_ok = 0;
403         /* Note: we must check them all anyway, as some objects may
404          * want to do something when signaled, even if others are not */
405         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
406             not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
407         if (not_ok) goto other_checks;
408         /* Wait satisfied: tell it to all objects */
409         signaled = 0;
410         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
411             if (entry->obj->ops->satisfied( entry->obj, thread ))
412                 signaled = STATUS_ABANDONED_WAIT_0;
413         return signaled;
414     }
415     else
416     {
417         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
418         {
419             if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
420             /* Wait satisfied: tell it to the object */
421             signaled = i;
422             *object = entry->obj;
423             if (entry->obj->ops->satisfied( entry->obj, thread ))
424                 signaled = i + STATUS_ABANDONED_WAIT_0;
425             return signaled;
426         }
427     }
428
429  other_checks:
430     if ((wait->flags & SELECT_INTERRUPTIBLE) && thread->system_apc.head) return STATUS_USER_APC;
431     if ((wait->flags & SELECT_ALERTABLE) && thread->user_apc.head) return STATUS_USER_APC;
432     if (wait->flags & SELECT_TIMEOUT)
433     {
434         struct timeval now;
435         gettimeofday( &now, NULL );
436         if (!time_before( &now, &wait->timeout )) return STATUS_TIMEOUT;
437     }
438     return -1;
439 }
440
441 /* build a reply to the select request */
442 static void build_select_reply( struct thread *thread, struct object *obj, int signaled )
443 {
444     struct select_request *req = get_req_ptr( thread );
445     req->signaled = signaled;
446 }
447
448 /* attempt to wake up a thread */
449 /* return 1 if OK, 0 if the wait condition is still not satisfied */
450 static int wake_thread( struct thread *thread )
451 {
452     int signaled;
453     struct object *object;
454     if ((signaled = check_wait( thread, &object )) == -1) return 0;
455     thread->error = 0;
456     thread->wait->reply( thread, object, signaled );
457     end_wait( thread );
458     return 1;
459 }
460
461 /* thread wait timeout */
462 static void thread_timeout( void *ptr )
463 {
464     struct thread *thread = ptr;
465     if (debug_level) fprintf( stderr, "%08x: *timeout*\n", (unsigned int)thread );
466     assert( thread->wait );
467     thread->error = 0;
468     thread->wait->user = NULL;
469     thread->wait->reply( thread, NULL, STATUS_TIMEOUT );
470     end_wait( thread );
471     send_reply( thread );
472 }
473
474 /* sleep on a list of objects */
475 int sleep_on( int count, struct object *objects[], int flags, int sec, int usec, sleep_reply func )
476 {
477     assert( !current->wait );
478     if (!wait_on( count, objects, flags, sec, usec, func )) return 0;
479     if (wake_thread( current )) return 1;
480     /* now we need to wait */
481     if (flags & SELECT_TIMEOUT)
482     {
483         if (!(current->wait->user = add_timeout_user( &current->wait->timeout,
484                                                       thread_timeout, current )))
485         {
486             end_wait( current );
487             return 0;
488         }
489     }
490     return 1;
491 }
492
493 /* select on a list of handles */
494 static int select_on( int count, handle_t *handles, int flags, int sec, int usec )
495 {
496     int ret = 0;
497     int i;
498     struct object *objects[MAXIMUM_WAIT_OBJECTS];
499
500     if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
501     {
502         set_error( STATUS_INVALID_PARAMETER );
503         return 0;
504     }
505     for (i = 0; i < count; i++)
506     {
507         if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
508             break;
509     }
510     if (i == count) ret = sleep_on( count, objects, flags, sec, usec, build_select_reply );
511     while (--i >= 0) release_object( objects[i] );
512     return ret;
513 }
514
515 /* attempt to wake threads sleeping on the object wait queue */
516 void wake_up( struct object *obj, int max )
517 {
518     struct wait_queue_entry *entry = obj->head;
519
520     while (entry)
521     {
522         struct thread *thread = entry->thread;
523         entry = entry->next;
524         if (wake_thread( thread ))
525         {
526             send_reply( thread );
527             if (max && !--max) break;
528         }
529     }
530 }
531
532 /* queue an async procedure call */
533 int thread_queue_apc( struct thread *thread, struct object *owner, void *func,
534                       enum apc_type type, int system, int nb_args, ... )
535 {
536     struct thread_apc *apc;
537     struct apc_queue *queue = system ? &thread->system_apc : &thread->user_apc;
538
539     /* cancel a possible previous APC with the same owner */
540     if (owner) thread_cancel_apc( thread, owner, system );
541
542     if (!(apc = mem_alloc( sizeof(*apc) + (nb_args-1)*sizeof(apc->args[0]) ))) return 0;
543     apc->prev    = queue->tail;
544     apc->next    = NULL;
545     apc->owner   = owner;
546     apc->func    = func;
547     apc->type    = type;
548     apc->nb_args = nb_args;
549     if (nb_args)
550     {
551         int i;
552         va_list args;
553         va_start( args, nb_args );
554         for (i = 0; i < nb_args; i++) apc->args[i] = va_arg( args, void * );
555         va_end( args );
556     }
557     queue->tail = apc;
558     if (!apc->prev)  /* first one */
559     {
560         queue->head = apc;
561         if (thread->wait && wake_thread( thread )) send_reply( thread );
562     }
563     return 1;
564 }
565
566 /* cancel the async procedure call owned by a specific object */
567 void thread_cancel_apc( struct thread *thread, struct object *owner, int system )
568 {
569     struct thread_apc *apc;
570     struct apc_queue *queue = system ? &thread->system_apc : &thread->user_apc;
571     for (apc = queue->head; apc; apc = apc->next)
572     {
573         if (apc->owner != owner) continue;
574         if (apc->next) apc->next->prev = apc->prev;
575         else queue->tail = apc->prev;
576         if (apc->prev) apc->prev->next = apc->next;
577         else queue->head = apc->next;
578         free( apc );
579         return;
580     }
581 }
582
583 /* remove the head apc from the queue; the returned pointer must be freed by the caller */
584 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
585 {
586     struct thread_apc *apc;
587     struct apc_queue *queue = &thread->system_apc;
588
589     if (!queue->head && !system_only) queue = &thread->user_apc;
590     if ((apc = queue->head))
591     {
592         if (apc->next) apc->next->prev = NULL;
593         else queue->tail = NULL;
594         queue->head = apc->next;
595     }
596     return apc;
597 }
598
599 /* retrieve an LDT selector entry */
600 static void get_selector_entry( struct thread *thread, int entry,
601                                 unsigned int *base, unsigned int *limit,
602                                 unsigned char *flags )
603 {
604     if (!thread->process->ldt_copy)
605     {
606         set_error( STATUS_ACCESS_DENIED );
607         return;
608     }
609     if (entry >= 8192)
610     {
611         set_error( STATUS_INVALID_PARAMETER );  /* FIXME */
612         return;
613     }
614     if (suspend_for_ptrace( thread ))
615     {
616         unsigned char flags_buf[4];
617         int *addr = (int *)thread->process->ldt_copy + entry;
618         if (read_thread_int( thread, addr, base ) == -1) goto done;
619         if (read_thread_int( thread, addr + 8192, limit ) == -1) goto done;
620         addr = (int *)thread->process->ldt_copy + 2*8192 + (entry >> 2);
621         if (read_thread_int( thread, addr, (int *)flags_buf ) == -1) goto done;
622         *flags = flags_buf[entry & 3];
623     done:
624         resume_thread( thread );
625     }
626 }
627
628 /* kill a thread on the spot */
629 void kill_thread( struct thread *thread, int violent_death )
630 {
631     if (thread->state == TERMINATED) return;  /* already killed */
632     thread->state = TERMINATED;
633     if (current == thread) current = NULL;
634     if (debug_level)
635         fprintf( stderr,"%08x: *killed* exit_code=%d\n",
636                  (unsigned int)thread, thread->exit_code );
637     if (thread->wait)
638     {
639         end_wait( thread );
640         /* if it is waiting on the socket, we don't need to send a SIGTERM */
641         violent_death = 0;
642     }
643     debug_exit_thread( thread );
644     abandon_mutexes( thread );
645     remove_process_thread( thread->process, thread );
646     wake_up( &thread->obj, 0 );
647     detach_thread( thread, violent_death ? SIGTERM : 0 );
648     remove_select_user( &thread->obj );
649     release_object( thread->request_fd );
650     close( thread->reply_fd );
651     munmap( thread->buffer, MAX_REQUEST_LENGTH );
652     thread->request_fd = NULL;
653     thread->reply_fd = -1;
654     thread->buffer = (void *)-1;
655     release_object( thread );
656 }
657
658 /* take a snapshot of currently running threads */
659 struct thread_snapshot *thread_snap( int *count )
660 {
661     struct thread_snapshot *snapshot, *ptr;
662     struct thread *thread;
663     int total = 0;
664
665     for (thread = first_thread; thread; thread = thread->next)
666         if (thread->state != TERMINATED) total++;
667     if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
668     ptr = snapshot;
669     for (thread = first_thread; thread; thread = thread->next)
670     {
671         if (thread->state == TERMINATED) continue;
672         ptr->thread   = thread;
673         ptr->count    = thread->obj.refcount;
674         ptr->priority = thread->priority;
675         grab_object( thread );
676         ptr++;
677     }
678     *count = total;
679     return snapshot;
680 }
681
682 /* signal that we are finished booting on the client side */
683 DECL_HANDLER(boot_done)
684 {
685     debug_level = max( debug_level, req->debug_level );
686     /* Make sure last_req is initialized */
687     current->last_req = REQ_BOOT_DONE;
688     if (current == booting_thread)
689     {
690         booting_thread = (struct thread *)~0UL;  /* make sure it doesn't match other threads */
691         lock_master_socket(0);  /* allow other clients now */
692     }
693 }
694
695 /* create a new thread */
696 DECL_HANDLER(new_thread)
697 {
698     struct thread *thread;
699     int sock[2];
700
701     if (socketpair( AF_UNIX, SOCK_STREAM, 0, sock ) != -1)
702     {
703         if ((thread = create_thread( sock[0], current->process )))
704         {
705             if (req->suspend) thread->suspend++;
706             req->tid = thread;
707             if ((req->handle = alloc_handle( current->process, thread,
708                                              THREAD_ALL_ACCESS, req->inherit )))
709             {
710                 send_client_fd( current, sock[1], req->handle );
711                 close( sock[1] );
712                 /* thread object will be released when the thread gets killed */
713                 return;
714             }
715             kill_thread( thread, 1 );
716         }
717         close( sock[1] );
718     }
719     else file_set_error();
720 }
721
722 /* retrieve the thread buffer file descriptor */
723 DECL_HANDLER(get_thread_buffer)
724 {
725     fatal_protocol_error( current, "get_thread_buffer: should never get called directly\n" );
726 }
727
728 /* initialize a new thread */
729 DECL_HANDLER(init_thread)
730 {
731     if (current->unix_pid)
732     {
733         fatal_protocol_error( current, "init_thread: already running\n" );
734         return;
735     }
736     current->unix_pid = req->unix_pid;
737     current->teb      = req->teb;
738     if (current->suspend + current->process->suspend > 0) stop_thread( current );
739     if (current->process->running_threads > 1)
740         generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
741 }
742
743 /* terminate a thread */
744 DECL_HANDLER(terminate_thread)
745 {
746     struct thread *thread;
747
748     req->self = 0;
749     req->last = 0;
750     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
751     {
752         thread->exit_code = req->exit_code;
753         if (thread != current) kill_thread( thread, 1 );
754         else
755         {
756             req->self = 1;
757             req->last = (thread->process->running_threads == 1);
758         }
759         release_object( thread );
760     }
761 }
762
763 /* fetch information about a thread */
764 DECL_HANDLER(get_thread_info)
765 {
766     struct thread *thread;
767     handle_t handle = req->handle;
768
769     if (!handle) thread = get_thread_from_id( req->tid_in );
770     else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
771
772     if (thread)
773     {
774         req->tid       = get_thread_id( thread );
775         req->teb       = thread->teb;
776         req->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STILL_ACTIVE;
777         req->priority  = thread->priority;
778         release_object( thread );
779     }
780 }
781
782 /* set information about a thread */
783 DECL_HANDLER(set_thread_info)
784 {
785     struct thread *thread;
786
787     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
788     {
789         set_thread_info( thread, req );
790         release_object( thread );
791     }
792 }
793
794 /* suspend a thread */
795 DECL_HANDLER(suspend_thread)
796 {
797     struct thread *thread;
798
799     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
800     {
801         req->count = suspend_thread( thread, 1 );
802         release_object( thread );
803     }
804 }
805
806 /* resume a thread */
807 DECL_HANDLER(resume_thread)
808 {
809     struct thread *thread;
810
811     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
812     {
813         req->count = resume_thread( thread );
814         release_object( thread );
815     }
816 }
817
818 /* select on a handle list */
819 DECL_HANDLER(select)
820 {
821     int count = get_req_data_size(req) / sizeof(int);
822     if (!select_on( count, get_req_data(req), req->flags, req->sec, req->usec ))
823         req->signaled = -1;
824 }
825
826 /* queue an APC for a thread */
827 DECL_HANDLER(queue_apc)
828 {
829     struct thread *thread;
830     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
831     {
832         thread_queue_apc( thread, NULL, req->func, APC_USER, !req->user, 1, req->param );
833         release_object( thread );
834     }
835 }
836
837 /* get next APC to call */
838 DECL_HANDLER(get_apc)
839 {
840     struct thread_apc *apc;
841     size_t size;
842
843     for (;;)
844     {
845         if (!(apc = thread_dequeue_apc( current, !req->alertable )))
846         {
847             /* no more APCs */
848             req->func    = NULL;
849             req->type    = APC_NONE;
850             set_req_data_size( req, 0 );
851             return;
852         }
853         /* Optimization: ignore APCs that have a NULL func; they are only used
854          * to wake up a thread, but since we got here the thread woke up already.
855          */
856         if (apc->func) break;
857         free( apc );
858     }
859     size = apc->nb_args * sizeof(apc->args[0]);
860     if (size > get_req_data_size(req)) size = get_req_data_size(req);
861     req->func = apc->func;
862     req->type = apc->type;
863     memcpy( get_req_data(req), apc->args, size );
864     set_req_data_size( req, size );
865     free( apc );
866 }
867
868 /* fetch a selector entry for a thread */
869 DECL_HANDLER(get_selector_entry)
870 {
871     struct thread *thread;
872     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
873     {
874         get_selector_entry( thread, req->entry, &req->base, &req->limit, &req->flags );
875         release_object( thread );
876     }
877 }