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