Fixed resource loading.
[wine/multimedia.git] / server / thread.c
blobeeedd2bf0a10cae8d17f27936b879c9e60c848d8
1 /*
2 * Server-side thread management
4 * Copyright (C) 1998 Alexandre Julliard
5 */
7 #include "config.h"
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>
27 #include "winbase.h"
29 #include "handle.h"
30 #include "process.h"
31 #include "thread.h"
32 #include "request.h"
35 /* thread queues */
37 struct wait_queue_entry
39 struct wait_queue_entry *next;
40 struct wait_queue_entry *prev;
41 struct object *obj;
42 struct thread *thread;
45 struct thread_wait
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];
55 /* asynchronous procedure calls */
57 struct thread_apc
59 void *func; /* function to call in client */
60 void *param; /* function param */
62 #define MAX_THREAD_APC 16 /* Max outstanding APCs for a thread */
65 /* thread operations */
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 );
72 static const struct object_ops thread_ops =
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 */
89 static struct thread *first_thread;
90 static struct thread *booting_thread;
92 /* allocate the buffer for the communication with the client */
93 static int alloc_client_buffer( struct thread *thread )
95 struct get_thread_buffer_request *req;
96 int fd;
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;
112 error:
113 file_set_error();
114 if (fd != -1) close( fd );
115 return 0;
118 /* create a new thread */
119 struct thread *create_thread( int fd, struct process *process, int suspend )
121 struct thread *thread;
123 int flags = fcntl( fd, F_GETFL, 0 );
124 fcntl( fd, F_SETFL, flags | O_NONBLOCK );
126 if (!(thread = alloc_object( &thread_ops, fd ))) return NULL;
128 thread->unix_pid = 0; /* not known yet */
129 thread->context = NULL;
130 thread->teb = NULL;
131 thread->mutex = NULL;
132 thread->debug_ctx = NULL;
133 thread->debug_event = NULL;
134 thread->wait = NULL;
135 thread->apc = NULL;
136 thread->apc_count = 0;
137 thread->error = 0;
138 thread->pass_fd = -1;
139 thread->state = RUNNING;
140 thread->attached = 0;
141 thread->exit_code = 0;
142 thread->next = NULL;
143 thread->prev = NULL;
144 thread->priority = THREAD_PRIORITY_NORMAL;
145 thread->affinity = 1;
146 thread->suspend = (suspend != 0);
147 thread->buffer = (void *)-1;
148 thread->last_req = REQ_GET_THREAD_BUFFER;
149 thread->process = (struct process *)grab_object( process );
151 if (!current) current = thread;
153 if (!booting_thread) /* first thread ever */
155 booting_thread = thread;
156 lock_master_socket(1);
159 if ((thread->next = first_thread) != NULL) thread->next->prev = thread;
160 first_thread = thread;
162 set_select_events( &thread->obj, POLLIN ); /* start listening to events */
163 if (!alloc_client_buffer( thread )) goto error;
164 return thread;
166 error:
167 release_object( thread );
168 return NULL;
171 /* handle a client event */
172 void thread_poll_event( struct object *obj, int event )
174 struct thread *thread = (struct thread *)obj;
175 assert( obj->ops == &thread_ops );
177 if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
178 else
180 if (event & POLLOUT) write_request( thread );
181 if (event & POLLIN) read_request( thread );
185 /* destroy a thread when its refcount is 0 */
186 static void destroy_thread( struct object *obj )
188 struct thread *thread = (struct thread *)obj;
189 assert( obj->ops == &thread_ops );
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 );
201 /* dump a thread on stdout for debugging purposes */
202 static void dump_thread( struct object *obj, int verbose )
204 struct thread *thread = (struct thread *)obj;
205 assert( obj->ops == &thread_ops );
207 fprintf( stderr, "Thread pid=%d teb=%p state=%d\n",
208 thread->unix_pid, thread->teb, thread->state );
211 static int thread_signaled( struct object *obj, struct thread *thread )
213 struct thread *mythread = (struct thread *)obj;
214 return (mythread->state == TERMINATED);
217 /* get a thread pointer from a thread id (and increment the refcount) */
218 struct thread *get_thread_from_id( void *id )
220 struct thread *t = first_thread;
221 while (t && (t != id)) t = t->next;
222 if (t) grab_object( t );
223 return t;
226 /* get a thread from a handle (and increment the refcount) */
227 struct thread *get_thread_from_handle( int handle, unsigned int access )
229 return (struct thread *)get_handle_obj( current->process, handle,
230 access, &thread_ops );
233 /* find a thread from a Unix pid */
234 struct thread *get_thread_from_pid( int pid )
236 struct thread *t = first_thread;
237 while (t && (t->unix_pid != pid)) t = t->next;
238 return t;
241 /* set all information about a thread */
242 static void set_thread_info( struct thread *thread,
243 struct set_thread_info_request *req )
245 if (req->mask & SET_THREAD_INFO_PRIORITY)
246 thread->priority = req->priority;
247 if (req->mask & SET_THREAD_INFO_AFFINITY)
249 if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
250 else thread->affinity = req->affinity;
254 /* suspend a thread */
255 int suspend_thread( struct thread *thread, int check_limit )
257 int old_count = thread->suspend;
258 if (thread->suspend < MAXIMUM_SUSPEND_COUNT || !check_limit)
260 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
262 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
263 return old_count;
266 /* resume a thread */
267 int resume_thread( struct thread *thread )
269 int old_count = thread->suspend;
270 if (thread->suspend > 0)
272 if (!(--thread->suspend + thread->process->suspend)) continue_thread( thread );
274 return old_count;
277 /* suspend all threads but the current */
278 void suspend_all_threads( void )
280 struct thread *thread;
281 for ( thread = first_thread; thread; thread = thread->next )
282 if ( thread != current )
283 suspend_thread( thread, 0 );
286 /* resume all threads but the current */
287 void resume_all_threads( void )
289 struct thread *thread;
290 for ( thread = first_thread; thread; thread = thread->next )
291 if ( thread != current )
292 resume_thread( thread );
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 )
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;
308 /* remove a thread from an object wait queue */
309 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
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 );
318 /* finish waiting */
319 static void end_wait( struct thread *thread )
321 struct thread_wait *wait = thread->wait;
322 struct wait_queue_entry *entry;
323 int i;
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;
333 /* build the thread wait structure */
334 static int wait_on( int count, struct object *objects[], int flags,
335 int timeout, sleep_reply func )
337 struct thread_wait *wait;
338 struct wait_queue_entry *entry;
339 int i;
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)
349 gettimeofday( &wait->timeout, 0 );
350 add_timeout( &wait->timeout, timeout );
353 for (i = 0, entry = wait->queues; i < count; i++, entry++)
355 struct object *obj = objects[i];
356 entry->thread = current;
357 if (!obj->ops->add_queue( obj, entry ))
359 wait->count = i;
360 end_wait( current );
361 return 0;
364 return 1;
367 /* check if the thread waiting condition is satisfied */
368 static int check_wait( struct thread *thread, struct object **object )
370 int i, signaled;
371 struct thread_wait *wait = thread->wait;
372 struct wait_queue_entry *entry = wait->queues;
374 assert( wait );
375 *object = NULL;
376 if (wait->flags & SELECT_ALL)
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;
391 else
393 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
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;
405 other_checks:
406 if ((wait->flags & SELECT_ALERTABLE) && thread->apc) return STATUS_USER_APC;
407 if (wait->flags & SELECT_TIMEOUT)
409 struct timeval now;
410 gettimeofday( &now, NULL );
411 if (!time_before( &now, &wait->timeout )) return STATUS_TIMEOUT;
413 return -1;
416 /* build a reply to the select request */
417 static void build_select_reply( struct thread *thread, struct object *obj, int signaled )
419 struct select_request *req = get_req_ptr( thread );
420 req->signaled = signaled;
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 )
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;
436 /* thread wait timeout */
437 static void thread_timeout( void *ptr )
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 );
449 /* sleep on a list of objects */
450 int sleep_on( int count, struct object *objects[], int flags, int timeout, sleep_reply func )
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)
458 if (!(current->wait->user = add_timeout_user( &current->wait->timeout,
459 thread_timeout, current )))
461 end_wait( current );
462 return 0;
465 return 1;
468 /* select on a list of handles */
469 static int select_on( int count, int *handles, int flags, int timeout )
471 int ret = 0;
472 int i;
473 struct object *objects[MAXIMUM_WAIT_OBJECTS];
475 if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
477 set_error( STATUS_INVALID_PARAMETER );
478 return 0;
480 for (i = 0; i < count; i++)
482 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
483 break;
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;
490 /* attempt to wake threads sleeping on the object wait queue */
491 void wake_up( struct object *obj, int max )
493 struct wait_queue_entry *entry = obj->head;
495 while (entry)
497 struct thread *thread = entry->thread;
498 entry = entry->next;
499 if (wake_thread( thread ))
501 send_reply( thread );
502 if (max && !--max) break;
507 /* queue an async procedure call */
508 static int thread_queue_apc( struct thread *thread, void *func, void *param )
510 struct thread_apc *apc;
511 if (!thread->apc)
513 if (!(thread->apc = mem_alloc( MAX_THREAD_APC * sizeof(*apc) )))
514 return 0;
515 thread->apc_count = 0;
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)
523 if (wake_thread( thread )) send_reply( thread );
525 return 1;
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 )
533 if (!thread->process->ldt_copy || !thread->process->ldt_flags)
535 set_error( STATUS_ACCESS_DENIED );
536 return;
538 if (entry >= 8192)
540 set_error( STATUS_INVALID_PARAMETER ); /* FIXME */
541 return;
543 if (suspend_for_ptrace( thread ))
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 done:
553 resume_thread( thread );
557 /* kill a thread on the spot */
558 void kill_thread( struct thread *thread, int violent_death )
560 if (thread->state == TERMINATED) return; /* already killed */
561 thread->state = TERMINATED;
562 if (current == thread) current = NULL;
563 if (debug_level)
564 fprintf( stderr,"%08x: *killed* exit_code=%d\n",
565 (unsigned int)thread, thread->exit_code );
566 if (thread->wait)
568 end_wait( thread );
569 /* if it is waiting on the socket, we don't need to send a SIGTERM */
570 violent_death = 0;
572 debug_exit_thread( thread );
573 abandon_mutexes( thread );
574 remove_process_thread( thread->process, thread );
575 wake_up( &thread->obj, 0 );
576 detach_thread( thread, violent_death ? SIGTERM : 0 );
577 remove_select_user( &thread->obj );
578 munmap( thread->buffer, MAX_REQUEST_LENGTH );
579 thread->buffer = (void *)-1;
580 release_object( thread );
583 /* take a snapshot of currently running threads */
584 struct thread_snapshot *thread_snap( int *count )
586 struct thread_snapshot *snapshot, *ptr;
587 struct thread *thread;
588 int total = 0;
590 for (thread = first_thread; thread; thread = thread->next)
591 if (thread->state != TERMINATED) total++;
592 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
593 ptr = snapshot;
594 for (thread = first_thread; thread; thread = thread->next)
596 if (thread->state == TERMINATED) continue;
597 ptr->thread = thread;
598 ptr->count = thread->obj.refcount;
599 ptr->priority = thread->priority;
600 grab_object( thread );
601 ptr++;
603 *count = total;
604 return snapshot;
607 /* signal that we are finished booting on the client side */
608 DECL_HANDLER(boot_done)
610 debug_level = max( debug_level, req->debug_level );
611 /* Make sure last_req is initialized */
612 current->last_req = REQ_BOOT_DONE;
613 if (current == booting_thread)
615 booting_thread = (struct thread *)~0UL; /* make sure it doesn't match other threads */
616 lock_master_socket(0); /* allow other clients now */
620 /* create a new thread */
621 DECL_HANDLER(new_thread)
623 struct thread *thread;
624 int sock[2];
626 if (socketpair( AF_UNIX, SOCK_STREAM, 0, sock ) != -1)
628 if ((thread = create_thread( sock[0], current->process, req->suspend )))
630 req->tid = thread;
631 if ((req->handle = alloc_handle( current->process, thread,
632 THREAD_ALL_ACCESS, req->inherit )) != -1)
634 set_reply_fd( current, sock[1] );
635 /* thread object will be released when the thread gets killed */
636 add_process_thread( current->process, thread );
637 return;
639 release_object( thread );
641 close( sock[1] );
643 else file_set_error();
646 /* retrieve the thread buffer file descriptor */
647 DECL_HANDLER(get_thread_buffer)
649 fatal_protocol_error( current, "get_thread_buffer: should never get called directly\n" );
652 /* initialize a new thread */
653 DECL_HANDLER(init_thread)
655 if (current->unix_pid)
657 fatal_protocol_error( current, "init_thread: already running\n" );
658 return;
660 current->unix_pid = req->unix_pid;
661 current->teb = req->teb;
662 if (current->suspend + current->process->suspend > 0) stop_thread( current );
663 if (current->process->running_threads > 1)
664 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
667 /* terminate a thread */
668 DECL_HANDLER(terminate_thread)
670 struct thread *thread;
672 req->self = 0;
673 req->last = 0;
674 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
676 thread->exit_code = req->exit_code;
677 if (thread != current) kill_thread( thread, 1 );
678 else
680 req->self = 1;
681 req->last = (thread->process->running_threads == 1);
683 release_object( thread );
687 /* fetch information about a thread */
688 DECL_HANDLER(get_thread_info)
690 struct thread *thread;
691 int handle = req->handle;
693 if (handle == -1) thread = get_thread_from_id( req->tid_in );
694 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
696 if (thread)
698 req->tid = get_thread_id( thread );
699 req->teb = thread->teb;
700 req->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STILL_ACTIVE;
701 req->priority = thread->priority;
702 release_object( thread );
706 /* set information about a thread */
707 DECL_HANDLER(set_thread_info)
709 struct thread *thread;
711 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
713 set_thread_info( thread, req );
714 release_object( thread );
718 /* suspend a thread */
719 DECL_HANDLER(suspend_thread)
721 struct thread *thread;
723 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
725 req->count = suspend_thread( thread, 1 );
726 release_object( thread );
730 /* resume a thread */
731 DECL_HANDLER(resume_thread)
733 struct thread *thread;
735 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
737 req->count = resume_thread( thread );
738 release_object( thread );
742 /* select on a handle list */
743 DECL_HANDLER(select)
745 if (!select_on( req->count, req->handles, req->flags, req->timeout ))
746 req->signaled = -1;
749 /* queue an APC for a thread */
750 DECL_HANDLER(queue_apc)
752 struct thread *thread;
753 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
755 thread_queue_apc( thread, req->func, req->param );
756 release_object( thread );
760 /* get list of APC to call */
761 DECL_HANDLER(get_apcs)
763 if ((req->count = current->apc_count))
765 memcpy( req->apcs, current->apc, current->apc_count * sizeof(*current->apc) );
766 free( current->apc );
767 current->apc = NULL;
768 current->apc_count = 0;
772 /* fetch a selector entry for a thread */
773 DECL_HANDLER(get_selector_entry)
775 struct thread *thread;
776 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
778 get_selector_entry( thread, req->entry, &req->base, &req->limit, &req->flags );
779 release_object( thread );