Don't crash when we get a SIGCHLD for a removed thread.
[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 <fcntl.h>
11 #include <signal.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #ifdef HAVE_SYS_MMAN_H
16 #include <sys/mman.h>
17 #endif
18 #include <sys/ptrace.h>
19 #include <sys/types.h>
20 #include <sys/uio.h>
21 #include <sys/wait.h>
22 #include <unistd.h>
23 #include <stdarg.h>
24
25
26 #include "winbase.h"
27 #include "winerror.h"
28
29 #include "handle.h"
30 #include "process.h"
31 #include "thread.h"
32 #include "request.h"
33
34
35 /* thread queues */
36
37 struct wait_queue_entry
38 {
39     struct wait_queue_entry *next;
40     struct wait_queue_entry *prev;
41     struct object           *obj;
42     struct thread           *thread;
43 };
44
45 struct thread_wait
46 {
47     int                     count;      /* count of objects */
48     int                     flags;
49     struct timeval          timeout;
50     struct timeout_user    *user;
51     struct wait_queue_entry queues[1];
52 };
53
54 /* asynchronous procedure calls */
55
56 struct thread_apc
57 {
58     void                   *func;    /* function to call in client */
59     void                   *param;   /* function param */
60 };
61 #define MAX_THREAD_APC  16  /* Max outstanding APCs for a thread */
62
63
64 /* thread operations */
65
66 static void dump_thread( struct object *obj, int verbose );
67 static int thread_signaled( struct object *obj, struct thread *thread );
68 static void destroy_thread( struct object *obj );
69
70 static const struct object_ops thread_ops =
71 {
72     sizeof(struct thread),
73     dump_thread,
74     add_queue,
75     remove_queue,
76     thread_signaled,
77     no_satisfied,
78     no_read_fd,
79     no_write_fd,
80     no_flush,
81     no_get_file_info,
82     destroy_thread
83 };
84
85 static struct thread *first_thread;
86
87 /* allocate the buffer for the communication with the client */
88 static int alloc_client_buffer( struct thread *thread )
89 {
90     int fd;
91
92     if ((fd = create_anonymous_file()) == -1) return -1;
93     if (ftruncate( fd, MAX_REQUEST_LENGTH ) == -1) goto error;
94     if ((thread->buffer = mmap( 0, MAX_REQUEST_LENGTH, PROT_READ | PROT_WRITE,
95                                 MAP_SHARED, fd, 0 )) == (void*)-1) goto error;
96     return fd;
97
98  error:
99     file_set_error();
100     if (fd != -1) close( fd );
101     return -1;
102 }
103
104 /* create a new thread */
105 static struct thread *create_thread( int fd, struct process *process, int suspend )
106 {
107     struct thread *thread;
108     int buf_fd;
109
110     if (!(thread = alloc_object( &thread_ops ))) return NULL;
111
112     thread->client      = NULL;
113     thread->unix_pid    = 0;  /* not known yet */
114     thread->teb         = NULL;
115     thread->mutex       = NULL;
116     thread->debug_ctx   = NULL;
117     thread->debug_first = NULL;
118     thread->debug_event = NULL;
119     thread->wait        = NULL;
120     thread->apc         = NULL;
121     thread->apc_count   = 0;
122     thread->error       = 0;
123     thread->state       = RUNNING;
124     thread->attached    = 0;
125     thread->exit_code   = 0x103;  /* STILL_ACTIVE */
126     thread->next        = NULL;
127     thread->prev        = NULL;
128     thread->priority    = THREAD_PRIORITY_NORMAL;
129     thread->affinity    = 1;
130     thread->suspend     = (suspend != 0);
131     thread->buffer      = (void *)-1;
132     thread->last_req    = REQ_GET_THREAD_BUFFER;
133
134     if (!first_thread)  /* creating the first thread */
135     {
136         current = thread;
137         thread->process = process = create_initial_process(); 
138         assert( process );
139     }
140     else thread->process = (struct process *)grab_object( process );
141
142     if ((thread->next = first_thread) != NULL) thread->next->prev = thread;
143     first_thread = thread;
144     add_process_thread( process, thread );
145
146     if ((buf_fd = alloc_client_buffer( thread )) == -1) goto error;
147     if (!(thread->client = add_client( fd, thread )))
148     {
149         close( buf_fd );
150         goto error;
151     }
152     set_reply_fd( thread, buf_fd );  /* send the fd to the client */
153     send_reply( thread );
154     return thread;
155
156  error:
157     remove_process_thread( process, thread );
158     release_object( thread );
159     return NULL;
160 }
161
162 /* create the initial thread and start the main server loop */
163 void create_initial_thread( int fd )
164 {
165     create_thread( fd, NULL, 0 );
166     select_loop();
167 }
168
169 /* destroy a thread when its refcount is 0 */
170 static void destroy_thread( struct object *obj )
171 {
172     struct thread *thread = (struct thread *)obj;
173     assert( obj->ops == &thread_ops );
174
175     assert( !thread->debug_ctx );  /* cannot still be debugging something */
176     release_object( thread->process );
177     if (thread->next) thread->next->prev = thread->prev;
178     if (thread->prev) thread->prev->next = thread->next;
179     else first_thread = thread->next;
180     if (thread->apc) free( thread->apc );
181     if (thread->buffer != (void *)-1) munmap( thread->buffer, MAX_REQUEST_LENGTH );
182 }
183
184 /* dump a thread on stdout for debugging purposes */
185 static void dump_thread( struct object *obj, int verbose )
186 {
187     struct thread *thread = (struct thread *)obj;
188     assert( obj->ops == &thread_ops );
189
190     fprintf( stderr, "Thread pid=%d teb=%p state=%d\n",
191              thread->unix_pid, thread->teb, thread->state );
192 }
193
194 static int thread_signaled( struct object *obj, struct thread *thread )
195 {
196     struct thread *mythread = (struct thread *)obj;
197     return (mythread->state == TERMINATED);
198 }
199
200 /* get a thread pointer from a thread id (and increment the refcount) */
201 struct thread *get_thread_from_id( void *id )
202 {
203     struct thread *t = first_thread;
204     while (t && (t != id)) t = t->next;
205     if (t) grab_object( t );
206     return t;
207 }
208
209 /* get a thread from a handle (and increment the refcount) */
210 struct thread *get_thread_from_handle( int handle, unsigned int access )
211 {
212     return (struct thread *)get_handle_obj( current->process, handle,
213                                             access, &thread_ops );
214 }
215
216 /* set all information about a thread */
217 static void set_thread_info( struct thread *thread,
218                              struct set_thread_info_request *req )
219 {
220     if (req->mask & SET_THREAD_INFO_PRIORITY)
221         thread->priority = req->priority;
222     if (req->mask & SET_THREAD_INFO_AFFINITY)
223     {
224         if (req->affinity != 1) set_error( ERROR_INVALID_PARAMETER );
225         else thread->affinity = req->affinity;
226     }
227 }
228
229 /* find a thread from a Unix pid */
230 static struct thread *get_thread_from_pid( int pid )
231 {
232     struct thread *t = first_thread;
233     while (t && (t->unix_pid != pid)) t = t->next;
234     return t;
235 }
236
237 /* wait for a ptraced child to get a certain signal */
238 /* if the signal is 0, we simply check if anything is pending and return at once */
239 void wait4_thread( struct thread *thread, int signal )
240 {
241     int status;
242     int pid;
243
244
245  restart:
246     pid = thread ? thread->unix_pid : -1;
247     if ((pid = wait4( pid, &status, WUNTRACED | (signal ? 0 : WNOHANG), NULL )) == -1)
248     {
249         perror( "wait4" );
250         return;
251     }
252     if (WIFSTOPPED(status))
253     {
254         int sig = WSTOPSIG(status);
255         if (debug_level) fprintf( stderr, "ptrace: pid %d got sig %d\n", pid, sig );
256         switch(sig)
257         {
258         case SIGSTOP:  /* continue at once if not suspended */
259             if (!thread)
260                 if (!(thread = get_thread_from_pid( pid ))) break;
261             if (!(thread->process->suspend + thread->suspend))
262                 ptrace( PTRACE_CONT, pid, 0, sig );
263             break;
264         default:  /* ignore other signals for now */
265             ptrace( PTRACE_CONT, pid, 0, sig );
266             break;
267         }
268         if (signal && sig != signal) goto restart;
269     }
270     else if (WIFSIGNALED(status))
271     {
272         int exit_code = WTERMSIG(status);
273         if (debug_level)
274             fprintf( stderr, "ptrace: pid %d killed by sig %d\n", pid, exit_code );
275         if (!thread)
276             if (!(thread = get_thread_from_pid( pid ))) return;
277         if (thread->client) remove_client( thread->client, exit_code );
278     }
279     else if (WIFEXITED(status))
280     {
281         int exit_code = WEXITSTATUS(status);
282         if (debug_level)
283             fprintf( stderr, "ptrace: pid %d exited with status %d\n", pid, exit_code );
284         if (!thread)
285             if (!(thread = get_thread_from_pid( pid ))) return;
286         if (thread->client) remove_client( thread->client, exit_code );
287     }
288     else fprintf( stderr, "wait4: pid %d unknown status %x\n", pid, status );
289 }
290
291 /* attach to a Unix thread */
292 static int attach_thread( struct thread *thread )
293 {
294     /* this may fail if the client is already being debugged */
295     if (ptrace( PTRACE_ATTACH, thread->unix_pid, 0, 0 ) == -1) return 0;
296     if (debug_level) fprintf( stderr, "ptrace: attached to pid %d\n", thread->unix_pid );
297     thread->attached = 1;
298     wait4_thread( thread, SIGSTOP );
299     return 1;
300 }
301
302 /* detach from a Unix thread and kill it */
303 static void detach_thread( struct thread *thread )
304 {
305     if (!thread->unix_pid) return;
306     kill( thread->unix_pid, SIGTERM );
307     if (thread->suspend + thread->process->suspend) continue_thread( thread );
308     if (thread->attached)
309     {
310         wait4_thread( thread, SIGTERM );
311         if (debug_level) fprintf( stderr, "ptrace: detaching from %d\n", thread->unix_pid );
312         ptrace( PTRACE_DETACH, thread->unix_pid, 0, SIGTERM );
313         thread->attached = 0;
314     }
315 }
316
317 /* stop a thread (at the Unix level) */
318 void stop_thread( struct thread *thread )
319 {
320     if (!thread->unix_pid) return;
321     /* first try to attach to it */
322     if (!thread->attached)
323         if (attach_thread( thread )) return;  /* this will have stopped it */
324     /* attached already, or attach failed -> send a signal */
325     kill( thread->unix_pid, SIGSTOP );
326     if (thread->attached) wait4_thread( thread, SIGSTOP );
327 }
328
329 /* make a thread continue (at the Unix level) */
330 void continue_thread( struct thread *thread )
331 {
332     if (!thread->unix_pid) return;
333     if (!thread->attached) kill( thread->unix_pid, SIGCONT );
334     else ptrace( PTRACE_CONT, thread->unix_pid, 0, SIGSTOP );
335 }
336  
337 /* suspend a thread */
338 static int suspend_thread( struct thread *thread )
339 {
340     int old_count = thread->suspend;
341     if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
342     {
343         if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
344     }
345     return old_count;
346 }
347
348 /* resume a thread */
349 static int resume_thread( struct thread *thread )
350 {
351     int old_count = thread->suspend;
352     if (thread->suspend > 0)
353     {
354         if (!(--thread->suspend + thread->process->suspend)) continue_thread( thread );
355     }
356     return old_count;
357 }
358
359 /* suspend all threads but the current */
360 void suspend_all_threads( void )
361 {
362     struct thread *thread;
363     for ( thread = first_thread; thread; thread = thread->next )
364         if ( thread != current )
365             suspend_thread( thread );
366 }
367
368 /* resume all threads but the current */
369 void resume_all_threads( void )
370 {
371     struct thread *thread;
372     for ( thread = first_thread; thread; thread = thread->next )
373         if ( thread != current )
374             resume_thread( thread );
375 }
376
377 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
378 int add_queue( struct object *obj, struct wait_queue_entry *entry )
379 {
380     grab_object( obj );
381     entry->obj    = obj;
382     entry->prev   = obj->tail;
383     entry->next   = NULL;
384     if (obj->tail) obj->tail->next = entry;
385     else obj->head = entry;
386     obj->tail = entry;
387     return 1;
388 }
389
390 /* remove a thread from an object wait queue */
391 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
392 {
393     if (entry->next) entry->next->prev = entry->prev;
394     else obj->tail = entry->prev;
395     if (entry->prev) entry->prev->next = entry->next;
396     else obj->head = entry->next;
397     release_object( obj );
398 }
399
400 /* finish waiting */
401 static void end_wait( struct thread *thread )
402 {
403     struct thread_wait *wait = thread->wait;
404     struct wait_queue_entry *entry;
405     int i;
406
407     assert( wait );
408     for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
409         entry->obj->ops->remove_queue( entry->obj, entry );
410     if (wait->user) remove_timeout_user( wait->user );
411     free( wait );
412     thread->wait = NULL;
413 }
414
415 /* build the thread wait structure */
416 static int wait_on( struct thread *thread, int count,
417                     int *handles, int flags, int timeout )
418 {
419     struct thread_wait *wait;
420     struct wait_queue_entry *entry;
421     struct object *obj;
422     int i;
423
424     if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
425     {
426         set_error( ERROR_INVALID_PARAMETER );
427         return 0;
428     }
429     if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
430     thread->wait  = wait;
431     wait->count   = count;
432     wait->flags   = flags;
433     wait->user    = NULL;
434     if (flags & SELECT_TIMEOUT) make_timeout( &wait->timeout, timeout );
435
436     for (i = 0, entry = wait->queues; i < count; i++, entry++)
437     {
438         if (!(obj = get_handle_obj( thread->process, handles[i],
439                                     SYNCHRONIZE, NULL )))
440         {
441             wait->count = i - 1;
442             end_wait( thread );
443             return 0;
444         }
445         entry->thread = thread;
446         if (!obj->ops->add_queue( obj, entry ))
447         {
448             wait->count = i - 1;
449             end_wait( thread );
450             return 0;
451         }
452         release_object( obj );
453     }
454     return 1;
455 }
456
457 /* check if the thread waiting condition is satisfied */
458 static int check_wait( struct thread *thread, int *signaled )
459 {
460     int i;
461     struct thread_wait *wait = thread->wait;
462     struct wait_queue_entry *entry = wait->queues;
463
464     assert( wait );
465     if (wait->flags & SELECT_ALL)
466     {
467         int not_ok = 0;
468         /* Note: we must check them all anyway, as some objects may
469          * want to do something when signaled, even if others are not */
470         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
471             not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
472         if (not_ok) goto other_checks;
473         /* Wait satisfied: tell it to all objects */
474         *signaled = 0;
475         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
476             if (entry->obj->ops->satisfied( entry->obj, thread ))
477                 *signaled = STATUS_ABANDONED_WAIT_0;
478         return 1;
479     }
480     else
481     {
482         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
483         {
484             if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
485             /* Wait satisfied: tell it to the object */
486             *signaled = i;
487             if (entry->obj->ops->satisfied( entry->obj, thread ))
488                 *signaled = i + STATUS_ABANDONED_WAIT_0;
489             return 1;
490         }
491     }
492
493  other_checks:
494     if ((wait->flags & SELECT_ALERTABLE) && thread->apc)
495     {
496         *signaled = STATUS_USER_APC;
497         return 1;
498     }
499     if (wait->flags & SELECT_TIMEOUT)
500     {
501         struct timeval now;
502         gettimeofday( &now, NULL );
503         if ((now.tv_sec > wait->timeout.tv_sec) ||
504             ((now.tv_sec == wait->timeout.tv_sec) &&
505              (now.tv_usec >= wait->timeout.tv_usec)))
506         {
507             *signaled = STATUS_TIMEOUT;
508             return 1;
509         }
510     }
511     return 0;
512 }
513
514 /* attempt to wake up a thread */
515 /* return 1 if OK, 0 if the wait condition is still not satisfied */
516 static int wake_thread( struct thread *thread )
517 {
518     struct select_request *req = get_req_ptr( thread );
519
520     if (!check_wait( thread, &req->signaled )) return 0;
521     end_wait( thread );
522     return 1;
523 }
524
525 /* sleep on a list of objects */
526 static void sleep_on( struct thread *thread, int count, int *handles, int flags, int timeout )
527 {
528     struct select_request *req;
529     assert( !thread->wait );
530     if (!wait_on( thread, count, handles, flags, timeout )) goto error;
531     if (wake_thread( thread )) return;
532     /* now we need to wait */
533     if (flags & SELECT_TIMEOUT)
534     {
535         if (!(thread->wait->user = add_timeout_user( &thread->wait->timeout,
536                                                      call_timeout_handler, thread )))
537             goto error;
538     }
539     thread->state = SLEEPING;
540     return;
541
542  error:
543     req = get_req_ptr( thread );
544     req->signaled = -1;
545 }
546
547 /* timeout for the current thread */
548 void thread_timeout(void)
549 {
550     struct select_request *req = get_req_ptr( current );
551
552     assert( current->wait );
553     current->wait->user = NULL;
554     end_wait( current );
555     req->signaled = STATUS_TIMEOUT;
556     send_reply( current );
557 }
558
559 /* attempt to wake threads sleeping on the object wait queue */
560 void wake_up( struct object *obj, int max )
561 {
562     struct wait_queue_entry *entry = obj->head;
563
564     while (entry)
565     {
566         struct thread *thread = entry->thread;
567         entry = entry->next;
568         if (wake_thread( thread ))
569         {
570             send_reply( thread );
571             if (max && !--max) break;
572         }
573     }
574 }
575
576 /* queue an async procedure call */
577 static int thread_queue_apc( struct thread *thread, void *func, void *param )
578 {
579     struct thread_apc *apc;
580     if (!thread->apc)
581     {
582         if (!(thread->apc = mem_alloc( MAX_THREAD_APC * sizeof(*apc) )))
583             return 0;
584         thread->apc_count = 0;
585     }
586     else if (thread->apc_count >= MAX_THREAD_APC) return 0;
587     thread->apc[thread->apc_count].func  = func;
588     thread->apc[thread->apc_count].param = param;
589     thread->apc_count++;
590     if (thread->wait)
591     {
592         if (wake_thread( thread )) send_reply( thread );
593     }
594     return 1;
595 }
596
597 /* kill a thread on the spot */
598 void kill_thread( struct thread *thread, int exit_code )
599 {
600     if (thread->state == TERMINATED) return;  /* already killed */
601     remove_client( thread->client, exit_code ); /* this will call thread_killed */
602 }
603
604 /* a thread has been killed */
605 void thread_killed( struct thread *thread, int exit_code )
606 {
607     thread->state = TERMINATED;
608     thread->exit_code = exit_code;
609     thread->client = NULL;
610     if (thread->wait) end_wait( thread );
611     debug_exit_thread( thread, exit_code );
612     abandon_mutexes( thread );
613     remove_process_thread( thread->process, thread );
614     wake_up( &thread->obj, 0 );
615     detach_thread( thread );
616     release_object( thread );
617 }
618
619 /* create a new thread */
620 DECL_HANDLER(new_thread)
621 {
622     struct thread *thread;
623     struct process *process;
624
625     if ((process = get_process_from_id( req->pid )))
626     {
627         if ((fd = dup(fd)) != -1)
628         {
629             if ((thread = create_thread( fd, process, req->suspend )))
630             {
631                 req->tid = thread;
632                 if ((req->handle = alloc_handle( current->process, thread,
633                                                  THREAD_ALL_ACCESS, req->inherit )) == -1)
634                     release_object( thread );
635                 /* else will be released when the thread gets killed */
636             }
637             else close( fd );
638         }
639         else file_set_error();
640         release_object( process );
641     }
642 }
643
644 /* retrieve the thread buffer file descriptor */
645 DECL_HANDLER(get_thread_buffer)
646 {
647     fatal_protocol_error( current, "get_thread_buffer: should never get called directly\n" );
648 }
649
650 /* initialize a new thread */
651 DECL_HANDLER(init_thread)
652 {
653     if (current->unix_pid)
654     {
655         fatal_protocol_error( current, "init_thread: already running\n" );
656         return;
657     }
658     current->unix_pid = req->unix_pid;
659     current->teb      = req->teb;
660     if (current->suspend + current->process->suspend > 0) stop_thread( current );
661     req->pid = current->process;
662     req->tid = current;
663 }
664
665 /* terminate a thread */
666 DECL_HANDLER(terminate_thread)
667 {
668     struct thread *thread;
669
670     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
671     {
672         kill_thread( thread, req->exit_code );
673         release_object( thread );
674     }
675 }
676
677 /* fetch information about a thread */
678 DECL_HANDLER(get_thread_info)
679 {
680     struct thread *thread;
681
682     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
683     {
684         req->tid       = thread;
685         req->exit_code = thread->exit_code;
686         req->priority  = thread->priority;
687         release_object( thread );
688     }
689 }
690
691 /* set information about a thread */
692 DECL_HANDLER(set_thread_info)
693 {
694     struct thread *thread;
695
696     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
697     {
698         set_thread_info( thread, req );
699         release_object( thread );
700     }
701 }
702
703 /* suspend a thread */
704 DECL_HANDLER(suspend_thread)
705 {
706     struct thread *thread;
707
708     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
709     {
710         req->count = suspend_thread( thread );
711         release_object( thread );
712     }
713 }
714
715 /* resume a thread */
716 DECL_HANDLER(resume_thread)
717 {
718     struct thread *thread;
719
720     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
721     {
722         req->count = resume_thread( thread );
723         release_object( thread );
724     }
725 }
726
727 /* select on a handle list */
728 DECL_HANDLER(select)
729 {
730     sleep_on( current, req->count, req->handles, req->flags, req->timeout );
731 }
732
733 /* queue an APC for a thread */
734 DECL_HANDLER(queue_apc)
735 {
736     struct thread *thread;
737     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
738     {
739         thread_queue_apc( thread, req->func, req->param );
740         release_object( thread );
741     }
742 }
743
744 /* get list of APC to call */
745 DECL_HANDLER(get_apcs)
746 {
747     if ((req->count = current->apc_count))
748     {
749         memcpy( req->apcs, current->apc, current->apc_count * sizeof(*current->apc) );
750         free( current->apc );
751         current->apc = NULL;
752         current->apc_count = 0;
753     }
754 }