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