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