2 * Server-side thread management
4 * Copyright (C) 1998 Alexandre Julliard
16 #ifdef HAVE_SYS_MMAN_H
19 #include <sys/types.h>
20 #ifdef HAVE_SYS_SOCKET_H
21 # include <sys/socket.h>
39 int count; /* count of objects */
41 struct timeval timeout;
42 struct timeout_user *user;
43 sleep_reply reply; /* function to build the reply */
44 struct wait_queue_entry queues[1];
47 /* asynchronous procedure calls */
51 struct thread_apc *next; /* queue linked list */
52 struct thread_apc *prev;
53 struct object *owner; /* object that queued this apc */
54 void *func; /* function to call in client */
55 enum apc_type type; /* type of apc function */
56 int nb_args; /* number of arguments */
57 void *args[1]; /* function arguments */
61 /* thread operations */
63 static void dump_thread( struct object *obj, int verbose );
64 static int thread_signaled( struct object *obj, struct thread *thread );
65 extern void thread_poll_event( struct object *obj, int event );
66 static void destroy_thread( struct object *obj );
67 static struct thread_apc *thread_dequeue_apc( struct thread *thread );
69 static const struct object_ops thread_ops =
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 */
82 no_get_file_info, /* get_file_info */
83 destroy_thread /* destroy */
86 static struct thread *first_thread;
87 static struct thread *booting_thread;
89 /* allocate the buffer for the communication with the client */
90 static int alloc_client_buffer( struct thread *thread )
92 struct get_thread_buffer_request *req;
95 if ((fd = create_anonymous_file()) == -1) return -1;
96 if (ftruncate( fd, MAX_REQUEST_LENGTH ) == -1) goto error;
97 if ((thread->buffer = mmap( 0, MAX_REQUEST_LENGTH, PROT_READ | PROT_WRITE,
98 MAP_SHARED, fd, 0 )) == (void*)-1) goto error;
99 thread->buffer_info = (struct server_buffer_info *)((char *)thread->buffer + MAX_REQUEST_LENGTH) - 1;
100 /* build the first request into the buffer and send it */
101 req = thread->buffer;
102 req->pid = get_process_id( thread->process );
103 req->tid = get_thread_id( thread );
104 req->boot = (thread == booting_thread);
105 req->version = SERVER_PROTOCOL_VERSION;
106 set_reply_fd( thread, fd );
107 send_reply( thread );
112 if (fd != -1) close( fd );
116 /* create a new thread */
117 struct thread *create_thread( int fd, struct process *process )
119 struct thread *thread;
121 int flags = fcntl( fd, F_GETFL, 0 );
122 fcntl( fd, F_SETFL, flags | O_NONBLOCK );
124 if (!(thread = alloc_object( &thread_ops, fd ))) return NULL;
126 thread->unix_pid = 0; /* not known yet */
127 thread->context = NULL;
129 thread->mutex = NULL;
130 thread->debug_ctx = NULL;
131 thread->debug_event = NULL;
132 thread->queue = NULL;
135 thread->apc_head = NULL;
136 thread->apc_tail = NULL;
138 thread->pass_fd = -1;
139 thread->state = RUNNING;
140 thread->attached = 0;
141 thread->exit_code = 0;
144 thread->priority = THREAD_PRIORITY_NORMAL;
145 thread->affinity = 1;
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;
167 release_object( thread );
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 );
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_apc *apc;
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 while ((apc = thread_dequeue_apc( thread ))) free( apc );
198 if (thread->info) release_object( thread->info );
199 if (thread->queue) release_object( thread->queue );
200 if (thread->buffer != (void *)-1) munmap( thread->buffer, MAX_REQUEST_LENGTH );
201 if (thread->pass_fd != -1) close( thread->pass_fd );
204 /* dump a thread on stdout for debugging purposes */
205 static void dump_thread( struct object *obj, int verbose )
207 struct thread *thread = (struct thread *)obj;
208 assert( obj->ops == &thread_ops );
210 fprintf( stderr, "Thread pid=%d teb=%p state=%d\n",
211 thread->unix_pid, thread->teb, thread->state );
214 static int thread_signaled( struct object *obj, struct thread *thread )
216 struct thread *mythread = (struct thread *)obj;
217 return (mythread->state == TERMINATED);
220 /* get a thread pointer from a thread id (and increment the refcount) */
221 struct thread *get_thread_from_id( void *id )
223 struct thread *t = first_thread;
224 while (t && (t != id)) t = t->next;
225 if (t) grab_object( t );
229 /* get a thread from a handle (and increment the refcount) */
230 struct thread *get_thread_from_handle( int handle, unsigned int access )
232 return (struct thread *)get_handle_obj( current->process, handle,
233 access, &thread_ops );
236 /* find a thread from a Unix pid */
237 struct thread *get_thread_from_pid( int pid )
239 struct thread *t = first_thread;
240 while (t && (t->unix_pid != pid)) t = t->next;
244 /* set all information about a thread */
245 static void set_thread_info( struct thread *thread,
246 struct set_thread_info_request *req )
248 if (req->mask & SET_THREAD_INFO_PRIORITY)
249 thread->priority = req->priority;
250 if (req->mask & SET_THREAD_INFO_AFFINITY)
252 if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
253 else thread->affinity = req->affinity;
257 /* suspend a thread */
258 int suspend_thread( struct thread *thread, int check_limit )
260 int old_count = thread->suspend;
261 if (thread->suspend < MAXIMUM_SUSPEND_COUNT || !check_limit)
263 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
265 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
269 /* resume a thread */
270 int resume_thread( struct thread *thread )
272 int old_count = thread->suspend;
273 if (thread->suspend > 0)
275 if (!(--thread->suspend + thread->process->suspend)) continue_thread( thread );
280 /* suspend all threads but the current */
281 void suspend_all_threads( void )
283 struct thread *thread;
284 for ( thread = first_thread; thread; thread = thread->next )
285 if ( thread != current )
286 suspend_thread( thread, 0 );
289 /* resume all threads but the current */
290 void resume_all_threads( void )
292 struct thread *thread;
293 for ( thread = first_thread; thread; thread = thread->next )
294 if ( thread != current )
295 resume_thread( thread );
298 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
299 int add_queue( struct object *obj, struct wait_queue_entry *entry )
303 entry->prev = obj->tail;
305 if (obj->tail) obj->tail->next = entry;
306 else obj->head = entry;
311 /* remove a thread from an object wait queue */
312 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
314 if (entry->next) entry->next->prev = entry->prev;
315 else obj->tail = entry->prev;
316 if (entry->prev) entry->prev->next = entry->next;
317 else obj->head = entry->next;
318 release_object( obj );
322 static void end_wait( struct thread *thread )
324 struct thread_wait *wait = thread->wait;
325 struct wait_queue_entry *entry;
329 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
330 entry->obj->ops->remove_queue( entry->obj, entry );
331 if (wait->user) remove_timeout_user( wait->user );
336 /* build the thread wait structure */
337 static int wait_on( int count, struct object *objects[], int flags,
338 int timeout, sleep_reply func )
340 struct thread_wait *wait;
341 struct wait_queue_entry *entry;
344 if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
345 current->wait = wait;
350 if (flags & SELECT_TIMEOUT)
352 gettimeofday( &wait->timeout, 0 );
353 add_timeout( &wait->timeout, timeout );
356 for (i = 0, entry = wait->queues; i < count; i++, entry++)
358 struct object *obj = objects[i];
359 entry->thread = current;
360 if (!obj->ops->add_queue( obj, entry ))
370 /* check if the thread waiting condition is satisfied */
371 static int check_wait( struct thread *thread, struct object **object )
374 struct thread_wait *wait = thread->wait;
375 struct wait_queue_entry *entry = wait->queues;
379 if (wait->flags & SELECT_ALL)
382 /* Note: we must check them all anyway, as some objects may
383 * want to do something when signaled, even if others are not */
384 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
385 not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
386 if (not_ok) goto other_checks;
387 /* Wait satisfied: tell it to all objects */
389 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
390 if (entry->obj->ops->satisfied( entry->obj, thread ))
391 signaled = STATUS_ABANDONED_WAIT_0;
396 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
398 if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
399 /* Wait satisfied: tell it to the object */
401 *object = entry->obj;
402 if (entry->obj->ops->satisfied( entry->obj, thread ))
403 signaled = i + STATUS_ABANDONED_WAIT_0;
409 if ((wait->flags & SELECT_ALERTABLE) && thread->apc_head) return STATUS_USER_APC;
410 if (wait->flags & SELECT_TIMEOUT)
413 gettimeofday( &now, NULL );
414 if (!time_before( &now, &wait->timeout )) return STATUS_TIMEOUT;
419 /* build a reply to the select request */
420 static void build_select_reply( struct thread *thread, struct object *obj, int signaled )
422 struct select_request *req = get_req_ptr( thread );
423 req->signaled = signaled;
426 /* attempt to wake up a thread */
427 /* return 1 if OK, 0 if the wait condition is still not satisfied */
428 static int wake_thread( struct thread *thread )
431 struct object *object;
432 if ((signaled = check_wait( thread, &object )) == -1) return 0;
434 thread->wait->reply( thread, object, signaled );
439 /* thread wait timeout */
440 static void thread_timeout( void *ptr )
442 struct thread *thread = ptr;
443 if (debug_level) fprintf( stderr, "%08x: *timeout*\n", (unsigned int)thread );
444 assert( thread->wait );
446 thread->wait->user = NULL;
447 thread->wait->reply( thread, NULL, STATUS_TIMEOUT );
449 send_reply( thread );
452 /* sleep on a list of objects */
453 int sleep_on( int count, struct object *objects[], int flags, int timeout, sleep_reply func )
455 assert( !current->wait );
456 if (!wait_on( count, objects, flags, timeout, func )) return 0;
457 if (wake_thread( current )) return 1;
458 /* now we need to wait */
459 if (flags & SELECT_TIMEOUT)
461 if (!(current->wait->user = add_timeout_user( ¤t->wait->timeout,
462 thread_timeout, current )))
471 /* select on a list of handles */
472 static int select_on( int count, int *handles, int flags, int timeout )
476 struct object *objects[MAXIMUM_WAIT_OBJECTS];
478 if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
480 set_error( STATUS_INVALID_PARAMETER );
483 for (i = 0; i < count; i++)
485 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
488 if (i == count) ret = sleep_on( count, objects, flags, timeout, build_select_reply );
489 while (--i >= 0) release_object( objects[i] );
493 /* attempt to wake threads sleeping on the object wait queue */
494 void wake_up( struct object *obj, int max )
496 struct wait_queue_entry *entry = obj->head;
500 struct thread *thread = entry->thread;
502 if (wake_thread( thread ))
504 send_reply( thread );
505 if (max && !--max) break;
510 /* queue an async procedure call */
511 int thread_queue_apc( struct thread *thread, struct object *owner, void *func,
512 enum apc_type type, int nb_args, ... )
514 struct thread_apc *apc;
516 /* cancel a possible previous APC with the same owner */
517 if (owner) thread_cancel_apc( thread, owner );
519 if (!(apc = mem_alloc( sizeof(*apc) + (nb_args-1)*sizeof(apc->args[0]) ))) return 0;
520 apc->prev = thread->apc_tail;
525 apc->nb_args = nb_args;
530 va_start( args, nb_args );
531 for (i = 0; i < nb_args; i++) apc->args[i] = va_arg( args, void * );
534 thread->apc_tail = apc;
535 if (!apc->prev) /* first one */
537 thread->apc_head = apc;
538 if (thread->wait && wake_thread( thread )) send_reply( thread );
543 /* cancel the async procedure call owned by a specific object */
544 void thread_cancel_apc( struct thread *thread, struct object *owner )
546 struct thread_apc *apc;
547 for (apc = thread->apc_head; apc; apc = apc->next)
549 if (apc->owner != owner) continue;
550 if (apc->next) apc->next->prev = apc->prev;
551 else thread->apc_tail = apc->prev;
552 if (apc->prev) apc->prev->next = apc->next;
553 else thread->apc_head = apc->next;
559 /* remove the head apc from the queue; the returned pointer must be freed by the caller */
560 static struct thread_apc *thread_dequeue_apc( struct thread *thread )
562 struct thread_apc *apc = thread->apc_head;
565 if (apc->next) apc->next->prev = NULL;
566 else thread->apc_tail = NULL;
567 thread->apc_head = apc->next;
572 /* retrieve an LDT selector entry */
573 static void get_selector_entry( struct thread *thread, int entry,
574 unsigned int *base, unsigned int *limit,
575 unsigned char *flags )
577 if (!thread->process->ldt_copy || !thread->process->ldt_flags)
579 set_error( STATUS_ACCESS_DENIED );
584 set_error( STATUS_INVALID_PARAMETER ); /* FIXME */
587 if (suspend_for_ptrace( thread ))
589 unsigned char flags_buf[4];
590 int *addr = (int *)thread->process->ldt_copy + 2 * entry;
591 if (read_thread_int( thread, addr, base ) == -1) goto done;
592 if (read_thread_int( thread, addr + 1, limit ) == -1) goto done;
593 addr = (int *)thread->process->ldt_flags + (entry >> 2);
594 if (read_thread_int( thread, addr, (int *)flags_buf ) == -1) goto done;
595 *flags = flags_buf[entry & 3];
597 resume_thread( thread );
601 /* kill a thread on the spot */
602 void kill_thread( struct thread *thread, int violent_death )
604 if (thread->state == TERMINATED) return; /* already killed */
605 thread->state = TERMINATED;
606 if (current == thread) current = NULL;
608 fprintf( stderr,"%08x: *killed* exit_code=%d\n",
609 (unsigned int)thread, thread->exit_code );
613 /* if it is waiting on the socket, we don't need to send a SIGTERM */
616 debug_exit_thread( thread );
617 abandon_mutexes( thread );
618 remove_process_thread( thread->process, thread );
619 wake_up( &thread->obj, 0 );
620 detach_thread( thread, violent_death ? SIGTERM : 0 );
621 remove_select_user( &thread->obj );
622 munmap( thread->buffer, MAX_REQUEST_LENGTH );
623 thread->buffer = (void *)-1;
624 release_object( thread );
627 /* take a snapshot of currently running threads */
628 struct thread_snapshot *thread_snap( int *count )
630 struct thread_snapshot *snapshot, *ptr;
631 struct thread *thread;
634 for (thread = first_thread; thread; thread = thread->next)
635 if (thread->state != TERMINATED) total++;
636 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
638 for (thread = first_thread; thread; thread = thread->next)
640 if (thread->state == TERMINATED) continue;
641 ptr->thread = thread;
642 ptr->count = thread->obj.refcount;
643 ptr->priority = thread->priority;
644 grab_object( thread );
651 /* signal that we are finished booting on the client side */
652 DECL_HANDLER(boot_done)
654 debug_level = max( debug_level, req->debug_level );
655 /* Make sure last_req is initialized */
656 current->last_req = REQ_BOOT_DONE;
657 if (current == booting_thread)
659 booting_thread = (struct thread *)~0UL; /* make sure it doesn't match other threads */
660 lock_master_socket(0); /* allow other clients now */
664 /* create a new thread */
665 DECL_HANDLER(new_thread)
667 struct thread *thread;
670 if (socketpair( AF_UNIX, SOCK_STREAM, 0, sock ) != -1)
672 if ((thread = create_thread( sock[0], current->process )))
674 if (req->suspend) thread->suspend++;
676 if ((req->handle = alloc_handle( current->process, thread,
677 THREAD_ALL_ACCESS, req->inherit )) != -1)
679 set_reply_fd( current, sock[1] );
680 /* thread object will be released when the thread gets killed */
681 add_process_thread( current->process, thread );
684 release_object( thread );
688 else file_set_error();
691 /* retrieve the thread buffer file descriptor */
692 DECL_HANDLER(get_thread_buffer)
694 fatal_protocol_error( current, "get_thread_buffer: should never get called directly\n" );
697 /* initialize a new thread */
698 DECL_HANDLER(init_thread)
700 if (current->unix_pid)
702 fatal_protocol_error( current, "init_thread: already running\n" );
705 current->unix_pid = req->unix_pid;
706 current->teb = req->teb;
707 if (current->suspend + current->process->suspend > 0) stop_thread( current );
708 if (current->process->running_threads > 1)
709 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
712 /* terminate a thread */
713 DECL_HANDLER(terminate_thread)
715 struct thread *thread;
719 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
721 thread->exit_code = req->exit_code;
722 if (thread != current) kill_thread( thread, 1 );
726 req->last = (thread->process->running_threads == 1);
728 release_object( thread );
732 /* fetch information about a thread */
733 DECL_HANDLER(get_thread_info)
735 struct thread *thread;
736 int handle = req->handle;
738 if (handle == -1) thread = get_thread_from_id( req->tid_in );
739 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
743 req->tid = get_thread_id( thread );
744 req->teb = thread->teb;
745 req->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STILL_ACTIVE;
746 req->priority = thread->priority;
747 release_object( thread );
751 /* set information about a thread */
752 DECL_HANDLER(set_thread_info)
754 struct thread *thread;
756 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
758 set_thread_info( thread, req );
759 release_object( thread );
763 /* suspend a thread */
764 DECL_HANDLER(suspend_thread)
766 struct thread *thread;
768 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
770 req->count = suspend_thread( thread, 1 );
771 release_object( thread );
775 /* resume a thread */
776 DECL_HANDLER(resume_thread)
778 struct thread *thread;
780 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
782 req->count = resume_thread( thread );
783 release_object( thread );
787 /* select on a handle list */
790 int count = get_req_data_size(req) / sizeof(int);
791 if (!select_on( count, get_req_data(req), req->flags, req->timeout ))
795 /* queue an APC for a thread */
796 DECL_HANDLER(queue_apc)
798 struct thread *thread;
799 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
801 thread_queue_apc( thread, NULL, req->func, APC_USER, 1, req->param );
802 release_object( thread );
806 /* get next APC to call */
807 DECL_HANDLER(get_apc)
809 struct thread_apc *apc;
814 if (!(apc = thread_dequeue_apc( current )))
818 req->type = APC_NONE;
819 set_req_data_size( req, 0 );
822 /* Optimization: ignore APCs that have a NULL func; they are only used
823 * to wake up a thread, but since we got here the thread woke up already.
825 if (apc->func) break;
828 size = apc->nb_args * sizeof(apc->args[0]);
829 if (size > get_req_data_size(req)) size = get_req_data_size(req);
830 req->func = apc->func;
831 req->type = apc->type;
832 memcpy( get_req_data(req), apc->args, size );
833 set_req_data_size( req, size );
837 /* fetch a selector entry for a thread */
838 DECL_HANDLER(get_selector_entry)
840 struct thread *thread;
841 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
843 get_selector_entry( thread, req->entry, &req->base, &req->limit, &req->flags );
844 release_object( thread );