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