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