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