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