Removed extraneous ERR message.
[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 #include <sys/uio.h>
20 #include <unistd.h>
21 #include <stdarg.h>
22
23
24 #include "winbase.h"
25 #include "winerror.h"
26
27 #include "handle.h"
28 #include "process.h"
29 #include "thread.h"
30 #include "request.h"
31
32
33 /* thread queues */
34
35 struct wait_queue_entry
36 {
37     struct wait_queue_entry *next;
38     struct wait_queue_entry *prev;
39     struct object           *obj;
40     struct thread           *thread;
41 };
42
43 struct thread_wait
44 {
45     int                     count;      /* count of objects */
46     int                     flags;
47     struct timeval          timeout;
48     struct timeout_user    *user;
49     struct wait_queue_entry queues[1];
50 };
51
52 /* asynchronous procedure calls */
53
54 struct thread_apc
55 {
56     void                   *func;    /* function to call in client */
57     void                   *param;   /* function param */
58 };
59 #define MAX_THREAD_APC  16  /* Max outstanding APCs for a thread */
60
61
62 /* thread operations */
63
64 static void dump_thread( struct object *obj, int verbose );
65 static int thread_signaled( struct object *obj, struct thread *thread );
66 extern void thread_poll_event( struct object *obj, int event );
67 static void destroy_thread( struct object *obj );
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_read_fd,                 /* get_read_fd */
80     no_write_fd,                /* get_write_fd */
81     no_flush,                   /* flush */
82     no_get_file_info,           /* get_file_info */
83     destroy_thread              /* destroy */
84 };
85
86 static struct thread *first_thread;
87
88 /* allocate the buffer for the communication with the client */
89 static int alloc_client_buffer( struct thread *thread )
90 {
91     int fd;
92
93     if ((fd = create_anonymous_file()) == -1) return -1;
94     if (ftruncate( fd, MAX_REQUEST_LENGTH ) == -1) goto error;
95     if ((thread->buffer = mmap( 0, MAX_REQUEST_LENGTH, PROT_READ | PROT_WRITE,
96                                 MAP_SHARED, fd, 0 )) == (void*)-1) goto error;
97     return fd;
98
99  error:
100     file_set_error();
101     if (fd != -1) close( fd );
102     return -1;
103 }
104
105 /* create a new thread */
106 static struct thread *create_thread( int fd, struct process *process, int suspend )
107 {
108     struct thread *thread;
109     int buf_fd;
110
111     int flags = fcntl( fd, F_GETFL, 0 );
112     fcntl( fd, F_SETFL, flags | O_NONBLOCK );
113
114     if (!(thread = alloc_object( &thread_ops, fd ))) return NULL;
115
116     thread->unix_pid    = 0;  /* not known yet */
117     thread->teb         = NULL;
118     thread->mutex       = NULL;
119     thread->debug_ctx   = NULL;
120     thread->debug_event = NULL;
121     thread->exit_event  = NULL;
122     thread->wait        = NULL;
123     thread->apc         = NULL;
124     thread->apc_count   = 0;
125     thread->error       = 0;
126     thread->pass_fd     = -1;
127     thread->state       = RUNNING;
128     thread->attached    = 0;
129     thread->exit_code   = 0x103;  /* STILL_ACTIVE */
130     thread->next        = NULL;
131     thread->prev        = NULL;
132     thread->priority    = THREAD_PRIORITY_NORMAL;
133     thread->affinity    = 1;
134     thread->suspend     = (suspend != 0);
135     thread->buffer      = (void *)-1;
136     thread->last_req    = REQ_GET_THREAD_BUFFER;
137
138     if (!first_thread)  /* creating the first thread */
139     {
140         current = thread;
141         thread->process = process = create_initial_process(); 
142         assert( process );
143     }
144     else thread->process = (struct process *)grab_object( process );
145
146     if ((thread->next = first_thread) != NULL) thread->next->prev = thread;
147     first_thread = thread;
148     add_process_thread( process, thread );
149
150     if ((buf_fd = alloc_client_buffer( thread )) == -1) goto error;
151
152     set_select_events( &thread->obj, POLLIN );  /* start listening to events */
153     set_reply_fd( thread, buf_fd );  /* send the fd to the client */
154     send_reply( thread );
155     return thread;
156
157  error:
158     remove_process_thread( process, thread );
159     release_object( thread );
160     return NULL;
161 }
162
163 /* create the initial thread and start the main server loop */
164 void create_initial_thread( int fd )
165 {
166     create_thread( fd, NULL, 0 );
167     select_loop();
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( ERROR_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( ERROR_SIGNAL_REFUSED );
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( struct thread *thread, int count,
334                     int *handles, int flags, int timeout )
335 {
336     struct thread_wait *wait;
337     struct wait_queue_entry *entry;
338     struct object *obj;
339     int i;
340
341     if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
342     {
343         set_error( ERROR_INVALID_PARAMETER );
344         return 0;
345     }
346     if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
347     thread->wait  = wait;
348     wait->count   = count;
349     wait->flags   = flags;
350     wait->user    = NULL;
351     if (flags & SELECT_TIMEOUT)
352     {
353         gettimeofday( &wait->timeout, 0 );
354         add_timeout( &wait->timeout, timeout );
355     }
356
357     for (i = 0, entry = wait->queues; i < count; i++, entry++)
358     {
359         if (!(obj = get_handle_obj( thread->process, handles[i],
360                                     SYNCHRONIZE, NULL )))
361         {
362             wait->count = i - 1;
363             end_wait( thread );
364             return 0;
365         }
366         entry->thread = thread;
367         if (!obj->ops->add_queue( obj, entry ))
368         {
369             wait->count = i - 1;
370             end_wait( thread );
371             return 0;
372         }
373         release_object( obj );
374     }
375     return 1;
376 }
377
378 /* check if the thread waiting condition is satisfied */
379 static int check_wait( struct thread *thread, int *signaled )
380 {
381     int i;
382     struct thread_wait *wait = thread->wait;
383     struct wait_queue_entry *entry = wait->queues;
384
385     assert( wait );
386     if (wait->flags & SELECT_ALL)
387     {
388         int not_ok = 0;
389         /* Note: we must check them all anyway, as some objects may
390          * want to do something when signaled, even if others are not */
391         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
392             not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
393         if (not_ok) goto other_checks;
394         /* Wait satisfied: tell it to all objects */
395         *signaled = 0;
396         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
397             if (entry->obj->ops->satisfied( entry->obj, thread ))
398                 *signaled = STATUS_ABANDONED_WAIT_0;
399         return 1;
400     }
401     else
402     {
403         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
404         {
405             if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
406             /* Wait satisfied: tell it to the object */
407             *signaled = i;
408             if (entry->obj->ops->satisfied( entry->obj, thread ))
409                 *signaled = i + STATUS_ABANDONED_WAIT_0;
410             return 1;
411         }
412     }
413
414  other_checks:
415     if ((wait->flags & SELECT_ALERTABLE) && thread->apc)
416     {
417         *signaled = STATUS_USER_APC;
418         return 1;
419     }
420     if (wait->flags & SELECT_TIMEOUT)
421     {
422         struct timeval now;
423         gettimeofday( &now, NULL );
424         if (!time_before( &now, &wait->timeout ))
425         {
426             *signaled = STATUS_TIMEOUT;
427             return 1;
428         }
429     }
430     return 0;
431 }
432
433 /* attempt to wake up a thread */
434 /* return 1 if OK, 0 if the wait condition is still not satisfied */
435 static int wake_thread( struct thread *thread )
436 {
437     struct select_request *req = get_req_ptr( thread );
438
439     if (!check_wait( thread, &req->signaled )) return 0;
440     end_wait( thread );
441     return 1;
442 }
443
444 /* sleep on a list of objects */
445 static void sleep_on( struct thread *thread, int count, int *handles, int flags, int timeout )
446 {
447     struct select_request *req;
448     assert( !thread->wait );
449     if (!wait_on( thread, count, handles, flags, timeout )) goto error;
450     if (wake_thread( thread )) return;
451     /* now we need to wait */
452     if (flags & SELECT_TIMEOUT)
453     {
454         if (!(thread->wait->user = add_timeout_user( &thread->wait->timeout,
455                                                      call_timeout_handler, thread )))
456             goto error;
457     }
458     thread->state = SLEEPING;
459     return;
460
461  error:
462     req = get_req_ptr( thread );
463     req->signaled = -1;
464 }
465
466 /* timeout for the current thread */
467 void thread_timeout(void)
468 {
469     struct select_request *req = get_req_ptr( current );
470
471     assert( current->wait );
472     current->wait->user = NULL;
473     end_wait( current );
474     req->signaled = STATUS_TIMEOUT;
475     send_reply( current );
476 }
477
478 /* attempt to wake threads sleeping on the object wait queue */
479 void wake_up( struct object *obj, int max )
480 {
481     struct wait_queue_entry *entry = obj->head;
482
483     while (entry)
484     {
485         struct thread *thread = entry->thread;
486         entry = entry->next;
487         if (wake_thread( thread ))
488         {
489             send_reply( thread );
490             if (max && !--max) break;
491         }
492     }
493 }
494
495 /* queue an async procedure call */
496 static int thread_queue_apc( struct thread *thread, void *func, void *param )
497 {
498     struct thread_apc *apc;
499     if (!thread->apc)
500     {
501         if (!(thread->apc = mem_alloc( MAX_THREAD_APC * sizeof(*apc) )))
502             return 0;
503         thread->apc_count = 0;
504     }
505     else if (thread->apc_count >= MAX_THREAD_APC) return 0;
506     thread->apc[thread->apc_count].func  = func;
507     thread->apc[thread->apc_count].param = param;
508     thread->apc_count++;
509     if (thread->wait)
510     {
511         if (wake_thread( thread )) send_reply( thread );
512     }
513     return 1;
514 }
515
516 /* kill a thread on the spot */
517 void kill_thread( struct thread *thread, int exit_code )
518 {
519     if (thread->state == TERMINATED) return;  /* already killed */
520     thread->state = TERMINATED;
521     thread->exit_code = exit_code;
522     if (current == thread) current = NULL;
523     if (debug_level) trace_kill( thread );
524     if (thread->wait) end_wait( thread );
525     debug_exit_thread( thread, exit_code );
526     abandon_mutexes( thread );
527     remove_process_thread( thread->process, thread );
528     wake_up( &thread->obj, 0 );
529     detach_thread( thread );
530     remove_select_user( &thread->obj );
531     release_object( thread );
532 }
533
534 /* create a new thread */
535 DECL_HANDLER(new_thread)
536 {
537     struct thread *thread;
538     struct process *process;
539
540     if ((process = get_process_from_id( req->pid )))
541     {
542         if ((fd = dup(fd)) != -1)
543         {
544             if ((thread = create_thread( fd, process, req->suspend )))
545             {
546                 req->tid = thread;
547                 if ((req->handle = alloc_handle( current->process, thread,
548                                                  THREAD_ALL_ACCESS, req->inherit )) == -1)
549                     release_object( thread );
550                 /* else will be released when the thread gets killed */
551             }
552             else close( fd );
553         }
554         else file_set_error();
555         release_object( process );
556     }
557 }
558
559 /* retrieve the thread buffer file descriptor */
560 DECL_HANDLER(get_thread_buffer)
561 {
562     fatal_protocol_error( current, "get_thread_buffer: should never get called directly\n" );
563 }
564
565 /* initialize a new thread */
566 DECL_HANDLER(init_thread)
567 {
568     if (current->unix_pid)
569     {
570         fatal_protocol_error( current, "init_thread: already running\n" );
571         return;
572     }
573     current->unix_pid = req->unix_pid;
574     current->teb      = req->teb;
575     if (current->suspend + current->process->suspend > 0) stop_thread( current );
576     req->pid = current->process;
577     req->tid = current;
578 }
579
580 /* terminate a thread */
581 DECL_HANDLER(terminate_thread)
582 {
583     struct thread *thread;
584
585     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
586     {
587         kill_thread( thread, req->exit_code );
588         release_object( thread );
589     }
590 }
591
592 /* fetch information about a thread */
593 DECL_HANDLER(get_thread_info)
594 {
595     struct thread *thread;
596
597     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
598     {
599         req->tid       = thread;
600         req->exit_code = thread->exit_code;
601         req->priority  = thread->priority;
602         release_object( thread );
603     }
604 }
605
606 /* set information about a thread */
607 DECL_HANDLER(set_thread_info)
608 {
609     struct thread *thread;
610
611     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
612     {
613         set_thread_info( thread, req );
614         release_object( thread );
615     }
616 }
617
618 /* suspend a thread */
619 DECL_HANDLER(suspend_thread)
620 {
621     struct thread *thread;
622
623     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
624     {
625         req->count = suspend_thread( thread, 1 );
626         release_object( thread );
627     }
628 }
629
630 /* resume a thread */
631 DECL_HANDLER(resume_thread)
632 {
633     struct thread *thread;
634
635     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
636     {
637         req->count = resume_thread( thread );
638         release_object( thread );
639     }
640 }
641
642 /* select on a handle list */
643 DECL_HANDLER(select)
644 {
645     sleep_on( current, req->count, req->handles, req->flags, req->timeout );
646 }
647
648 /* queue an APC for a thread */
649 DECL_HANDLER(queue_apc)
650 {
651     struct thread *thread;
652     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
653     {
654         thread_queue_apc( thread, req->func, req->param );
655         release_object( thread );
656     }
657 }
658
659 /* get list of APC to call */
660 DECL_HANDLER(get_apcs)
661 {
662     if ((req->count = current->apc_count))
663     {
664         memcpy( req->apcs, current->apc, current->apc_count * sizeof(*current->apc) );
665         free( current->apc );
666         current->apc = NULL;
667         current->apc_count = 0;
668     }
669 }