server: Support queuing some APCs to a process instead of a thread.
[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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <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 #ifdef HAVE_POLL_H
36 #include <poll.h>
37 #endif
38
39 #include "ntstatus.h"
40 #define WIN32_NO_STATUS
41 #include "windef.h"
42 #include "winternl.h"
43
44 #include "file.h"
45 #include "handle.h"
46 #include "process.h"
47 #include "thread.h"
48 #include "request.h"
49 #include "user.h"
50 #include "security.h"
51
52
53 /* thread queues */
54
55 struct thread_wait
56 {
57     struct thread_wait     *next;       /* next wait structure for this thread */
58     struct thread          *thread;     /* owner thread */
59     int                     count;      /* count of objects */
60     int                     flags;
61     void                   *cookie;     /* magic cookie to return to client */
62     struct timeval          timeout;
63     struct timeout_user    *user;
64     struct wait_queue_entry queues[1];
65 };
66
67 /* asynchronous procedure calls */
68
69 struct thread_apc
70 {
71     struct object       obj;      /* object header */
72     struct list         entry;    /* queue linked list */
73     struct object      *owner;    /* object that queued this apc */
74     int                 executed; /* has it been executed by the client? */
75     apc_call_t          call;     /* call arguments */
76     apc_result_t        result;   /* call results once executed */
77 };
78
79 static void dump_thread_apc( struct object *obj, int verbose );
80 static int thread_apc_signaled( struct object *obj, struct thread *thread );
81 static void clear_apc_queue( struct list *queue );
82
83 static const struct object_ops thread_apc_ops =
84 {
85     sizeof(struct thread_apc),  /* size */
86     dump_thread_apc,            /* dump */
87     add_queue,                  /* add_queue */
88     remove_queue,               /* remove_queue */
89     thread_apc_signaled,        /* signaled */
90     no_satisfied,               /* satisfied */
91     no_signal,                  /* signal */
92     no_get_fd,                  /* get_fd */
93     no_map_access,              /* map_access */
94     no_lookup_name,             /* lookup_name */
95     no_close_handle,            /* close_handle */
96     no_destroy                  /* destroy */
97 };
98
99
100 /* thread operations */
101
102 static void dump_thread( struct object *obj, int verbose );
103 static int thread_signaled( struct object *obj, struct thread *thread );
104 static unsigned int thread_map_access( struct object *obj, unsigned int access );
105 static void thread_poll_event( struct fd *fd, int event );
106 static void destroy_thread( struct object *obj );
107
108 static const struct object_ops thread_ops =
109 {
110     sizeof(struct thread),      /* size */
111     dump_thread,                /* dump */
112     add_queue,                  /* add_queue */
113     remove_queue,               /* remove_queue */
114     thread_signaled,            /* signaled */
115     no_satisfied,               /* satisfied */
116     no_signal,                  /* signal */
117     no_get_fd,                  /* get_fd */
118     thread_map_access,          /* map_access */
119     no_lookup_name,             /* lookup_name */
120     no_close_handle,            /* close_handle */
121     destroy_thread              /* destroy */
122 };
123
124 static const struct fd_ops thread_fd_ops =
125 {
126     NULL,                       /* get_poll_events */
127     thread_poll_event,          /* poll_event */
128     no_flush,                   /* flush */
129     no_get_file_info,           /* get_file_info */
130     no_queue_async,             /* queue_async */
131     no_cancel_async             /* cancel_async */
132 };
133
134 static struct list thread_list = LIST_INIT(thread_list);
135
136 /* initialize the structure for a newly allocated thread */
137 inline static void init_thread_structure( struct thread *thread )
138 {
139     int i;
140
141     thread->unix_pid        = -1;  /* not known yet */
142     thread->unix_tid        = -1;  /* not known yet */
143     thread->context         = NULL;
144     thread->suspend_context = NULL;
145     thread->teb             = NULL;
146     thread->debug_ctx       = NULL;
147     thread->debug_event     = NULL;
148     thread->debug_break     = 0;
149     thread->queue           = NULL;
150     thread->wait            = NULL;
151     thread->error           = 0;
152     thread->req_data        = NULL;
153     thread->req_toread      = 0;
154     thread->reply_data      = NULL;
155     thread->reply_towrite   = 0;
156     thread->request_fd      = NULL;
157     thread->reply_fd        = NULL;
158     thread->wait_fd         = NULL;
159     thread->state           = RUNNING;
160     thread->exit_code       = 0;
161     thread->priority        = 0;
162     thread->affinity        = 1;
163     thread->suspend         = 0;
164     thread->desktop_users   = 0;
165     thread->token           = NULL;
166
167     thread->creation_time = current_time;
168     thread->exit_time.tv_sec = thread->exit_time.tv_usec = 0;
169
170     list_init( &thread->mutex_list );
171     list_init( &thread->system_apc );
172     list_init( &thread->user_apc );
173
174     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
175         thread->inflight[i].server = thread->inflight[i].client = -1;
176 }
177
178 /* check if address looks valid for a client-side data structure (TEB etc.) */
179 static inline int is_valid_address( void *addr )
180 {
181     return addr && !((unsigned long)addr % sizeof(int));
182 }
183
184 /* create a new thread */
185 struct thread *create_thread( int fd, struct process *process )
186 {
187     struct thread *thread;
188
189     if (!(thread = alloc_object( &thread_ops ))) return NULL;
190
191     init_thread_structure( thread );
192
193     thread->process = (struct process *)grab_object( process );
194     thread->desktop = process->desktop;
195     if (!current) current = thread;
196
197     list_add_head( &thread_list, &thread->entry );
198
199     if (!(thread->id = alloc_ptid( thread )))
200     {
201         release_object( thread );
202         return NULL;
203     }
204     if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj )))
205     {
206         release_object( thread );
207         return NULL;
208     }
209
210     set_fd_events( thread->request_fd, POLLIN );  /* start listening to events */
211     add_process_thread( thread->process, thread );
212     return thread;
213 }
214
215 /* handle a client event */
216 static void thread_poll_event( struct fd *fd, int event )
217 {
218     struct thread *thread = get_fd_user( fd );
219     assert( thread->obj.ops == &thread_ops );
220
221     if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
222     else if (event & POLLIN) read_request( thread );
223     else if (event & POLLOUT) write_reply( thread );
224 }
225
226 /* cleanup everything that is no longer needed by a dead thread */
227 /* used by destroy_thread and kill_thread */
228 static void cleanup_thread( struct thread *thread )
229 {
230     int i;
231
232     clear_apc_queue( &thread->system_apc );
233     clear_apc_queue( &thread->user_apc );
234     free( thread->req_data );
235     free( thread->reply_data );
236     if (thread->request_fd) release_object( thread->request_fd );
237     if (thread->reply_fd) release_object( thread->reply_fd );
238     if (thread->wait_fd) release_object( thread->wait_fd );
239     free( thread->suspend_context );
240     free_msg_queue( thread );
241     cleanup_clipboard_thread(thread);
242     destroy_thread_windows( thread );
243     close_thread_desktop( thread );
244     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
245     {
246         if (thread->inflight[i].client != -1)
247         {
248             close( thread->inflight[i].server );
249             thread->inflight[i].client = thread->inflight[i].server = -1;
250         }
251     }
252     thread->req_data = NULL;
253     thread->reply_data = NULL;
254     thread->request_fd = NULL;
255     thread->reply_fd = NULL;
256     thread->wait_fd = NULL;
257     thread->context = NULL;
258     thread->suspend_context = NULL;
259     thread->desktop = 0;
260 }
261
262 /* destroy a thread when its refcount is 0 */
263 static void destroy_thread( struct object *obj )
264 {
265     struct thread *thread = (struct thread *)obj;
266     assert( obj->ops == &thread_ops );
267
268     assert( !thread->debug_ctx );  /* cannot still be debugging something */
269     list_remove( &thread->entry );
270     cleanup_thread( thread );
271     release_object( thread->process );
272     if (thread->id) free_ptid( thread->id );
273     if (thread->token) release_object( thread->token );
274 }
275
276 /* dump a thread on stdout for debugging purposes */
277 static void dump_thread( struct object *obj, int verbose )
278 {
279     struct thread *thread = (struct thread *)obj;
280     assert( obj->ops == &thread_ops );
281
282     fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d teb=%p state=%d\n",
283              thread->id, thread->unix_pid, thread->unix_tid, thread->teb, thread->state );
284 }
285
286 static int thread_signaled( struct object *obj, struct thread *thread )
287 {
288     struct thread *mythread = (struct thread *)obj;
289     return (mythread->state == TERMINATED);
290 }
291
292 static unsigned int thread_map_access( struct object *obj, unsigned int access )
293 {
294     if (access & GENERIC_READ)    access |= STANDARD_RIGHTS_READ | SYNCHRONIZE;
295     if (access & GENERIC_WRITE)   access |= STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
296     if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
297     if (access & GENERIC_ALL)     access |= THREAD_ALL_ACCESS;
298     return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
299 }
300
301 static void dump_thread_apc( struct object *obj, int verbose )
302 {
303     struct thread_apc *apc = (struct thread_apc *)obj;
304     assert( obj->ops == &thread_apc_ops );
305
306     fprintf( stderr, "APC owner=%p type=%u\n", apc->owner, apc->call.type );
307 }
308
309 static int thread_apc_signaled( struct object *obj, struct thread *thread )
310 {
311     struct thread_apc *apc = (struct thread_apc *)obj;
312     return apc->executed;
313 }
314
315 /* queue an async procedure call */
316 static struct thread_apc *create_apc( struct object *owner, const apc_call_t *call_data )
317 {
318     struct thread_apc *apc;
319
320     if ((apc = alloc_object( &thread_apc_ops )))
321     {
322         apc->call        = *call_data;
323         apc->owner       = owner;
324         apc->executed    = 0;
325         apc->result.type = APC_NONE;
326     }
327     return apc;
328 }
329
330 /* get a thread pointer from a thread id (and increment the refcount) */
331 struct thread *get_thread_from_id( thread_id_t id )
332 {
333     struct object *obj = get_ptid_entry( id );
334
335     if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
336     set_error( STATUS_INVALID_CID );
337     return NULL;
338 }
339
340 /* get a thread from a handle (and increment the refcount) */
341 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
342 {
343     return (struct thread *)get_handle_obj( current->process, handle,
344                                             access, &thread_ops );
345 }
346
347 /* find a thread from a Unix tid */
348 struct thread *get_thread_from_tid( int tid )
349 {
350     struct thread *thread;
351
352     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
353     {
354         if (thread->unix_tid == tid) return thread;
355     }
356     return NULL;
357 }
358
359 /* find a thread from a Unix pid */
360 struct thread *get_thread_from_pid( int pid )
361 {
362     struct thread *thread;
363
364     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
365     {
366         if (thread->unix_pid == pid) return thread;
367     }
368     return NULL;
369 }
370
371 /* set all information about a thread */
372 static void set_thread_info( struct thread *thread,
373                              const struct set_thread_info_request *req )
374 {
375     if (req->mask & SET_THREAD_INFO_PRIORITY)
376         thread->priority = req->priority;
377     if (req->mask & SET_THREAD_INFO_AFFINITY)
378     {
379         if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
380         else thread->affinity = req->affinity;
381     }
382     if (req->mask & SET_THREAD_INFO_TOKEN)
383         security_set_thread_token( thread, req->token );
384 }
385
386 /* stop a thread (at the Unix level) */
387 void stop_thread( struct thread *thread )
388 {
389     if (thread->context) return;  /* already inside a debug event, no need for a signal */
390     /* can't stop a thread while initialisation is in progress */
391     if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
392 }
393
394 /* suspend a thread */
395 static int suspend_thread( struct thread *thread )
396 {
397     int old_count = thread->suspend;
398     if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
399     {
400         if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
401     }
402     else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
403     return old_count;
404 }
405
406 /* resume a thread */
407 static int resume_thread( struct thread *thread )
408 {
409     int old_count = thread->suspend;
410     if (thread->suspend > 0)
411     {
412         if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
413     }
414     return old_count;
415 }
416
417 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
418 int add_queue( struct object *obj, struct wait_queue_entry *entry )
419 {
420     grab_object( obj );
421     entry->obj = obj;
422     list_add_tail( &obj->wait_queue, &entry->entry );
423     return 1;
424 }
425
426 /* remove a thread from an object wait queue */
427 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
428 {
429     list_remove( &entry->entry );
430     release_object( obj );
431 }
432
433 /* finish waiting */
434 static void end_wait( struct thread *thread )
435 {
436     struct thread_wait *wait = thread->wait;
437     struct wait_queue_entry *entry;
438     int i;
439
440     assert( wait );
441     for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
442         entry->obj->ops->remove_queue( entry->obj, entry );
443     if (wait->user) remove_timeout_user( wait->user );
444     thread->wait = wait->next;
445     free( wait );
446 }
447
448 /* build the thread wait structure */
449 static int wait_on( int count, struct object *objects[], int flags, const abs_time_t *timeout )
450 {
451     struct thread_wait *wait;
452     struct wait_queue_entry *entry;
453     int i;
454
455     if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
456     wait->next    = current->wait;
457     wait->thread  = current;
458     wait->count   = count;
459     wait->flags   = flags;
460     wait->user    = NULL;
461     current->wait = wait;
462     if (flags & SELECT_TIMEOUT)
463     {
464         wait->timeout.tv_sec  = timeout->sec;
465         wait->timeout.tv_usec = timeout->usec;
466     }
467
468     for (i = 0, entry = wait->queues; i < count; i++, entry++)
469     {
470         struct object *obj = objects[i];
471         entry->thread = current;
472         if (!obj->ops->add_queue( obj, entry ))
473         {
474             wait->count = i;
475             end_wait( current );
476             return 0;
477         }
478     }
479     return 1;
480 }
481
482 /* check if the thread waiting condition is satisfied */
483 static int check_wait( struct thread *thread )
484 {
485     int i, signaled;
486     struct thread_wait *wait = thread->wait;
487     struct wait_queue_entry *entry = wait->queues;
488
489     /* Suspended threads may not acquire locks, but they can run system APCs */
490     if (thread->process->suspend + thread->suspend > 0)
491     {
492         if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
493             return STATUS_USER_APC;
494         return -1;
495     }
496
497     assert( wait );
498     if (wait->flags & SELECT_ALL)
499     {
500         int not_ok = 0;
501         /* Note: we must check them all anyway, as some objects may
502          * want to do something when signaled, even if others are not */
503         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
504             not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
505         if (not_ok) goto other_checks;
506         /* Wait satisfied: tell it to all objects */
507         signaled = 0;
508         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
509             if (entry->obj->ops->satisfied( entry->obj, thread ))
510                 signaled = STATUS_ABANDONED_WAIT_0;
511         return signaled;
512     }
513     else
514     {
515         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
516         {
517             if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
518             /* Wait satisfied: tell it to the object */
519             signaled = i;
520             if (entry->obj->ops->satisfied( entry->obj, thread ))
521                 signaled = i + STATUS_ABANDONED_WAIT_0;
522             return signaled;
523         }
524     }
525
526  other_checks:
527     if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty(&thread->system_apc)) return STATUS_USER_APC;
528     if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
529     if (wait->flags & SELECT_TIMEOUT)
530     {
531         if (!time_before( &current_time, &wait->timeout )) return STATUS_TIMEOUT;
532     }
533     return -1;
534 }
535
536 /* send the wakeup signal to a thread */
537 static int send_thread_wakeup( struct thread *thread, void *cookie, int signaled )
538 {
539     struct wake_up_reply reply;
540     int ret;
541
542     reply.cookie   = cookie;
543     reply.signaled = signaled;
544     if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
545         return 0;
546     if (ret >= 0)
547         fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
548     else if (errno == EPIPE)
549         kill_thread( thread, 0 );  /* normal death */
550     else
551         fatal_protocol_perror( thread, "write" );
552     return -1;
553 }
554
555 /* attempt to wake up a thread */
556 /* return >0 if OK, 0 if the wait condition is still not satisfied */
557 int wake_thread( struct thread *thread )
558 {
559     int signaled, count;
560     void *cookie;
561
562     for (count = 0; thread->wait; count++)
563     {
564         if ((signaled = check_wait( thread )) == -1) break;
565
566         cookie = thread->wait->cookie;
567         if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
568                                   thread->id, signaled, cookie );
569         end_wait( thread );
570         if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
571             break;
572     }
573     return count;
574 }
575
576 /* thread wait timeout */
577 static void thread_timeout( void *ptr )
578 {
579     struct thread_wait *wait = ptr;
580     struct thread *thread = wait->thread;
581     void *cookie = wait->cookie;
582
583     wait->user = NULL;
584     if (thread->wait != wait) return; /* not the top-level wait, ignore it */
585     if (thread->suspend + thread->process->suspend > 0) return;  /* suspended, ignore it */
586
587     if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
588                               thread->id, (int)STATUS_TIMEOUT, cookie );
589     end_wait( thread );
590     if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
591     /* check if other objects have become signaled in the meantime */
592     wake_thread( thread );
593 }
594
595 /* try signaling an event flag, a semaphore or a mutex */
596 static int signal_object( obj_handle_t handle )
597 {
598     struct object *obj;
599     int ret = 0;
600
601     obj = get_handle_obj( current->process, handle, 0, NULL );
602     if (obj)
603     {
604         ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
605         release_object( obj );
606     }
607     return ret;
608 }
609
610 /* select on a list of handles */
611 static void select_on( int count, void *cookie, const obj_handle_t *handles,
612                        int flags, const abs_time_t *timeout, obj_handle_t signal_obj )
613 {
614     int ret, i;
615     struct object *objects[MAXIMUM_WAIT_OBJECTS];
616
617     if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
618     {
619         set_error( STATUS_INVALID_PARAMETER );
620         return;
621     }
622     for (i = 0; i < count; i++)
623     {
624         if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
625             break;
626     }
627
628     if (i < count) goto done;
629     if (!wait_on( count, objects, flags, timeout )) goto done;
630
631     /* signal the object */
632     if (signal_obj)
633     {
634         if (!signal_object( signal_obj ))
635         {
636             end_wait( current );
637             goto done;
638         }
639         /* check if we woke ourselves up */
640         if (!current->wait) goto done;
641     }
642
643     if ((ret = check_wait( current )) != -1)
644     {
645         /* condition is already satisfied */
646         end_wait( current );
647         set_error( ret );
648         goto done;
649     }
650
651     /* now we need to wait */
652     if (flags & SELECT_TIMEOUT)
653     {
654         if (!(current->wait->user = add_timeout_user( &current->wait->timeout,
655                                                       thread_timeout, current->wait )))
656         {
657             end_wait( current );
658             goto done;
659         }
660     }
661     current->wait->cookie = cookie;
662     set_error( STATUS_PENDING );
663
664 done:
665     while (--i >= 0) release_object( objects[i] );
666 }
667
668 /* attempt to wake threads sleeping on the object wait queue */
669 void wake_up( struct object *obj, int max )
670 {
671     struct list *ptr, *next;
672
673     LIST_FOR_EACH_SAFE( ptr, next, &obj->wait_queue )
674     {
675         struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
676         if (wake_thread( entry->thread ))
677         {
678             if (max && !--max) break;
679         }
680     }
681 }
682
683 /* return the apc queue to use for a given apc type */
684 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
685 {
686     switch(type)
687     {
688     case APC_NONE:
689     case APC_USER:
690     case APC_TIMER:
691         return &thread->user_apc;
692     default:
693         return &thread->system_apc;
694     }
695 }
696
697 /* queue an existing APC to a given thread */
698 static int queue_apc( struct process *process, struct thread *thread, struct thread_apc *apc )
699 {
700     struct list *queue;
701
702     if (!thread)  /* find a suitable thread inside the process */
703     {
704         struct thread *candidate;
705
706         /* first try to find a waiting thread */
707         LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
708         {
709             if (candidate->state == TERMINATED) continue;
710             if (process->suspend || candidate->suspend ||
711                 (candidate->wait && (candidate->wait->flags & SELECT_INTERRUPTIBLE)))
712             {
713                 thread = candidate;
714                 break;
715             }
716         }
717         if (!thread)
718         {
719             /* then use the first one that accepts a signal */
720             LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
721             {
722                 if (send_thread_signal( candidate, SIGUSR1 ))
723                 {
724                     thread = candidate;
725                     break;
726                 }
727             }
728         }
729         if (!thread) return 0;  /* nothing found */
730     }
731     else
732     {
733         if (thread->state == TERMINATED) return 0;
734         /* cancel a possible previous APC with the same owner */
735         if (apc->owner) thread_cancel_apc( thread, apc->owner, apc->call.type );
736     }
737
738     queue = get_apc_queue( thread, apc->call.type );
739     grab_object( apc );
740     list_add_tail( queue, &apc->entry );
741     if (!list_prev( queue, &apc->entry ))  /* first one */
742         wake_thread( thread );
743
744     return 1;
745 }
746
747 /* queue an async procedure call */
748 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
749 {
750     struct thread_apc *apc;
751     int ret = 0;
752
753     if ((apc = create_apc( owner, call_data )))
754     {
755         ret = queue_apc( NULL, thread, apc );
756         release_object( apc );
757     }
758     return ret;
759 }
760
761 /* cancel the async procedure call owned by a specific object */
762 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
763 {
764     struct thread_apc *apc;
765     struct list *queue = get_apc_queue( thread, type );
766
767     LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
768     {
769         if (apc->owner != owner) continue;
770         list_remove( &apc->entry );
771         apc->executed = 1;
772         wake_up( &apc->obj, 0 );
773         release_object( apc );
774         return;
775     }
776 }
777
778 /* remove the head apc from the queue; the returned object must be released by the caller */
779 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
780 {
781     struct thread_apc *apc = NULL;
782     struct list *ptr = list_head( &thread->system_apc );
783
784     if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
785     if (ptr)
786     {
787         apc = LIST_ENTRY( ptr, struct thread_apc, entry );
788         list_remove( ptr );
789     }
790     return apc;
791 }
792
793 /* clear an APC queue, cancelling all the APCs on it */
794 static void clear_apc_queue( struct list *queue )
795 {
796     struct list *ptr;
797
798     while ((ptr = list_head( queue )))
799     {
800         struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
801         list_remove( &apc->entry );
802         apc->executed = 1;
803         wake_up( &apc->obj, 0 );
804         release_object( apc );
805     }
806 }
807
808 /* add an fd to the inflight list */
809 /* return list index, or -1 on error */
810 int thread_add_inflight_fd( struct thread *thread, int client, int server )
811 {
812     int i;
813
814     if (server == -1) return -1;
815     if (client == -1)
816     {
817         close( server );
818         return -1;
819     }
820
821     /* first check if we already have an entry for this fd */
822     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
823         if (thread->inflight[i].client == client)
824         {
825             close( thread->inflight[i].server );
826             thread->inflight[i].server = server;
827             return i;
828         }
829
830     /* now find a free spot to store it */
831     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
832         if (thread->inflight[i].client == -1)
833         {
834             thread->inflight[i].client = client;
835             thread->inflight[i].server = server;
836             return i;
837         }
838     return -1;
839 }
840
841 /* get an inflight fd and purge it from the list */
842 /* the fd must be closed when no longer used */
843 int thread_get_inflight_fd( struct thread *thread, int client )
844 {
845     int i, ret;
846
847     if (client == -1) return -1;
848
849     do
850     {
851         for (i = 0; i < MAX_INFLIGHT_FDS; i++)
852         {
853             if (thread->inflight[i].client == client)
854             {
855                 ret = thread->inflight[i].server;
856                 thread->inflight[i].server = thread->inflight[i].client = -1;
857                 return ret;
858             }
859         }
860     } while (!receive_fd( thread->process ));  /* in case it is still in the socket buffer */
861     return -1;
862 }
863
864 /* kill a thread on the spot */
865 void kill_thread( struct thread *thread, int violent_death )
866 {
867     if (thread->state == TERMINATED) return;  /* already killed */
868     thread->state = TERMINATED;
869     thread->exit_time = current_time;
870     if (current == thread) current = NULL;
871     if (debug_level)
872         fprintf( stderr,"%04x: *killed* exit_code=%d\n",
873                  thread->id, thread->exit_code );
874     if (thread->wait)
875     {
876         while (thread->wait) end_wait( thread );
877         send_thread_wakeup( thread, NULL, STATUS_PENDING );
878         /* if it is waiting on the socket, we don't need to send a SIGTERM */
879         violent_death = 0;
880     }
881     kill_console_processes( thread, 0 );
882     debug_exit_thread( thread );
883     abandon_mutexes( thread );
884     wake_up( &thread->obj, 0 );
885     if (violent_death) send_thread_signal( thread, SIGTERM );
886     cleanup_thread( thread );
887     remove_process_thread( thread->process, thread );
888     release_object( thread );
889 }
890
891 /* trigger a breakpoint event in a given thread */
892 void break_thread( struct thread *thread )
893 {
894     struct debug_event_exception data;
895
896     assert( thread->context );
897
898     data.record.ExceptionCode    = STATUS_BREAKPOINT;
899     data.record.ExceptionFlags   = EXCEPTION_CONTINUABLE;
900     data.record.ExceptionRecord  = NULL;
901     data.record.ExceptionAddress = get_context_ip( thread->context );
902     data.record.NumberParameters = 0;
903     data.first = 1;
904     generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
905     thread->debug_break = 0;
906 }
907
908 /* take a snapshot of currently running threads */
909 struct thread_snapshot *thread_snap( int *count )
910 {
911     struct thread_snapshot *snapshot, *ptr;
912     struct thread *thread;
913     int total = 0;
914
915     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
916         if (thread->state != TERMINATED) total++;
917     if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
918     ptr = snapshot;
919     LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
920     {
921         if (thread->state == TERMINATED) continue;
922         ptr->thread   = thread;
923         ptr->count    = thread->obj.refcount;
924         ptr->priority = thread->priority;
925         grab_object( thread );
926         ptr++;
927     }
928     *count = total;
929     return snapshot;
930 }
931
932 /* gets the current impersonation token */
933 struct token *thread_get_impersonation_token( struct thread *thread )
934 {
935     if (thread->token)
936         return thread->token;
937     else
938         return thread->process->token;
939 }
940
941 /* create a new thread */
942 DECL_HANDLER(new_thread)
943 {
944     struct thread *thread;
945     int request_fd = thread_get_inflight_fd( current, req->request_fd );
946
947     if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
948     {
949         if (request_fd != -1) close( request_fd );
950         set_error( STATUS_INVALID_HANDLE );
951         return;
952     }
953
954     if ((thread = create_thread( request_fd, current->process )))
955     {
956         if (req->suspend) thread->suspend++;
957         reply->tid = get_thread_id( thread );
958         if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
959         {
960             /* thread object will be released when the thread gets killed */
961             return;
962         }
963         kill_thread( thread, 1 );
964     }
965 }
966
967 /* initialize a new thread */
968 DECL_HANDLER(init_thread)
969 {
970     struct process *process = current->process;
971     int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
972     int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
973
974     if (current->reply_fd)  /* already initialised */
975     {
976         set_error( STATUS_INVALID_PARAMETER );
977         goto error;
978     }
979
980     if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
981
982     current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj );
983     reply_fd = -1;
984     if (!current->reply_fd) goto error;
985
986     if (wait_fd == -1)
987     {
988         set_error( STATUS_TOO_MANY_OPENED_FILES );  /* most likely reason */
989         return;
990     }
991     if (!(current->wait_fd  = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj )))
992         return;
993
994     if (!is_valid_address(req->teb) || !is_valid_address(req->peb) || !is_valid_address(req->ldt_copy))
995     {
996         set_error( STATUS_INVALID_PARAMETER );
997         return;
998     }
999
1000     current->unix_pid = req->unix_pid;
1001     current->unix_tid = req->unix_tid;
1002     current->teb      = req->teb;
1003
1004     if (!process->peb)  /* first thread, initialize the process too */
1005     {
1006         process->unix_pid = current->unix_pid;
1007         process->peb      = req->peb;
1008         process->ldt_copy = req->ldt_copy;
1009         reply->info_size  = init_process( current );
1010     }
1011     else
1012     {
1013         if (process->unix_pid != current->unix_pid)
1014             process->unix_pid = -1;  /* can happen with linuxthreads */
1015         if (current->suspend + process->suspend > 0) stop_thread( current );
1016         generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
1017     }
1018     debug_level = max( debug_level, req->debug_level );
1019
1020     reply->pid     = get_process_id( process );
1021     reply->tid     = get_thread_id( current );
1022     reply->version = SERVER_PROTOCOL_VERSION;
1023     reply->server_start.sec  = server_start_time.tv_sec;
1024     reply->server_start.usec = server_start_time.tv_usec;
1025     return;
1026
1027  error:
1028     if (reply_fd != -1) close( reply_fd );
1029     if (wait_fd != -1) close( wait_fd );
1030 }
1031
1032 /* terminate a thread */
1033 DECL_HANDLER(terminate_thread)
1034 {
1035     struct thread *thread;
1036
1037     reply->self = 0;
1038     reply->last = 0;
1039     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1040     {
1041         thread->exit_code = req->exit_code;
1042         if (thread != current) kill_thread( thread, 1 );
1043         else
1044         {
1045             reply->self = 1;
1046             reply->last = (thread->process->running_threads == 1);
1047         }
1048         release_object( thread );
1049     }
1050 }
1051
1052 /* open a handle to a thread */
1053 DECL_HANDLER(open_thread)
1054 {
1055     struct thread *thread = get_thread_from_id( req->tid );
1056
1057     reply->handle = 0;
1058     if (thread)
1059     {
1060         reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1061         release_object( thread );
1062     }
1063 }
1064
1065 /* fetch information about a thread */
1066 DECL_HANDLER(get_thread_info)
1067 {
1068     struct thread *thread;
1069     obj_handle_t handle = req->handle;
1070
1071     if (!handle) thread = get_thread_from_id( req->tid_in );
1072     else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1073
1074     if (thread)
1075     {
1076         reply->pid            = get_process_id( thread->process );
1077         reply->tid            = get_thread_id( thread );
1078         reply->teb            = thread->teb;
1079         reply->exit_code      = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1080         reply->priority       = thread->priority;
1081         reply->affinity       = thread->affinity;
1082         reply->creation_time.sec  = thread->creation_time.tv_sec;
1083         reply->creation_time.usec = thread->creation_time.tv_usec;
1084         reply->exit_time.sec  = thread->exit_time.tv_sec;
1085         reply->exit_time.usec = thread->exit_time.tv_usec;
1086         reply->last           = thread->process->running_threads == 1;
1087
1088         release_object( thread );
1089     }
1090 }
1091
1092 /* set information about a thread */
1093 DECL_HANDLER(set_thread_info)
1094 {
1095     struct thread *thread;
1096
1097     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1098     {
1099         set_thread_info( thread, req );
1100         release_object( thread );
1101     }
1102 }
1103
1104 /* suspend a thread */
1105 DECL_HANDLER(suspend_thread)
1106 {
1107     struct thread *thread;
1108
1109     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1110     {
1111         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1112         else reply->count = suspend_thread( thread );
1113         release_object( thread );
1114     }
1115 }
1116
1117 /* resume a thread */
1118 DECL_HANDLER(resume_thread)
1119 {
1120     struct thread *thread;
1121
1122     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1123     {
1124         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1125         else reply->count = resume_thread( thread );
1126         release_object( thread );
1127     }
1128 }
1129
1130 /* select on a handle list */
1131 DECL_HANDLER(select)
1132 {
1133     int count = get_req_data_size() / sizeof(obj_handle_t);
1134     select_on( count, req->cookie, get_req_data(), req->flags, &req->timeout, req->signal );
1135 }
1136
1137 /* queue an APC for a thread or process */
1138 DECL_HANDLER(queue_apc)
1139 {
1140     struct thread *thread;
1141     struct process *process;
1142     struct thread_apc *apc;
1143
1144     if (!(apc = create_apc( NULL, &req->call ))) return;
1145
1146     switch (apc->call.type)
1147     {
1148     case APC_NONE:
1149     case APC_USER:
1150         if ((thread = get_thread_from_handle( req->thread, THREAD_SET_CONTEXT )))
1151         {
1152             if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1153             release_object( thread );
1154         }
1155         break;
1156     case APC_VIRTUAL_ALLOC:
1157     case APC_VIRTUAL_FREE:
1158         if ((process = get_process_from_handle( req->process, PROCESS_VM_OPERATION )))
1159         {
1160             obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1161             if (handle)
1162             {
1163                 if (queue_apc( process, NULL, apc )) reply->handle = handle;
1164                 else
1165                 {
1166                     close_handle( current->process, handle );
1167                     set_error( STATUS_PROCESS_IS_TERMINATING );
1168                 }
1169             }
1170             release_object( process );
1171         }
1172         break;
1173     default:
1174         set_error( STATUS_INVALID_PARAMETER );
1175         break;
1176     }
1177     release_object( apc );
1178 }
1179
1180 /* get next APC to call */
1181 DECL_HANDLER(get_apc)
1182 {
1183     struct thread_apc *apc;
1184     int system_only = !req->alertable;
1185
1186     if (req->prev)
1187     {
1188         if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev,
1189                                                          0, &thread_apc_ops ))) return;
1190         apc->result = req->result;
1191         apc->executed = 1;
1192         wake_up( &apc->obj, 0 );
1193         close_handle( current->process, req->prev );
1194         release_object( apc );
1195     }
1196
1197     if (current->suspend + current->process->suspend > 0) system_only = 1;
1198
1199     for (;;)
1200     {
1201         if (!(apc = thread_dequeue_apc( current, system_only )))
1202         {
1203             /* no more APCs */
1204             set_error( STATUS_PENDING );
1205             return;
1206         }
1207         /* Optimization: ignore APC_NONE calls, they are only used to
1208          * wake up a thread, but since we got here the thread woke up already.
1209          */
1210         if (apc->call.type != APC_NONE) break;
1211         apc->executed = 1;
1212         wake_up( &apc->obj, 0 );
1213         release_object( apc );
1214     }
1215
1216     if ((reply->handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1217         reply->call = apc->call;
1218     release_object( apc );
1219 }
1220
1221 /* Get the result of an APC call */
1222 DECL_HANDLER(get_apc_result)
1223 {
1224     struct thread_apc *apc;
1225
1226     if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1227                                                      0, &thread_apc_ops ))) return;
1228     if (!apc->executed) set_error( STATUS_PENDING );
1229     else
1230     {
1231         reply->result = apc->result;
1232         /* close the handle directly to avoid an extra round-trip */
1233         close_handle( current->process, req->handle );
1234     }
1235     release_object( apc );
1236 }
1237
1238 /* retrieve the current context of a thread */
1239 DECL_HANDLER(get_thread_context)
1240 {
1241     struct thread *thread;
1242     CONTEXT *context;
1243
1244     if (get_reply_max_size() < sizeof(CONTEXT))
1245     {
1246         set_error( STATUS_INVALID_PARAMETER );
1247         return;
1248     }
1249     if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1250
1251     if (req->suspend)
1252     {
1253         if (thread != current || !thread->suspend_context)
1254         {
1255             /* not suspended, shouldn't happen */
1256             set_error( STATUS_INVALID_PARAMETER );
1257         }
1258         else
1259         {
1260             if (thread->context == thread->suspend_context) thread->context = NULL;
1261             set_reply_data_ptr( thread->suspend_context, sizeof(CONTEXT) );
1262             thread->suspend_context = NULL;
1263         }
1264     }
1265     else if (thread != current && !thread->context)
1266     {
1267         /* thread is not suspended, retry (if it's still running) */
1268         if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1269         else set_error( STATUS_PENDING );
1270     }
1271     else if ((context = set_reply_data_size( sizeof(CONTEXT) )))
1272     {
1273         unsigned int flags = get_context_system_regs( req->flags );
1274
1275         memset( context, 0, sizeof(CONTEXT) );
1276         context->ContextFlags = get_context_cpu_flag();
1277         if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1278         if (flags) get_thread_context( thread, context, flags );
1279     }
1280     reply->self = (thread == current);
1281     release_object( thread );
1282 }
1283
1284 /* set the current context of a thread */
1285 DECL_HANDLER(set_thread_context)
1286 {
1287     struct thread *thread;
1288
1289     if (get_req_data_size() < sizeof(CONTEXT))
1290     {
1291         set_error( STATUS_INVALID_PARAMETER );
1292         return;
1293     }
1294     if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1295
1296     if (req->suspend)
1297     {
1298         if (thread != current || thread->context)
1299         {
1300             /* nested suspend or exception, shouldn't happen */
1301             set_error( STATUS_INVALID_PARAMETER );
1302         }
1303         else if ((thread->suspend_context = mem_alloc( sizeof(CONTEXT) )))
1304         {
1305             memcpy( thread->suspend_context, get_req_data(), sizeof(CONTEXT) );
1306             thread->context = thread->suspend_context;
1307             if (thread->debug_break) break_thread( thread );
1308         }
1309     }
1310     else if (thread != current && !thread->context)
1311     {
1312         /* thread is not suspended, retry (if it's still running) */
1313         if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1314         else set_error( STATUS_PENDING );
1315     }
1316     else
1317     {
1318         const CONTEXT *context = get_req_data();
1319         unsigned int flags = get_context_system_regs( req->flags );
1320
1321         if (flags) set_thread_context( thread, context, flags );
1322         if (thread->context && !get_error())
1323             copy_context( thread->context, context, req->flags & ~flags );
1324     }
1325     reply->self = (thread == current);
1326     release_object( thread );
1327 }
1328
1329 /* fetch a selector entry for a thread */
1330 DECL_HANDLER(get_selector_entry)
1331 {
1332     struct thread *thread;
1333     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1334     {
1335         get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1336         release_object( thread );
1337     }
1338 }