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