Fixed memory corruption with CoTaskMemRealloc.
[wine/multimedia.git] / server / thread.c
blobeef39dfdc6217ff459835fd8ec961b064c4c0ef0
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->wait = NULL;
134 thread->apc = NULL;
135 thread->apc_count = 0;
136 thread->error = 0;
137 thread->pass_fd = -1;
138 thread->state = RUNNING;
139 thread->attached = 0;
140 thread->exit_code = 0;
141 thread->next = NULL;
142 thread->prev = NULL;
143 thread->priority = THREAD_PRIORITY_NORMAL;
144 thread->affinity = 1;
145 thread->suspend = (suspend != 0);
146 thread->buffer = (void *)-1;
147 thread->last_req = REQ_GET_THREAD_BUFFER;
148 thread->process = (struct process *)grab_object( process );
150 if (!current) current = thread;
152 if (!booting_thread) /* first thread ever */
154 booting_thread = thread;
155 lock_master_socket(1);
158 if ((thread->next = first_thread) != NULL) thread->next->prev = thread;
159 first_thread = thread;
160 add_process_thread( process, 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 remove_process_thread( process, thread );
168 release_object( thread );
169 return NULL;
172 /* handle a client event */
173 void thread_poll_event( struct object *obj, int event )
175 struct thread *thread = (struct thread *)obj;
176 assert( obj->ops == &thread_ops );
178 if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
179 else
181 if (event & POLLOUT) write_request( thread );
182 if (event & POLLIN) read_request( thread );
186 /* destroy a thread when its refcount is 0 */
187 static void destroy_thread( struct object *obj )
189 struct thread *thread = (struct thread *)obj;
190 assert( obj->ops == &thread_ops );
192 assert( !thread->debug_ctx ); /* cannot still be debugging something */
193 release_object( thread->process );
194 if (thread->next) thread->next->prev = thread->prev;
195 if (thread->prev) thread->prev->next = thread->next;
196 else first_thread = thread->next;
197 if (thread->apc) free( thread->apc );
198 if (thread->buffer != (void *)-1) munmap( thread->buffer, MAX_REQUEST_LENGTH );
199 if (thread->pass_fd != -1) close( thread->pass_fd );
202 /* dump a thread on stdout for debugging purposes */
203 static void dump_thread( struct object *obj, int verbose )
205 struct thread *thread = (struct thread *)obj;
206 assert( obj->ops == &thread_ops );
208 fprintf( stderr, "Thread pid=%d teb=%p state=%d\n",
209 thread->unix_pid, thread->teb, thread->state );
212 static int thread_signaled( struct object *obj, struct thread *thread )
214 struct thread *mythread = (struct thread *)obj;
215 return (mythread->state == TERMINATED);
218 /* get a thread pointer from a thread id (and increment the refcount) */
219 struct thread *get_thread_from_id( void *id )
221 struct thread *t = first_thread;
222 while (t && (t != id)) t = t->next;
223 if (t) grab_object( t );
224 return t;
227 /* get a thread from a handle (and increment the refcount) */
228 struct thread *get_thread_from_handle( int handle, unsigned int access )
230 return (struct thread *)get_handle_obj( current->process, handle,
231 access, &thread_ops );
234 /* find a thread from a Unix pid */
235 struct thread *get_thread_from_pid( int pid )
237 struct thread *t = first_thread;
238 while (t && (t->unix_pid != pid)) t = t->next;
239 return t;
242 /* set all information about a thread */
243 static void set_thread_info( struct thread *thread,
244 struct set_thread_info_request *req )
246 if (req->mask & SET_THREAD_INFO_PRIORITY)
247 thread->priority = req->priority;
248 if (req->mask & SET_THREAD_INFO_AFFINITY)
250 if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
251 else thread->affinity = req->affinity;
255 /* suspend a thread */
256 int suspend_thread( struct thread *thread, int check_limit )
258 int old_count = thread->suspend;
259 if (thread->suspend < MAXIMUM_SUSPEND_COUNT || !check_limit)
261 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
263 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
264 return old_count;
267 /* resume a thread */
268 int resume_thread( struct thread *thread )
270 int old_count = thread->suspend;
271 if (thread->suspend > 0)
273 if (!(--thread->suspend + thread->process->suspend)) continue_thread( thread );
275 return old_count;
278 /* suspend all threads but the current */
279 void suspend_all_threads( void )
281 struct thread *thread;
282 for ( thread = first_thread; thread; thread = thread->next )
283 if ( thread != current )
284 suspend_thread( thread, 0 );
287 /* resume all threads but the current */
288 void resume_all_threads( void )
290 struct thread *thread;
291 for ( thread = first_thread; thread; thread = thread->next )
292 if ( thread != current )
293 resume_thread( thread );
296 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
297 int add_queue( struct object *obj, struct wait_queue_entry *entry )
299 grab_object( obj );
300 entry->obj = obj;
301 entry->prev = obj->tail;
302 entry->next = NULL;
303 if (obj->tail) obj->tail->next = entry;
304 else obj->head = entry;
305 obj->tail = entry;
306 return 1;
309 /* remove a thread from an object wait queue */
310 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
312 if (entry->next) entry->next->prev = entry->prev;
313 else obj->tail = entry->prev;
314 if (entry->prev) entry->prev->next = entry->next;
315 else obj->head = entry->next;
316 release_object( obj );
319 /* finish waiting */
320 static void end_wait( struct thread *thread )
322 struct thread_wait *wait = thread->wait;
323 struct wait_queue_entry *entry;
324 int i;
326 assert( wait );
327 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
328 entry->obj->ops->remove_queue( entry->obj, entry );
329 if (wait->user) remove_timeout_user( wait->user );
330 free( wait );
331 thread->wait = NULL;
334 /* build the thread wait structure */
335 static int wait_on( int count, struct object *objects[], int flags,
336 int timeout, sleep_reply func )
338 struct thread_wait *wait;
339 struct wait_queue_entry *entry;
340 int i;
342 if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
343 current->wait = wait;
344 wait->count = count;
345 wait->flags = flags;
346 wait->user = NULL;
347 wait->reply = func;
348 if (flags & SELECT_TIMEOUT)
350 gettimeofday( &wait->timeout, 0 );
351 add_timeout( &wait->timeout, timeout );
354 for (i = 0, entry = wait->queues; i < count; i++, entry++)
356 struct object *obj = objects[i];
357 entry->thread = current;
358 if (!obj->ops->add_queue( obj, entry ))
360 wait->count = i;
361 end_wait( current );
362 return 0;
365 return 1;
368 /* check if the thread waiting condition is satisfied */
369 static int check_wait( struct thread *thread, struct object **object )
371 int i, signaled;
372 struct thread_wait *wait = thread->wait;
373 struct wait_queue_entry *entry = wait->queues;
375 assert( wait );
376 *object = NULL;
377 if (wait->flags & SELECT_ALL)
379 int not_ok = 0;
380 /* Note: we must check them all anyway, as some objects may
381 * want to do something when signaled, even if others are not */
382 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
383 not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
384 if (not_ok) goto other_checks;
385 /* Wait satisfied: tell it to all objects */
386 signaled = 0;
387 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
388 if (entry->obj->ops->satisfied( entry->obj, thread ))
389 signaled = STATUS_ABANDONED_WAIT_0;
390 return signaled;
392 else
394 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
396 if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
397 /* Wait satisfied: tell it to the object */
398 signaled = i;
399 *object = entry->obj;
400 if (entry->obj->ops->satisfied( entry->obj, thread ))
401 signaled = i + STATUS_ABANDONED_WAIT_0;
402 return signaled;
406 other_checks:
407 if ((wait->flags & SELECT_ALERTABLE) && thread->apc) return STATUS_USER_APC;
408 if (wait->flags & SELECT_TIMEOUT)
410 struct timeval now;
411 gettimeofday( &now, NULL );
412 if (!time_before( &now, &wait->timeout )) return STATUS_TIMEOUT;
414 return -1;
417 /* build a reply to the select request */
418 static void build_select_reply( struct thread *thread, struct object *obj, int signaled )
420 struct select_request *req = get_req_ptr( thread );
421 req->signaled = signaled;
424 /* attempt to wake up a thread */
425 /* return 1 if OK, 0 if the wait condition is still not satisfied */
426 static int wake_thread( struct thread *thread )
428 int signaled;
429 struct object *object;
430 if ((signaled = check_wait( thread, &object )) == -1) return 0;
431 thread->error = 0;
432 thread->wait->reply( thread, object, signaled );
433 end_wait( thread );
434 return 1;
437 /* thread wait timeout */
438 static void thread_timeout( void *ptr )
440 struct thread *thread = ptr;
441 if (debug_level) fprintf( stderr, "%08x: *timeout*\n", (unsigned int)thread );
442 assert( thread->wait );
443 thread->error = 0;
444 thread->wait->user = NULL;
445 thread->wait->reply( thread, NULL, STATUS_TIMEOUT );
446 end_wait( thread );
447 send_reply( thread );
450 /* sleep on a list of objects */
451 int sleep_on( int count, struct object *objects[], int flags, int timeout, sleep_reply func )
453 assert( !current->wait );
454 if (!wait_on( count, objects, flags, timeout, func )) return 0;
455 if (wake_thread( current )) return 1;
456 /* now we need to wait */
457 if (flags & SELECT_TIMEOUT)
459 if (!(current->wait->user = add_timeout_user( &current->wait->timeout,
460 thread_timeout, current )))
462 end_wait( current );
463 return 0;
466 return 1;
469 /* select on a list of handles */
470 static int select_on( int count, int *handles, int flags, int timeout )
472 int ret = 0;
473 int i;
474 struct object *objects[MAXIMUM_WAIT_OBJECTS];
476 if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
478 set_error( STATUS_INVALID_PARAMETER );
479 return 0;
481 for (i = 0; i < count; i++)
483 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
484 break;
486 if (i == count) ret = sleep_on( count, objects, flags, timeout, build_select_reply );
487 while (--i >= 0) release_object( objects[i] );
488 return ret;
491 /* attempt to wake threads sleeping on the object wait queue */
492 void wake_up( struct object *obj, int max )
494 struct wait_queue_entry *entry = obj->head;
496 while (entry)
498 struct thread *thread = entry->thread;
499 entry = entry->next;
500 if (wake_thread( thread ))
502 send_reply( thread );
503 if (max && !--max) break;
508 /* queue an async procedure call */
509 static int thread_queue_apc( struct thread *thread, void *func, void *param )
511 struct thread_apc *apc;
512 if (!thread->apc)
514 if (!(thread->apc = mem_alloc( MAX_THREAD_APC * sizeof(*apc) )))
515 return 0;
516 thread->apc_count = 0;
518 else if (thread->apc_count >= MAX_THREAD_APC) return 0;
519 thread->apc[thread->apc_count].func = func;
520 thread->apc[thread->apc_count].param = param;
521 thread->apc_count++;
522 if (thread->wait)
524 if (wake_thread( thread )) send_reply( thread );
526 return 1;
529 /* retrieve an LDT selector entry */
530 static void get_selector_entry( struct thread *thread, int entry,
531 unsigned int *base, unsigned int *limit,
532 unsigned char *flags )
534 if (!thread->process->ldt_copy || !thread->process->ldt_flags)
536 set_error( STATUS_ACCESS_DENIED );
537 return;
539 if (entry >= 8192)
541 set_error( STATUS_INVALID_PARAMETER ); /* FIXME */
542 return;
544 if (suspend_for_ptrace( thread ))
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 done:
554 resume_thread( thread );
558 /* kill a thread on the spot */
559 void kill_thread( struct thread *thread, int violent_death )
561 if (thread->state == TERMINATED) return; /* already killed */
562 thread->state = TERMINATED;
563 if (current == thread) current = NULL;
564 if (debug_level)
565 fprintf( stderr,"%08x: *killed* exit_code=%d\n",
566 (unsigned int)thread, thread->exit_code );
567 if (thread->wait)
569 end_wait( thread );
570 /* if it is waiting on the socket, we don't need to send a SIGTERM */
571 violent_death = 0;
573 debug_exit_thread( thread );
574 abandon_mutexes( thread );
575 remove_process_thread( thread->process, thread );
576 wake_up( &thread->obj, 0 );
577 detach_thread( thread, violent_death ? SIGTERM : 0 );
578 remove_select_user( &thread->obj );
579 release_object( thread );
582 /* signal that we are finished booting on the client side */
583 DECL_HANDLER(boot_done)
585 debug_level = req->debug_level;
586 /* Make sure last_req is initialized */
587 current->last_req = REQ_BOOT_DONE;
588 if (current == booting_thread)
590 booting_thread = (struct thread *)~0UL; /* make sure it doesn't match other threads */
591 lock_master_socket(0); /* allow other clients now */
595 /* create a new thread */
596 DECL_HANDLER(new_thread)
598 struct thread *thread;
599 int sock[2];
601 if (socketpair( AF_UNIX, SOCK_STREAM, 0, sock ) != -1)
603 if ((thread = create_thread( sock[0], current->process, req->suspend )))
605 req->tid = thread;
606 if ((req->handle = alloc_handle( current->process, thread,
607 THREAD_ALL_ACCESS, req->inherit )) != -1)
609 set_reply_fd( current, sock[1] );
610 /* thread object will be released when the thread gets killed */
611 return;
613 release_object( thread );
615 close( sock[1] );
617 else file_set_error();
620 /* retrieve the thread buffer file descriptor */
621 DECL_HANDLER(get_thread_buffer)
623 fatal_protocol_error( current, "get_thread_buffer: should never get called directly\n" );
626 /* initialize a new thread */
627 DECL_HANDLER(init_thread)
629 if (current->unix_pid)
631 fatal_protocol_error( current, "init_thread: already running\n" );
632 return;
634 current->unix_pid = req->unix_pid;
635 current->teb = req->teb;
636 current->entry = req->entry;
637 if (current->suspend + current->process->suspend > 0) stop_thread( current );
638 if (current->process->running_threads > 1)
639 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, current );
642 /* terminate a thread */
643 DECL_HANDLER(terminate_thread)
645 struct thread *thread;
647 req->self = 0;
648 req->last = 0;
649 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
651 thread->exit_code = req->exit_code;
652 if (thread != current) kill_thread( thread, 1 );
653 else
655 req->self = 1;
656 req->last = (thread->process->running_threads == 1);
658 release_object( thread );
662 /* fetch information about a thread */
663 DECL_HANDLER(get_thread_info)
665 struct thread *thread;
667 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
669 req->tid = thread;
670 req->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STILL_ACTIVE;
671 req->priority = thread->priority;
672 release_object( thread );
676 /* set information about a thread */
677 DECL_HANDLER(set_thread_info)
679 struct thread *thread;
681 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
683 set_thread_info( thread, req );
684 release_object( thread );
688 /* suspend a thread */
689 DECL_HANDLER(suspend_thread)
691 struct thread *thread;
693 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
695 req->count = suspend_thread( thread, 1 );
696 release_object( thread );
700 /* resume a thread */
701 DECL_HANDLER(resume_thread)
703 struct thread *thread;
705 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
707 req->count = resume_thread( thread );
708 release_object( thread );
712 /* select on a handle list */
713 DECL_HANDLER(select)
715 if (!select_on( req->count, req->handles, req->flags, req->timeout ))
716 req->signaled = -1;
719 /* queue an APC for a thread */
720 DECL_HANDLER(queue_apc)
722 struct thread *thread;
723 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
725 thread_queue_apc( thread, req->func, req->param );
726 release_object( thread );
730 /* get list of APC to call */
731 DECL_HANDLER(get_apcs)
733 if ((req->count = current->apc_count))
735 memcpy( req->apcs, current->apc, current->apc_count * sizeof(*current->apc) );
736 free( current->apc );
737 current->apc = NULL;
738 current->apc_count = 0;
742 /* fetch a selector entry for a thread */
743 DECL_HANDLER(get_selector_entry)
745 struct thread *thread;
746 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
748 get_selector_entry( thread, req->entry, &req->base, &req->limit, &req->flags );
749 release_object( thread );