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