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