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