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