Reverse the order for deleting the items in resetcontent to correctly
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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
36 #include "windef.h"
37 #include "winbase.h"
38
39 #include "file.h"
40 #include "handle.h"
41 #include "process.h"
42 #include "thread.h"
43 #include "request.h"
44 #include "user.h"
45
46
47 /* thread queues */
48
49 struct thread_wait
50 {
51     struct thread_wait     *next;       /* next wait structure for this thread */
52     struct thread          *thread;     /* owner thread */
53     int                     count;      /* count of objects */
54     int                     flags;
55     void                   *cookie;     /* magic cookie to return to client */
56     struct timeval          timeout;
57     struct timeout_user    *user;
58     struct wait_queue_entry queues[1];
59 };
60
61 /* asynchronous procedure calls */
62
63 struct thread_apc
64 {
65     struct thread_apc  *next;     /* queue linked list */
66     struct thread_apc  *prev;
67     struct object      *owner;    /* object that queued this apc */
68     void               *func;     /* function to call in client */
69     enum apc_type       type;     /* type of apc function */
70     int                 nb_args;  /* number of arguments */
71     void               *arg1;     /* function arguments */
72     void               *arg2;
73     void               *arg3;
74 };
75
76
77 /* thread operations */
78
79 static void dump_thread( struct object *obj, int verbose );
80 static int thread_signaled( struct object *obj, struct thread *thread );
81 static void thread_poll_event( struct fd *fd, int event );
82 static void destroy_thread( struct object *obj );
83 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only );
84
85 static const struct object_ops thread_ops =
86 {
87     sizeof(struct thread),      /* size */
88     dump_thread,                /* dump */
89     add_queue,                  /* add_queue */
90     remove_queue,               /* remove_queue */
91     thread_signaled,            /* signaled */
92     no_satisfied,               /* satisfied */
93     no_get_fd,                  /* get_fd */
94     destroy_thread              /* destroy */
95 };
96
97 static const struct fd_ops thread_fd_ops =
98 {
99     NULL,                       /* get_poll_events */
100     thread_poll_event,          /* poll_event */
101     no_flush,                   /* flush */
102     no_get_file_info,           /* get_file_info */
103     no_queue_async,             /* queue_async */
104     no_cancel_async             /* cancel_async */
105 };
106
107 static struct thread *first_thread;
108 static struct thread *booting_thread;
109
110 /* initialize the structure for a newly allocated thread */
111 inline static void init_thread_structure( struct thread *thread )
112 {
113     int i;
114
115     thread->unix_pid        = -1;  /* not known yet */
116     thread->unix_tid        = -1;  /* not known yet */
117     thread->context         = NULL;
118     thread->teb             = NULL;
119     thread->mutex           = NULL;
120     thread->debug_ctx       = NULL;
121     thread->debug_event     = NULL;
122     thread->queue           = NULL;
123     thread->wait            = NULL;
124     thread->system_apc.head = NULL;
125     thread->system_apc.tail = NULL;
126     thread->user_apc.head   = NULL;
127     thread->user_apc.tail   = NULL;
128     thread->error           = 0;
129     thread->req_data        = NULL;
130     thread->req_toread      = 0;
131     thread->reply_data      = NULL;
132     thread->reply_towrite   = 0;
133     thread->request_fd      = NULL;
134     thread->reply_fd        = NULL;
135     thread->wait_fd         = NULL;
136     thread->state           = RUNNING;
137     thread->attached        = 0;
138     thread->exit_code       = 0;
139     thread->next            = NULL;
140     thread->prev            = NULL;
141     thread->priority        = THREAD_PRIORITY_NORMAL;
142     thread->affinity        = 1;
143     thread->suspend         = 0;
144     thread->creation_time   = time(NULL);
145     thread->exit_time       = 0;
146
147     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
148         thread->inflight[i].server = thread->inflight[i].client = -1;
149 }
150
151 /* create a new thread */
152 struct thread *create_thread( int fd, struct process *process )
153 {
154     struct thread *thread;
155
156     if (!(thread = alloc_object( &thread_ops ))) return NULL;
157
158     init_thread_structure( thread );
159
160     thread->process = (struct process *)grab_object( process );
161     if (!current) current = thread;
162
163     if (!booting_thread)  /* first thread ever */
164     {
165         booting_thread = thread;
166         lock_master_socket(1);
167     }
168
169     if ((thread->next = first_thread) != NULL) thread->next->prev = thread;
170     first_thread = thread;
171
172     if (!(thread->id = alloc_ptid( thread )))
173     {
174         release_object( thread );
175         return NULL;
176     }
177     if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj )))
178     {
179         release_object( thread );
180         return NULL;
181     }
182
183     thread->token = (struct token *) grab_object( process->token );
184
185     set_fd_events( thread->request_fd, POLLIN );  /* start listening to events */
186     add_process_thread( thread->process, thread );
187     return thread;
188 }
189
190 /* handle a client event */
191 static void thread_poll_event( struct fd *fd, int event )
192 {
193     struct thread *thread = get_fd_user( fd );
194     assert( thread->obj.ops == &thread_ops );
195
196     if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
197     else if (event & POLLIN) read_request( thread );
198     else if (event & POLLOUT) write_reply( thread );
199 }
200
201 /* cleanup everything that is no longer needed by a dead thread */
202 /* used by destroy_thread and kill_thread */
203 static void cleanup_thread( struct thread *thread )
204 {
205     int i;
206     struct thread_apc *apc;
207
208     while ((apc = thread_dequeue_apc( thread, 0 ))) free( apc );
209     if (thread->req_data) free( thread->req_data );
210     if (thread->reply_data) free( thread->reply_data );
211     if (thread->request_fd) release_object( thread->request_fd );
212     if (thread->reply_fd) release_object( thread->reply_fd );
213     if (thread->wait_fd) release_object( thread->wait_fd );
214     free_msg_queue( thread );
215     cleanup_clipboard_thread(thread);
216     destroy_thread_windows( thread );
217     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
218     {
219         if (thread->inflight[i].client != -1)
220         {
221             close( thread->inflight[i].server );
222             thread->inflight[i].client = thread->inflight[i].server = -1;
223         }
224     }
225     thread->req_data = NULL;
226     thread->reply_data = NULL;
227     thread->request_fd = NULL;
228     thread->reply_fd = NULL;
229     thread->wait_fd = NULL;
230
231     if (thread == booting_thread)  /* killing booting thread */
232     {
233         booting_thread = NULL;
234         lock_master_socket(0);
235     }
236 }
237
238 /* destroy a thread when its refcount is 0 */
239 static void destroy_thread( struct object *obj )
240 {
241     struct thread_apc *apc;
242     struct thread *thread = (struct thread *)obj;
243     assert( obj->ops == &thread_ops );
244
245     assert( !thread->debug_ctx );  /* cannot still be debugging something */
246     if (thread->next) thread->next->prev = thread->prev;
247     if (thread->prev) thread->prev->next = thread->next;
248     else first_thread = thread->next;
249     while ((apc = thread_dequeue_apc( thread, 0 ))) free( apc );
250     cleanup_thread( thread );
251     release_object( thread->process );
252     if (thread->id) free_ptid( thread->id );
253     if (thread->token) release_object( thread->token );
254 }
255
256 /* dump a thread on stdout for debugging purposes */
257 static void dump_thread( struct object *obj, int verbose )
258 {
259     struct thread *thread = (struct thread *)obj;
260     assert( obj->ops == &thread_ops );
261
262     fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d teb=%p state=%d\n",
263              thread->id, thread->unix_pid, thread->unix_tid, thread->teb, thread->state );
264 }
265
266 static int thread_signaled( struct object *obj, struct thread *thread )
267 {
268     struct thread *mythread = (struct thread *)obj;
269     return (mythread->state == TERMINATED);
270 }
271
272 /* get a thread pointer from a thread id (and increment the refcount) */
273 struct thread *get_thread_from_id( thread_id_t id )
274 {
275     struct object *obj = get_ptid_entry( id );
276
277     if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
278     set_win32_error( ERROR_INVALID_THREAD_ID );
279     return NULL;
280 }
281
282 /* get a thread from a handle (and increment the refcount) */
283 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
284 {
285     return (struct thread *)get_handle_obj( current->process, handle,
286                                             access, &thread_ops );
287 }
288
289 /* find a thread from a Unix pid */
290 struct thread *get_thread_from_pid( int pid )
291 {
292     struct thread *t;
293
294     for (t = first_thread; t; t = t->next) if (t->unix_tid == pid) return t;
295     for (t = first_thread; t; t = t->next) if (t->unix_pid == pid) return t;
296     return NULL;
297 }
298
299 /* set all information about a thread */
300 static void set_thread_info( struct thread *thread,
301                              const struct set_thread_info_request *req )
302 {
303     if (req->mask & SET_THREAD_INFO_PRIORITY)
304         thread->priority = req->priority;
305     if (req->mask & SET_THREAD_INFO_AFFINITY)
306     {
307         if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
308         else thread->affinity = req->affinity;
309     }
310 }
311
312 /* stop a thread (at the Unix level) */
313 void stop_thread( struct thread *thread )
314 {
315     /* can't stop a thread while initialisation is in progress */
316     if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
317 }
318
319 /* suspend a thread */
320 static int suspend_thread( struct thread *thread )
321 {
322     int old_count = thread->suspend;
323     if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
324     {
325         if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
326     }
327     else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
328     return old_count;
329 }
330
331 /* resume a thread */
332 static int resume_thread( struct thread *thread )
333 {
334     int old_count = thread->suspend;
335     if (thread->suspend > 0)
336     {
337         if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
338     }
339     return old_count;
340 }
341
342 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
343 int add_queue( struct object *obj, struct wait_queue_entry *entry )
344 {
345     grab_object( obj );
346     entry->obj    = obj;
347     entry->prev   = obj->tail;
348     entry->next   = NULL;
349     if (obj->tail) obj->tail->next = entry;
350     else obj->head = entry;
351     obj->tail = entry;
352     return 1;
353 }
354
355 /* remove a thread from an object wait queue */
356 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
357 {
358     if (entry->next) entry->next->prev = entry->prev;
359     else obj->tail = entry->prev;
360     if (entry->prev) entry->prev->next = entry->next;
361     else obj->head = entry->next;
362     release_object( obj );
363 }
364
365 /* finish waiting */
366 static void end_wait( struct thread *thread )
367 {
368     struct thread_wait *wait = thread->wait;
369     struct wait_queue_entry *entry;
370     int i;
371
372     assert( wait );
373     for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
374         entry->obj->ops->remove_queue( entry->obj, entry );
375     if (wait->user) remove_timeout_user( wait->user );
376     thread->wait = wait->next;
377     free( wait );
378 }
379
380 /* build the thread wait structure */
381 static int wait_on( int count, struct object *objects[], int flags, const abs_time_t *timeout )
382 {
383     struct thread_wait *wait;
384     struct wait_queue_entry *entry;
385     int i;
386
387     if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
388     wait->next    = current->wait;
389     wait->thread  = current;
390     wait->count   = count;
391     wait->flags   = flags;
392     wait->user    = NULL;
393     current->wait = wait;
394     if (flags & SELECT_TIMEOUT)
395     {
396         wait->timeout.tv_sec  = timeout->sec;
397         wait->timeout.tv_usec = timeout->usec;
398     }
399
400     for (i = 0, entry = wait->queues; i < count; i++, entry++)
401     {
402         struct object *obj = objects[i];
403         entry->thread = current;
404         if (!obj->ops->add_queue( obj, entry ))
405         {
406             wait->count = i;
407             end_wait( current );
408             return 0;
409         }
410     }
411     return 1;
412 }
413
414 /* check if the thread waiting condition is satisfied */
415 static int check_wait( struct thread *thread )
416 {
417     int i, signaled;
418     struct thread_wait *wait = thread->wait;
419     struct wait_queue_entry *entry = wait->queues;
420
421     /* Suspended threads may not acquire locks */
422     if( thread->process->suspend + thread->suspend > 0 ) return -1;
423
424     assert( wait );
425     if (wait->flags & SELECT_ALL)
426     {
427         int not_ok = 0;
428         /* Note: we must check them all anyway, as some objects may
429          * want to do something when signaled, even if others are not */
430         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
431             not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
432         if (not_ok) goto other_checks;
433         /* Wait satisfied: tell it to all objects */
434         signaled = 0;
435         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
436             if (entry->obj->ops->satisfied( entry->obj, thread ))
437                 signaled = STATUS_ABANDONED_WAIT_0;
438         return signaled;
439     }
440     else
441     {
442         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
443         {
444             if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
445             /* Wait satisfied: tell it to the object */
446             signaled = i;
447             if (entry->obj->ops->satisfied( entry->obj, thread ))
448                 signaled = i + STATUS_ABANDONED_WAIT_0;
449             return signaled;
450         }
451     }
452
453  other_checks:
454     if ((wait->flags & SELECT_INTERRUPTIBLE) && thread->system_apc.head) return STATUS_USER_APC;
455     if ((wait->flags & SELECT_ALERTABLE) && thread->user_apc.head) return STATUS_USER_APC;
456     if (wait->flags & SELECT_TIMEOUT)
457     {
458         struct timeval now;
459         gettimeofday( &now, NULL );
460         if (!time_before( &now, &wait->timeout )) return STATUS_TIMEOUT;
461     }
462     return -1;
463 }
464
465 /* send the wakeup signal to a thread */
466 static int send_thread_wakeup( struct thread *thread, void *cookie, int signaled )
467 {
468     struct wake_up_reply reply;
469     int ret;
470
471     reply.cookie   = cookie;
472     reply.signaled = signaled;
473     if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
474         return 0;
475     if (ret >= 0)
476         fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
477     else if (errno == EPIPE)
478         kill_thread( thread, 0 );  /* normal death */
479     else
480         fatal_protocol_perror( thread, "write" );
481     return -1;
482 }
483
484 /* attempt to wake up a thread */
485 /* return >0 if OK, 0 if the wait condition is still not satisfied */
486 int wake_thread( struct thread *thread )
487 {
488     int signaled, count;
489     void *cookie;
490
491     for (count = 0; thread->wait; count++)
492     {
493         if ((signaled = check_wait( thread )) == -1) break;
494
495         cookie = thread->wait->cookie;
496         if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
497                                   thread->id, signaled, cookie );
498         end_wait( thread );
499         if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
500             break;
501     }
502     return count;
503 }
504
505 /* thread wait timeout */
506 static void thread_timeout( void *ptr )
507 {
508     struct thread_wait *wait = ptr;
509     struct thread *thread = wait->thread;
510     void *cookie = wait->cookie;
511
512     wait->user = NULL;
513     if (thread->wait != wait) return; /* not the top-level wait, ignore it */
514     if (thread->suspend + thread->process->suspend > 0) return;  /* suspended, ignore it */
515
516     if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
517                               thread->id, STATUS_TIMEOUT, cookie );
518     end_wait( thread );
519     if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
520     /* check if other objects have become signaled in the meantime */
521     wake_thread( thread );
522 }
523
524 /* select on a list of handles */
525 static void select_on( int count, void *cookie, const obj_handle_t *handles,
526                        int flags, const abs_time_t *timeout )
527 {
528     int ret, i;
529     struct object *objects[MAXIMUM_WAIT_OBJECTS];
530
531     if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
532     {
533         set_error( STATUS_INVALID_PARAMETER );
534         return;
535     }
536     for (i = 0; i < count; i++)
537     {
538         if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
539             break;
540     }
541
542     if (i < count) goto done;
543     if (!wait_on( count, objects, flags, timeout )) goto done;
544
545     if ((ret = check_wait( current )) != -1)
546     {
547         /* condition is already satisfied */
548         end_wait( current );
549         set_error( ret );
550         goto done;
551     }
552
553     /* now we need to wait */
554     if (flags & SELECT_TIMEOUT)
555     {
556         if (!(current->wait->user = add_timeout_user( &current->wait->timeout,
557                                                       thread_timeout, current->wait )))
558         {
559             end_wait( current );
560             goto done;
561         }
562     }
563     current->wait->cookie = cookie;
564     set_error( STATUS_PENDING );
565
566 done:
567     while (--i >= 0) release_object( objects[i] );
568 }
569
570 /* attempt to wake threads sleeping on the object wait queue */
571 void wake_up( struct object *obj, int max )
572 {
573     struct wait_queue_entry *entry = obj->head;
574
575     while (entry)
576     {
577         struct thread *thread = entry->thread;
578         entry = entry->next;
579         if (wake_thread( thread ))
580         {
581             if (max && !--max) break;
582         }
583     }
584 }
585
586 /* queue an async procedure call */
587 int thread_queue_apc( struct thread *thread, struct object *owner, void *func,
588                       enum apc_type type, int system, void *arg1, void *arg2, void *arg3 )
589 {
590     struct thread_apc *apc;
591     struct apc_queue *queue = system ? &thread->system_apc : &thread->user_apc;
592
593     /* cancel a possible previous APC with the same owner */
594     if (owner) thread_cancel_apc( thread, owner, system );
595     if (thread->state == TERMINATED) return 0;
596
597     if (!(apc = mem_alloc( sizeof(*apc) ))) return 0;
598     apc->prev   = queue->tail;
599     apc->next   = NULL;
600     apc->owner  = owner;
601     apc->func   = func;
602     apc->type   = type;
603     apc->arg1   = arg1;
604     apc->arg2   = arg2;
605     apc->arg3   = arg3;
606     queue->tail = apc;
607     if (!apc->prev)  /* first one */
608     {
609         queue->head = apc;
610         wake_thread( thread );
611     }
612     else apc->prev->next = apc;
613
614     return 1;
615 }
616
617 /* cancel the async procedure call owned by a specific object */
618 void thread_cancel_apc( struct thread *thread, struct object *owner, int system )
619 {
620     struct thread_apc *apc;
621     struct apc_queue *queue = system ? &thread->system_apc : &thread->user_apc;
622     for (apc = queue->head; apc; apc = apc->next)
623     {
624         if (apc->owner != owner) continue;
625         if (apc->next) apc->next->prev = apc->prev;
626         else queue->tail = apc->prev;
627         if (apc->prev) apc->prev->next = apc->next;
628         else queue->head = apc->next;
629         free( apc );
630         return;
631     }
632 }
633
634 /* remove the head apc from the queue; the returned pointer must be freed by the caller */
635 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
636 {
637     struct thread_apc *apc;
638     struct apc_queue *queue = &thread->system_apc;
639
640     if (!queue->head && !system_only) queue = &thread->user_apc;
641     if ((apc = queue->head))
642     {
643         if (apc->next) apc->next->prev = NULL;
644         else queue->tail = NULL;
645         queue->head = apc->next;
646     }
647     return apc;
648 }
649
650 /* add an fd to the inflight list */
651 /* return list index, or -1 on error */
652 int thread_add_inflight_fd( struct thread *thread, int client, int server )
653 {
654     int i;
655
656     if (server == -1) return -1;
657     if (client == -1)
658     {
659         close( server );
660         return -1;
661     }
662
663     /* first check if we already have an entry for this fd */
664     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
665         if (thread->inflight[i].client == client)
666         {
667             close( thread->inflight[i].server );
668             thread->inflight[i].server = server;
669             return i;
670         }
671
672     /* now find a free spot to store it */
673     for (i = 0; i < MAX_INFLIGHT_FDS; i++)
674         if (thread->inflight[i].client == -1)
675         {
676             thread->inflight[i].client = client;
677             thread->inflight[i].server = server;
678             return i;
679         }
680     return -1;
681 }
682
683 /* get an inflight fd and purge it from the list */
684 /* the fd must be closed when no longer used */
685 int thread_get_inflight_fd( struct thread *thread, int client )
686 {
687     int i, ret;
688
689     if (client == -1) return -1;
690
691     do
692     {
693         for (i = 0; i < MAX_INFLIGHT_FDS; i++)
694         {
695             if (thread->inflight[i].client == client)
696             {
697                 ret = thread->inflight[i].server;
698                 thread->inflight[i].server = thread->inflight[i].client = -1;
699                 return ret;
700             }
701         }
702     } while (!receive_fd( thread->process ));  /* in case it is still in the socket buffer */
703     return -1;
704 }
705
706 /* retrieve an LDT selector entry */
707 static void get_selector_entry( struct thread *thread, int entry,
708                                 unsigned int *base, unsigned int *limit,
709                                 unsigned char *flags )
710 {
711     if (!thread->process->ldt_copy)
712     {
713         set_error( STATUS_ACCESS_DENIED );
714         return;
715     }
716     if (entry >= 8192)
717     {
718         set_error( STATUS_INVALID_PARAMETER );  /* FIXME */
719         return;
720     }
721     if (suspend_for_ptrace( thread ))
722     {
723         unsigned char flags_buf[4];
724         int *addr = (int *)thread->process->ldt_copy + entry;
725         if (read_thread_int( thread, addr, base ) == -1) goto done;
726         if (read_thread_int( thread, addr + 8192, limit ) == -1) goto done;
727         addr = (int *)thread->process->ldt_copy + 2*8192 + (entry >> 2);
728         if (read_thread_int( thread, addr, (int *)flags_buf ) == -1) goto done;
729         *flags = flags_buf[entry & 3];
730     done:
731         resume_after_ptrace( thread );
732     }
733 }
734
735 /* kill a thread on the spot */
736 void kill_thread( struct thread *thread, int violent_death )
737 {
738     if (thread->state == TERMINATED) return;  /* already killed */
739     thread->state = TERMINATED;
740     thread->exit_time = time(NULL);
741     if (current == thread) current = NULL;
742     if (debug_level)
743         fprintf( stderr,"%04x: *killed* exit_code=%d\n",
744                  thread->id, thread->exit_code );
745     if (thread->wait)
746     {
747         while (thread->wait) end_wait( thread );
748         send_thread_wakeup( thread, NULL, STATUS_PENDING );
749         /* if it is waiting on the socket, we don't need to send a SIGTERM */
750         violent_death = 0;
751     }
752     kill_console_processes( thread, 0 );
753     debug_exit_thread( thread );
754     abandon_mutexes( thread );
755     remove_process_thread( thread->process, thread );
756     wake_up( &thread->obj, 0 );
757     detach_thread( thread, violent_death ? SIGTERM : 0 );
758     cleanup_thread( thread );
759     release_object( thread );
760 }
761
762 /* take a snapshot of currently running threads */
763 struct thread_snapshot *thread_snap( int *count )
764 {
765     struct thread_snapshot *snapshot, *ptr;
766     struct thread *thread;
767     int total = 0;
768
769     for (thread = first_thread; thread; thread = thread->next)
770         if (thread->state != TERMINATED) total++;
771     if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
772     ptr = snapshot;
773     for (thread = first_thread; thread; thread = thread->next)
774     {
775         if (thread->state == TERMINATED) continue;
776         ptr->thread   = thread;
777         ptr->count    = thread->obj.refcount;
778         ptr->priority = thread->priority;
779         grab_object( thread );
780         ptr++;
781     }
782     *count = total;
783     return snapshot;
784 }
785
786 /* signal that we are finished booting on the client side */
787 DECL_HANDLER(boot_done)
788 {
789     debug_level = max( debug_level, req->debug_level );
790     if (current == booting_thread)
791     {
792         booting_thread = (struct thread *)~0UL;  /* make sure it doesn't match other threads */
793         lock_master_socket(0);  /* allow other clients now */
794     }
795 }
796
797 /* create a new thread */
798 DECL_HANDLER(new_thread)
799 {
800     struct thread *thread;
801     int request_fd = thread_get_inflight_fd( current, req->request_fd );
802
803     if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
804     {
805         if (request_fd != -1) close( request_fd );
806         set_error( STATUS_INVALID_HANDLE );
807         return;
808     }
809
810     if ((thread = create_thread( request_fd, current->process )))
811     {
812         if (req->suspend) thread->suspend++;
813         reply->tid = get_thread_id( thread );
814         if ((reply->handle = alloc_handle( current->process, thread,
815                                            THREAD_ALL_ACCESS, req->inherit )))
816         {
817             /* thread object will be released when the thread gets killed */
818             return;
819         }
820         kill_thread( thread, 1 );
821     }
822 }
823
824 /* initialize a new thread */
825 DECL_HANDLER(init_thread)
826 {
827     int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
828     int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
829
830     if (current->unix_pid != -1)
831     {
832         fatal_protocol_error( current, "init_thread: already running\n" );
833         goto error;
834     }
835     if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1)
836     {
837         fatal_protocol_error( current, "bad reply fd\n" );
838         goto error;
839     }
840     if (wait_fd == -1)
841     {
842         fatal_protocol_error( current, "bad wait fd\n" );
843         goto error;
844     }
845     if (!(current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj )))
846     {
847         reply_fd = -1;
848         fatal_protocol_error( current, "could not allocate reply fd\n" );
849         goto error;
850     }
851     if (!(current->wait_fd  = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj )))
852         return;
853
854     current->unix_pid = req->unix_pid;
855     current->unix_tid = req->unix_tid;
856     current->teb      = req->teb;
857
858     if (current->suspend + current->process->suspend > 0) stop_thread( current );
859     if (current->process->running_threads > 1)
860         generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
861
862     reply->pid     = get_process_id( current->process );
863     reply->tid     = get_thread_id( current );
864     reply->boot    = (current == booting_thread);
865     reply->version = SERVER_PROTOCOL_VERSION;
866     return;
867
868  error:
869     if (reply_fd != -1) close( reply_fd );
870     if (wait_fd != -1) close( wait_fd );
871 }
872
873 /* terminate a thread */
874 DECL_HANDLER(terminate_thread)
875 {
876     struct thread *thread;
877
878     reply->self = 0;
879     reply->last = 0;
880     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
881     {
882         thread->exit_code = req->exit_code;
883         if (thread != current) kill_thread( thread, 1 );
884         else
885         {
886             reply->self = 1;
887             reply->last = (thread->process->running_threads == 1);
888         }
889         release_object( thread );
890     }
891 }
892
893 /* open a handle to a thread */
894 DECL_HANDLER(open_thread)
895 {
896     struct thread *thread = get_thread_from_id( req->tid );
897
898     reply->handle = 0;
899     if (thread)
900     {
901         reply->handle = alloc_handle( current->process, thread, req->access, req->inherit );
902         release_object( thread );
903     }
904 }
905
906 /* fetch information about a thread */
907 DECL_HANDLER(get_thread_info)
908 {
909     struct thread *thread;
910     obj_handle_t handle = req->handle;
911
912     if (!handle) thread = get_thread_from_id( req->tid_in );
913     else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
914
915     if (thread)
916     {
917         reply->pid            = get_process_id( thread->process );
918         reply->tid            = get_thread_id( thread );
919         reply->teb            = thread->teb;
920         reply->exit_code      = (thread->state == TERMINATED) ? thread->exit_code : STILL_ACTIVE;
921         reply->priority       = thread->priority;
922         reply->affinity       = thread->affinity;
923         reply->creation_time  = thread->creation_time;
924         reply->exit_time      = thread->exit_time;
925
926         release_object( thread );
927     }
928 }
929
930 /* set information about a thread */
931 DECL_HANDLER(set_thread_info)
932 {
933     struct thread *thread;
934
935     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
936     {
937         set_thread_info( thread, req );
938         release_object( thread );
939     }
940 }
941
942 /* suspend a thread */
943 DECL_HANDLER(suspend_thread)
944 {
945     struct thread *thread;
946
947     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
948     {
949         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
950         else reply->count = suspend_thread( thread );
951         release_object( thread );
952     }
953 }
954
955 /* resume a thread */
956 DECL_HANDLER(resume_thread)
957 {
958     struct thread *thread;
959
960     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
961     {
962         if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
963         else reply->count = resume_thread( thread );
964         release_object( thread );
965     }
966 }
967
968 /* select on a handle list */
969 DECL_HANDLER(select)
970 {
971     int count = get_req_data_size() / sizeof(int);
972     select_on( count, req->cookie, get_req_data(), req->flags, &req->timeout );
973 }
974
975 /* queue an APC for a thread */
976 DECL_HANDLER(queue_apc)
977 {
978     struct thread *thread;
979     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
980     {
981         thread_queue_apc( thread, NULL, req->func, APC_USER, !req->user,
982                           req->arg1, req->arg2, req->arg3 );
983         release_object( thread );
984     }
985 }
986
987 /* get next APC to call */
988 DECL_HANDLER(get_apc)
989 {
990     struct thread_apc *apc;
991
992     for (;;)
993     {
994         if (!(apc = thread_dequeue_apc( current, !req->alertable )))
995         {
996             /* no more APCs */
997             reply->func = NULL;
998             reply->type = APC_NONE;
999             return;
1000         }
1001         /* Optimization: ignore APCs that have a NULL func; they are only used
1002          * to wake up a thread, but since we got here the thread woke up already.
1003          * Exception: for APC_ASYNC_IO, func == NULL is legal.
1004          */
1005         if (apc->func || apc->type == APC_ASYNC_IO) break;
1006         free( apc );
1007     }
1008     reply->func = apc->func;
1009     reply->type = apc->type;
1010     reply->arg1 = apc->arg1;
1011     reply->arg2 = apc->arg2;
1012     reply->arg3 = apc->arg3;
1013     free( apc );
1014 }
1015
1016 /* fetch a selector entry for a thread */
1017 DECL_HANDLER(get_selector_entry)
1018 {
1019     struct thread *thread;
1020     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1021     {
1022         get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1023         release_object( thread );
1024     }
1025 }