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