Store module names in Unicode in the server.
[wine] / server / thread.c
1 /*
2  * Server-side thread management
3  *
4  * Copyright (C) 1998 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 <errno.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/types.h>
33 #include <unistd.h>
34 #include <time.h>
35
36 #include "windef.h"
37 #include "winbase.h"
38
39 #include "file.h"
40 #include "handle.h"
41 #include "process.h"
42 #include "thread.h"
43 #include "request.h"
44 #include "user.h"
45
46
47 /* thread queues */
48
49 struct thread_wait
50 {
51     struct thread_wait     *next;       /* next wait structure for this thread */
52     struct thread          *thread;     /* owner thread */
53     int                     count;      /* count of objects */
54     int                     flags;
55     void                   *cookie;     /* magic cookie to return to client */
56     struct timeval          timeout;
57     struct timeout_user    *user;
58     struct wait_queue_entry queues[1];
59 };
60
61 /* asynchronous procedure calls */
62
63 struct thread_apc
64 {
65     struct thread_apc  *next;     /* queue linked list */
66     struct thread_apc  *prev;
67     struct object      *owner;    /* object that queued this apc */
68     void               *func;     /* function to call in client */
69     enum apc_type       type;     /* type of apc function */
70     int                 nb_args;  /* number of arguments */
71     void               *arg1;     /* function arguments */
72     void               *arg2;
73     void               *arg3;
74 };
75
76
77 /* thread operations */
78
79 static void dump_thread( struct object *obj, int verbose );
80 static int thread_signaled( struct object *obj, struct thread *thread );
81 static void thread_poll_event( struct fd *fd, int event );
82 static void destroy_thread( struct object *obj );
83 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only );
84
85 static const struct object_ops thread_ops =
86 {
87     sizeof(struct thread),      /* size */
88     dump_thread,                /* dump */
89     add_queue,                  /* add_queue */
90     remove_queue,               /* remove_queue */
91     thread_signaled,            /* signaled */
92     no_satisfied,               /* satisfied */
93     no_get_fd,                  /* get_fd */
94     destroy_thread              /* destroy */
95 };
96
97 static const struct fd_ops thread_fd_ops =
98 {
99     NULL,                       /* get_poll_events */
100     thread_poll_event,          /* poll_event */
101     no_flush,                   /* flush */
102     no_get_file_info,           /* get_file_info */
103     no_queue_async              /* queue_async */
104 };
105
106 static struct thread *first_thread;
107 static struct thread *booting_thread;
108
109 /* initialize the structure for a newly allocated thread */
110 inline static void init_thread_structure( struct thread *thread )
111 {
112     int i;
113
114     thread->unix_pid        = -1;  /* not known yet */
115     thread->unix_tid        = -1;  /* not known yet */
116     thread->context         = NULL;
117     thread->teb             = NULL;
118     thread->mutex           = NULL;
119     thread->debug_ctx       = NULL;
120     thread->debug_event     = NULL;
121     thread->queue           = NULL;
122     thread->wait            = NULL;
123     thread->system_apc.head = NULL;
124     thread->system_apc.tail = NULL;
125     thread->user_apc.head   = NULL;
126     thread->user_apc.tail   = NULL;
127     thread->error           = 0;
128     thread->req_data        = NULL;
129     thread->req_toread      = 0;
130     thread->reply_data      = NULL;
131     thread->reply_towrite   = 0;
132     thread->request_fd      = NULL;
133     thread->reply_fd        = NULL;
134     thread->wait_fd         = NULL;
135     thread->state           = RUNNING;
136     thread->attached        = 0;
137     thread->exit_code       = 0;
138     thread->next            = NULL;
139     thread->prev            = NULL;
140     thread->priority        = THREAD_PRIORITY_NORMAL;
141     thread->affinity        = 1;
142     thread->suspend         = 0;
143     thread->creation_time   = time(NULL);
144     thread->exit_time       = 0;
145
146     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
147         thread->inflight[i].server = thread->inflight[i].client = -1;
148 }
149
150 /* create a new thread */
151 struct thread *create_thread( int fd, struct process *process )
152 {
153     struct thread *thread;
154
155     if (!(thread = alloc_object( &thread_ops ))) return NULL;
156
157     init_thread_structure( thread );
158
159     thread->process = (struct process *)grab_object( process );
160     if (!current) current = thread;
161
162     if (!booting_thread)  /* first thread ever */
163     {
164         booting_thread = thread;
165         lock_master_socket(1);
166     }
167
168     if ((thread->next = first_thread) != NULL) thread->next->prev = thread;
169     first_thread = thread;
170
171     if (!(thread->id = alloc_ptid( thread )))
172     {
173         release_object( thread );
174         return NULL;
175     }
176     if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj )))
177     {
178         release_object( thread );
179         return NULL;
180     }
181
182     thread->token = (struct token *) grab_object( process->token );
183
184     set_fd_events( thread->request_fd, POLLIN );  /* start listening to events */
185     add_process_thread( thread->process, thread );
186     return thread;
187 }
188
189 /* handle a client event */
190 static void thread_poll_event( struct fd *fd, int event )
191 {
192     struct thread *thread = get_fd_user( fd );
193     assert( thread->obj.ops == &thread_ops );
194
195     if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
196     else if (event & POLLIN) read_request( thread );
197     else if (event & POLLOUT) write_reply( thread );
198 }
199
200 /* cleanup everything that is no longer needed by a dead thread */
201 /* used by destroy_thread and kill_thread */
202 static void cleanup_thread( struct thread *thread )
203 {
204     int i;
205     struct thread_apc *apc;
206
207     while ((apc = thread_dequeue_apc( thread, 0 ))) free( apc );
208     if (thread->req_data) free( thread->req_data );
209     if (thread->reply_data) free( thread->reply_data );
210     if (thread->request_fd) release_object( thread->request_fd );
211     if (thread->reply_fd) release_object( thread->reply_fd );
212     if (thread->wait_fd) release_object( thread->wait_fd );
213     free_msg_queue( thread );
214     cleanup_clipboard_thread(thread);
215     destroy_thread_windows( thread );
216     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
217     {
218         if (thread->inflight[i].client != -1)
219         {
220             close( thread->inflight[i].server );
221             thread->inflight[i].client = thread->inflight[i].server = -1;
222         }
223     }
224     thread->req_data = NULL;
225     thread->reply_data = NULL;
226     thread->request_fd = NULL;
227     thread->reply_fd = NULL;
228     thread->wait_fd = NULL;
229
230     if (thread == booting_thread)  /* killing booting thread */
231     {
232         booting_thread = NULL;
233         lock_master_socket(0);
234     }
235 }
236
237 /* destroy a thread when its refcount is 0 */
238 static void destroy_thread( struct object *obj )
239 {
240     struct thread_apc *apc;
241     struct thread *thread = (struct thread *)obj;
242     assert( obj->ops == &thread_ops );
243
244     assert( !thread->debug_ctx );  /* cannot still be debugging something */
245     if (thread->next) thread->next->prev = thread->prev;
246     if (thread->prev) thread->prev->next = thread->next;
247     else first_thread = thread->next;
248     while ((apc = thread_dequeue_apc( thread, 0 ))) free( apc );
249     cleanup_thread( thread );
250     release_object( thread->process );
251     if (thread->id) free_ptid( thread->id );
252     if (thread->token) release_object( thread->token );
253 }
254
255 /* dump a thread on stdout for debugging purposes */
256 static void dump_thread( struct object *obj, int verbose )
257 {
258     struct thread *thread = (struct thread *)obj;
259     assert( obj->ops == &thread_ops );
260
261     fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d teb=%p state=%d\n",
262              thread->id, thread->unix_pid, thread->unix_tid, thread->teb, thread->state );
263 }
264
265 static int thread_signaled( struct object *obj, struct thread *thread )
266 {
267     struct thread *mythread = (struct thread *)obj;
268     return (mythread->state == TERMINATED);
269 }
270
271 /* get a thread pointer from a thread id (and increment the refcount) */
272 struct thread *get_thread_from_id( thread_id_t id )
273 {
274     struct object *obj = get_ptid_entry( id );
275
276     if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
277     set_error( STATUS_INVALID_PARAMETER );
278     return NULL;
279 }
280
281 /* get a thread from a handle (and increment the refcount) */
282 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
283 {
284     return (struct thread *)get_handle_obj( current->process, handle,
285                                             access, &thread_ops );
286 }
287
288 /* find a thread from a Unix pid */
289 struct thread *get_thread_from_pid( int pid )
290 {
291     struct thread *t;
292
293     for (t = first_thread; t; t = t->next) if (t->unix_tid == pid) return t;
294     for (t = first_thread; t; t = t->next) if (t->unix_pid == pid) return t;
295     return NULL;
296 }
297
298 /* set all information about a thread */
299 static void set_thread_info( struct thread *thread,
300                              const struct set_thread_info_request *req )
301 {
302     if (req->mask & SET_THREAD_INFO_PRIORITY)
303         thread->priority = req->priority;
304     if (req->mask & SET_THREAD_INFO_AFFINITY)
305     {
306         if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
307         else thread->affinity = req->affinity;
308     }
309 }
310
311 /* stop a thread (at the Unix level) */
312 void stop_thread( struct thread *thread )
313 {
314     /* can't stop a thread while initialisation is in progress */
315     if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
316 }
317
318 /* suspend a thread */
319 static int suspend_thread( struct thread *thread )
320 {
321     int old_count = thread->suspend;
322     if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
323     {
324         if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
325     }
326     else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
327     return old_count;
328 }
329
330 /* resume a thread */
331 static int resume_thread( struct thread *thread )
332 {
333     int old_count = thread->suspend;
334     if (thread->suspend > 0)
335     {
336         if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
337     }
338     return old_count;
339 }
340
341 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
342 int add_queue( struct object *obj, struct wait_queue_entry *entry )
343 {
344     grab_object( obj );
345     entry->obj    = obj;
346     entry->prev   = obj->tail;
347     entry->next   = NULL;
348     if (obj->tail) obj->tail->next = entry;
349     else obj->head = entry;
350     obj->tail = entry;
351     return 1;
352 }
353
354 /* remove a thread from an object wait queue */
355 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
356 {
357     if (entry->next) entry->next->prev = entry->prev;
358     else obj->tail = entry->prev;
359     if (entry->prev) entry->prev->next = entry->next;
360     else obj->head = entry->next;
361     release_object( obj );
362 }
363
364 /* finish waiting */
365 static void end_wait( struct thread *thread )
366 {
367     struct thread_wait *wait = thread->wait;
368     struct wait_queue_entry *entry;
369     int i;
370
371     assert( wait );
372     for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
373         entry->obj->ops->remove_queue( entry->obj, entry );
374     if (wait->user) remove_timeout_user( wait->user );
375     thread->wait = wait->next;
376     free( wait );
377 }
378
379 /* build the thread wait structure */
380 static int wait_on( int count, struct object *objects[], int flags, const abs_time_t *timeout )
381 {
382     struct thread_wait *wait;
383     struct wait_queue_entry *entry;
384     int i;
385
386     if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
387     wait->next    = current->wait;
388     wait->thread  = current;
389     wait->count   = count;
390     wait->flags   = flags;
391     wait->user    = NULL;
392     current->wait = wait;
393     if (flags & SELECT_TIMEOUT)
394     {
395         wait->timeout.tv_sec  = timeout->sec;
396         wait->timeout.tv_usec = timeout->usec;
397     }
398
399     for (i = 0, entry = wait->queues; i < count; i++, entry++)
400     {
401         struct object *obj = objects[i];
402         entry->thread = current;
403         if (!obj->ops->add_queue( obj, entry ))
404         {
405             wait->count = i;
406             end_wait( current );
407             return 0;
408         }
409     }
410     return 1;
411 }
412
413 /* check if the thread waiting condition is satisfied */
414 static int check_wait( struct thread *thread )
415 {
416     int i, signaled;
417     struct thread_wait *wait = thread->wait;
418     struct wait_queue_entry *entry = wait->queues;
419
420     /* Suspended threads may not acquire locks */
421     if( thread->process->suspend + thread->suspend > 0 ) return -1;
422
423     assert( wait );
424     if (wait->flags & SELECT_ALL)
425     {
426         int not_ok = 0;
427         /* Note: we must check them all anyway, as some objects may
428          * want to do something when signaled, even if others are not */
429         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
430             not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
431         if (not_ok) goto other_checks;
432         /* Wait satisfied: tell it to all objects */
433         signaled = 0;
434         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
435             if (entry->obj->ops->satisfied( entry->obj, thread ))
436                 signaled = STATUS_ABANDONED_WAIT_0;
437         return signaled;
438     }
439     else
440     {
441         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
442         {
443             if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
444             /* Wait satisfied: tell it to the object */
445             signaled = i;
446             if (entry->obj->ops->satisfied( entry->obj, thread ))
447                 signaled = i + STATUS_ABANDONED_WAIT_0;
448             return signaled;
449         }
450     }
451
452  other_checks:
453     if ((wait->flags & SELECT_INTERRUPTIBLE) && thread->system_apc.head) return STATUS_USER_APC;
454     if ((wait->flags & SELECT_ALERTABLE) && thread->user_apc.head) return STATUS_USER_APC;
455     if (wait->flags & SELECT_TIMEOUT)
456     {
457         struct timeval now;
458         gettimeofday( &now, NULL );
459         if (!time_before( &now, &wait->timeout )) return STATUS_TIMEOUT;
460     }
461     return -1;
462 }
463
464 /* send the wakeup signal to a thread */
465 static int send_thread_wakeup( struct thread *thread, void *cookie, int signaled )
466 {
467     struct wake_up_reply reply;
468     int ret;
469
470     reply.cookie   = cookie;
471     reply.signaled = signaled;
472     if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
473         return 0;
474     if (ret >= 0)
475         fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
476     else if (errno == EPIPE)
477         kill_thread( thread, 0 );  /* normal death */
478     else
479         fatal_protocol_perror( thread, "write" );
480     return -1;
481 }
482
483 /* attempt to wake up a thread */
484 /* return >0 if OK, 0 if the wait condition is still not satisfied */
485 int wake_thread( struct thread *thread )
486 {
487     int signaled, count;
488     void *cookie;
489
490     for (count = 0; thread->wait; count++)
491     {
492         if ((signaled = check_wait( thread )) == -1) break;
493
494         cookie = thread->wait->cookie;
495         if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
496                                   thread->id, signaled, cookie );
497         end_wait( thread );
498         if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
499             break;
500     }
501     return count;
502 }
503
504 /* thread wait timeout */
505 static void thread_timeout( void *ptr )
506 {
507     struct thread_wait *wait = ptr;
508     struct thread *thread = wait->thread;
509     void *cookie = wait->cookie;
510
511     wait->user = NULL;
512     if (thread->wait != wait) return; /* not the top-level wait, ignore it */
513     if (thread->suspend + thread->process->suspend > 0) return;  /* suspended, ignore it */
514
515     if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
516                               thread->id, STATUS_TIMEOUT, cookie );
517     end_wait( thread );
518     if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
519     /* check if other objects have become signaled in the meantime */
520     wake_thread( thread );
521 }
522
523 /* select on a list of handles */
524 static void select_on( int count, void *cookie, const obj_handle_t *handles,
525                        int flags, const abs_time_t *timeout )
526 {
527     int ret, i;
528     struct object *objects[MAXIMUM_WAIT_OBJECTS];
529
530     if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
531     {
532         set_error( STATUS_INVALID_PARAMETER );
533         return;
534     }
535     for (i = 0; i < count; i++)
536     {
537         if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
538             break;
539     }
540
541     if (i < count) goto done;
542     if (!wait_on( count, objects, flags, timeout )) goto done;
543
544     if ((ret = check_wait( current )) != -1)
545     {
546         /* condition is already satisfied */
547         end_wait( current );
548         set_error( ret );
549         goto done;
550     }
551
552     /* now we need to wait */
553     if (flags & SELECT_TIMEOUT)
554     {
555         if (!(current->wait->user = add_timeout_user( &current->wait->timeout,
556                                                       thread_timeout, current->wait )))
557         {
558             end_wait( current );
559             goto done;
560         }
561     }
562     current->wait->cookie = cookie;
563     set_error( STATUS_PENDING );
564
565 done:
566     while (--i >= 0) release_object( objects[i] );
567 }
568
569 /* attempt to wake threads sleeping on the object wait queue */
570 void wake_up( struct object *obj, int max )
571 {
572     struct wait_queue_entry *entry = obj->head;
573
574     while (entry)
575     {
576         struct thread *thread = entry->thread;
577         entry = entry->next;
578         if (wake_thread( thread ))
579         {
580             if (max && !--max) break;
581         }
582     }
583 }
584
585 /* queue an async procedure call */
586 int thread_queue_apc( struct thread *thread, struct object *owner, void *func,
587                       enum apc_type type, int system, void *arg1, void *arg2, void *arg3 )
588 {
589     struct thread_apc *apc;
590     struct apc_queue *queue = system ? &thread->system_apc : &thread->user_apc;
591
592     /* cancel a possible previous APC with the same owner */
593     if (owner) thread_cancel_apc( thread, owner, system );
594     if (thread->state == TERMINATED) return 0;
595
596     if (!(apc = mem_alloc( sizeof(*apc) ))) return 0;
597     apc->prev   = queue->tail;
598     apc->next   = NULL;
599     apc->owner  = owner;
600     apc->func   = func;
601     apc->type   = type;
602     apc->arg1   = arg1;
603     apc->arg2   = arg2;
604     apc->arg3   = arg3;
605     queue->tail = apc;
606     if (!apc->prev)  /* first one */
607     {
608         queue->head = apc;
609         wake_thread( thread );
610     }
611     else apc->prev->next = apc;
612
613     return 1;
614 }
615
616 /* cancel the async procedure call owned by a specific object */
617 void thread_cancel_apc( struct thread *thread, struct object *owner, int system )
618 {
619     struct thread_apc *apc;
620     struct apc_queue *queue = system ? &thread->system_apc : &thread->user_apc;
621     for (apc = queue->head; apc; apc = apc->next)
622     {
623         if (apc->owner != owner) continue;
624         if (apc->next) apc->next->prev = apc->prev;
625         else queue->tail = apc->prev;
626         if (apc->prev) apc->prev->next = apc->next;
627         else queue->head = apc->next;
628         free( apc );
629         return;
630     }
631 }
632
633 /* remove the head apc from the queue; the returned pointer must be freed by the caller */
634 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
635 {
636     struct thread_apc *apc;
637     struct apc_queue *queue = &thread->system_apc;
638
639     if (!queue->head && !system_only) queue = &thread->user_apc;
640     if ((apc = queue->head))
641     {
642         if (apc->next) apc->next->prev = NULL;
643         else queue->tail = NULL;
644         queue->head = apc->next;
645     }
646     return apc;
647 }
648
649 /* add an fd to the inflight list */
650 /* return list index, or -1 on error */
651 int thread_add_inflight_fd( struct thread *thread, int client, int server )
652 {
653     int i;
654
655     if (server == -1) return -1;
656     if (client == -1)
657     {
658         close( server );
659         return -1;
660     }
661
662     /* first check if we already have an entry for this fd */
663     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
664         if (thread->inflight[i].client == client)
665         {
666             close( thread->inflight[i].server );
667             thread->inflight[i].server = server;
668             return i;
669         }
670
671     /* now find a free spot to store it */
672     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
673         if (thread->inflight[i].client == -1)
674         {
675             thread->inflight[i].client = client;
676             thread->inflight[i].server = server;
677             return i;
678         }
679     return -1;
680 }
681
682 /* get an inflight fd and purge it from the list */
683 /* the fd must be closed when no longer used */
684 int thread_get_inflight_fd( struct thread *thread, int client )
685 {
686     int i, ret;
687
688     if (client == -1) return -1;
689
690     do
691     {
692         for (i = 0; i < MAX_INFLIGHT_FDS; i++)
693         {
694             if (thread->inflight[i].client == client)
695             {
696                 ret = thread->inflight[i].server;
697                 thread->inflight[i].server = thread->inflight[i].client = -1;
698                 return ret;
699             }
700         }
701     } while (!receive_fd( thread->process ));  /* in case it is still in the socket buffer */
702     return -1;
703 }
704
705 /* retrieve an LDT selector entry */
706 static void get_selector_entry( struct thread *thread, int entry,
707                                 unsigned int *base, unsigned int *limit,
708                                 unsigned char *flags )
709 {
710     if (!thread->process->ldt_copy)
711     {
712         set_error( STATUS_ACCESS_DENIED );
713         return;
714     }
715     if (entry >= 8192)
716     {
717         set_error( STATUS_INVALID_PARAMETER );  /* FIXME */
718         return;
719     }
720     if (suspend_for_ptrace( thread ))
721     {
722         unsigned char flags_buf[4];
723         int *addr = (int *)thread->process->ldt_copy + entry;
724         if (read_thread_int( thread, addr, base ) == -1) goto done;
725         if (read_thread_int( thread, addr + 8192, limit ) == -1) goto done;
726         addr = (int *)thread->process->ldt_copy + 2*8192 + (entry >> 2);
727         if (read_thread_int( thread, addr, (int *)flags_buf ) == -1) goto done;
728         *flags = flags_buf[entry & 3];
729     done:
730         resume_after_ptrace( thread );
731     }
732 }
733
734 /* kill a thread on the spot */
735 void kill_thread( struct thread *thread, int violent_death )
736 {
737     if (thread->state == TERMINATED) return;  /* already killed */
738     thread->state = TERMINATED;
739     thread->exit_time = time(NULL);
740     if (current == thread) current = NULL;
741     if (debug_level)
742         fprintf( stderr,"%04x: *killed* exit_code=%d\n",
743                  thread->id, thread->exit_code );
744     if (thread->wait)
745     {
746         while (thread->wait) end_wait( thread );
747         send_thread_wakeup( thread, NULL, STATUS_PENDING );
748         /* if it is waiting on the socket, we don't need to send a SIGTERM */
749         violent_death = 0;
750     }
751     kill_console_processes( thread, 0 );
752     debug_exit_thread( thread );
753     abandon_mutexes( thread );
754     remove_process_thread( thread->process, thread );
755     wake_up( &thread->obj, 0 );
756     detach_thread( thread, violent_death ? SIGTERM : 0 );
757     cleanup_thread( thread );
758     release_object( thread );
759 }
760
761 /* take a snapshot of currently running threads */
762 struct thread_snapshot *thread_snap( int *count )
763 {
764     struct thread_snapshot *snapshot, *ptr;
765     struct thread *thread;
766     int total = 0;
767
768     for (thread = first_thread; thread; thread = thread->next)
769         if (thread->state != TERMINATED) total++;
770     if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
771     ptr = snapshot;
772     for (thread = first_thread; thread; thread = thread->next)
773     {
774         if (thread->state == TERMINATED) continue;
775         ptr->thread   = thread;
776         ptr->count    = thread->obj.refcount;
777         ptr->priority = thread->priority;
778         grab_object( thread );
779         ptr++;
780     }
781     *count = total;
782     return snapshot;
783 }
784
785 /* signal that we are finished booting on the client side */
786 DECL_HANDLER(boot_done)
787 {
788     debug_level = max( debug_level, req->debug_level );
789     if (current == booting_thread)
790     {
791         booting_thread = (struct thread *)~0UL;  /* make sure it doesn't match other threads */
792         lock_master_socket(0);  /* allow other clients now */
793     }
794 }
795
796 /* create a new thread */
797 DECL_HANDLER(new_thread)
798 {
799     struct thread *thread;
800     int request_fd = thread_get_inflight_fd( current, req->request_fd );
801
802     if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
803     {
804         if (request_fd != -1) close( request_fd );
805         set_error( STATUS_INVALID_HANDLE );
806         return;
807     }
808
809     if ((thread = create_thread( request_fd, current->process )))
810     {
811         if (req->suspend) thread->suspend++;
812         reply->tid = get_thread_id( thread );
813         if ((reply->handle = alloc_handle( current->process, thread,
814                                            THREAD_ALL_ACCESS, req->inherit )))
815         {
816             /* thread object will be released when the thread gets killed */
817             return;
818         }
819         kill_thread( thread, 1 );
820     }
821 }
822
823 /* initialize a new thread */
824 DECL_HANDLER(init_thread)
825 {
826     int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
827     int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
828
829     if (current->unix_pid != -1)
830     {
831         fatal_protocol_error( current, "init_thread: already running\n" );
832         goto error;
833     }
834     if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1)
835     {
836         fatal_protocol_error( current, "bad reply fd\n" );
837         goto error;
838     }
839     if (wait_fd == -1)
840     {
841         fatal_protocol_error( current, "bad wait fd\n" );
842         goto error;
843     }
844     current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj );
845     current->wait_fd  = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj );
846     if (!current->reply_fd || !current->wait_fd) return;
847
848     current->unix_pid = req->unix_pid;
849     current->unix_tid = req->unix_tid;
850     current->teb      = req->teb;
851
852     if (current->suspend + current->process->suspend > 0) stop_thread( current );
853     if (current->process->running_threads > 1)
854         generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
855
856     reply->pid     = get_process_id( current->process );
857     reply->tid     = get_thread_id( current );
858     reply->boot    = (current == booting_thread);
859     reply->version = SERVER_PROTOCOL_VERSION;
860     return;
861
862  error:
863     if (reply_fd != -1) close( reply_fd );
864     if (wait_fd != -1) close( wait_fd );
865 }
866
867 /* terminate a thread */
868 DECL_HANDLER(terminate_thread)
869 {
870     struct thread *thread;
871
872     reply->self = 0;
873     reply->last = 0;
874     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
875     {
876         thread->exit_code = req->exit_code;
877         if (thread != current) kill_thread( thread, 1 );
878         else
879         {
880             reply->self = 1;
881             reply->last = (thread->process->running_threads == 1);
882         }
883         release_object( thread );
884     }
885 }
886
887 /* open a handle to a thread */
888 DECL_HANDLER(open_thread)
889 {
890     struct thread *thread = get_thread_from_id( req->tid );
891
892     reply->handle = 0;
893     if (thread)
894     {
895         reply->handle = alloc_handle( current->process, thread, req->access, req->inherit );
896         release_object( thread );
897     }
898 }
899
900 /* fetch information about a thread */
901 DECL_HANDLER(get_thread_info)
902 {
903     struct thread *thread;
904     obj_handle_t handle = req->handle;
905
906     if (!handle) thread = get_thread_from_id( req->tid_in );
907     else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
908
909     if (thread)
910     {
911         reply->pid            = get_process_id( thread->process );
912         reply->tid            = get_thread_id( thread );
913         reply->teb            = thread->teb;
914         reply->exit_code      = (thread->state == TERMINATED) ? thread->exit_code : STILL_ACTIVE;
915         reply->priority       = thread->priority;
916         reply->affinity       = thread->affinity;
917         reply->creation_time  = thread->creation_time;
918         reply->exit_time      = thread->exit_time;
919
920         release_object( thread );
921     }
922 }
923
924 /* set information about a thread */
925 DECL_HANDLER(set_thread_info)
926 {
927     struct thread *thread;
928
929     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
930     {
931         set_thread_info( thread, req );
932         release_object( thread );
933     }
934 }
935
936 /* suspend a thread */
937 DECL_HANDLER(suspend_thread)
938 {
939     struct thread *thread;
940
941     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
942     {
943         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
944         else reply->count = suspend_thread( thread );
945         release_object( thread );
946     }
947 }
948
949 /* resume a thread */
950 DECL_HANDLER(resume_thread)
951 {
952     struct thread *thread;
953
954     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
955     {
956         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
957         else reply->count = resume_thread( thread );
958         release_object( thread );
959     }
960 }
961
962 /* select on a handle list */
963 DECL_HANDLER(select)
964 {
965     int count = get_req_data_size() / sizeof(int);
966     select_on( count, req->cookie, get_req_data(), req->flags, &req->timeout );
967 }
968
969 /* queue an APC for a thread */
970 DECL_HANDLER(queue_apc)
971 {
972     struct thread *thread;
973     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
974     {
975         thread_queue_apc( thread, NULL, req->func, APC_USER, !req->user,
976                           req->arg1, req->arg2, req->arg3 );
977         release_object( thread );
978     }
979 }
980
981 /* get next APC to call */
982 DECL_HANDLER(get_apc)
983 {
984     struct thread_apc *apc;
985
986     for (;;)
987     {
988         if (!(apc = thread_dequeue_apc( current, !req->alertable )))
989         {
990             /* no more APCs */
991             reply->func = NULL;
992             reply->type = APC_NONE;
993             return;
994         }
995         /* Optimization: ignore APCs that have a NULL func; they are only used
996          * to wake up a thread, but since we got here the thread woke up already.
997          * Exception: for APC_ASYNC_IO, func == NULL is legal.
998          */
999         if (apc->func || apc->type == APC_ASYNC_IO) break;
1000         free( apc );
1001     }
1002     reply->func = apc->func;
1003     reply->type = apc->type;
1004     reply->arg1 = apc->arg1;
1005     reply->arg2 = apc->arg2;
1006     reply->arg3 = apc->arg3;
1007     free( apc );
1008 }
1009
1010 /* fetch a selector entry for a thread */
1011 DECL_HANDLER(get_selector_entry)
1012 {
1013     struct thread *thread;
1014     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1015     {
1016         get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1017         release_object( thread );
1018     }
1019 }