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