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