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_get_fd, /* get_fd */
81 no_get_file_info, /* get_file_info */
82 destroy_thread /* destroy */
85 static struct thread *first_thread;
86 static struct thread *booting_thread;
88 /* allocate the buffer for the communication with the client */
89 static int alloc_client_buffer( struct thread *thread )
91 struct get_thread_buffer_request *req;
94 if ((fd = create_anonymous_file()) == -1) return -1;
95 if (ftruncate( fd, MAX_REQUEST_LENGTH ) == -1) goto error;
96 if ((thread->buffer = mmap( 0, MAX_REQUEST_LENGTH, PROT_READ | PROT_WRITE,
97 MAP_SHARED, fd, 0 )) == (void*)-1) goto error;
98 thread->buffer_info = (struct server_buffer_info *)((char *)thread->buffer + MAX_REQUEST_LENGTH) - 1;
99 /* build the first request into the buffer and send it */
100 req = thread->buffer;
101 req->pid = get_process_id( thread->process );
102 req->tid = get_thread_id( thread );
103 req->boot = (thread == booting_thread);
104 req->version = SERVER_PROTOCOL_VERSION;
105 set_reply_fd( thread, fd );
106 send_reply( thread );
111 if (fd != -1) close( fd );
115 /* create a new thread */
116 struct thread *create_thread( int fd, struct process *process )
118 struct thread *thread;
120 int flags = fcntl( fd, F_GETFL, 0 );
121 fcntl( fd, F_SETFL, flags | O_NONBLOCK );
123 if (!(thread = alloc_object( &thread_ops, fd ))) return NULL;
125 thread->unix_pid = 0; /* not known yet */
126 thread->context = NULL;
128 thread->mutex = NULL;
129 thread->debug_ctx = NULL;
130 thread->debug_event = NULL;
131 thread->queue = NULL;
134 thread->apc_head = NULL;
135 thread->apc_tail = NULL;
137 thread->pass_fd = -1;
138 thread->state = RUNNING;
139 thread->attached = 0;
140 thread->exit_code = 0;
143 thread->priority = THREAD_PRIORITY_NORMAL;
144 thread->affinity = 1;
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;
161 set_select_events( &thread->obj, POLLIN ); /* start listening to events */
162 if (!alloc_client_buffer( thread )) goto error;
166 release_object( thread );
170 /* handle a client event */
171 void thread_poll_event( struct object *obj, int event )
173 struct thread *thread = (struct thread *)obj;
174 assert( obj->ops == &thread_ops );
176 if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
179 if (event & POLLOUT) write_request( thread );
180 if (event & POLLIN) read_request( thread );
184 /* destroy a thread when its refcount is 0 */
185 static void destroy_thread( struct object *obj )
187 struct thread_apc *apc;
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 while ((apc = thread_dequeue_apc( thread ))) free( apc );
197 if (thread->info) release_object( thread->info );
198 if (thread->queue) release_object( thread->queue );
199 if (thread->buffer != (void *)-1) munmap( thread->buffer, MAX_REQUEST_LENGTH );
200 if (thread->pass_fd != -1) close( thread->pass_fd );
203 /* dump a thread on stdout for debugging purposes */
204 static void dump_thread( struct object *obj, int verbose )
206 struct thread *thread = (struct thread *)obj;
207 assert( obj->ops == &thread_ops );
209 fprintf( stderr, "Thread pid=%d teb=%p state=%d\n",
210 thread->unix_pid, thread->teb, thread->state );
213 static int thread_signaled( struct object *obj, struct thread *thread )
215 struct thread *mythread = (struct thread *)obj;
216 return (mythread->state == TERMINATED);
219 /* get a thread pointer from a thread id (and increment the refcount) */
220 struct thread *get_thread_from_id( void *id )
222 struct thread *t = first_thread;
223 while (t && (t != id)) t = t->next;
224 if (t) grab_object( t );
228 /* get a thread from a handle (and increment the refcount) */
229 struct thread *get_thread_from_handle( int handle, unsigned int access )
231 return (struct thread *)get_handle_obj( current->process, handle,
232 access, &thread_ops );
235 /* find a thread from a Unix pid */
236 struct thread *get_thread_from_pid( int pid )
238 struct thread *t = first_thread;
239 while (t && (t->unix_pid != pid)) t = t->next;
243 /* set all information about a thread */
244 static void set_thread_info( struct thread *thread,
245 struct set_thread_info_request *req )
247 if (req->mask & SET_THREAD_INFO_PRIORITY)
248 thread->priority = req->priority;
249 if (req->mask & SET_THREAD_INFO_AFFINITY)
251 if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
252 else thread->affinity = req->affinity;
256 /* suspend a thread */
257 int suspend_thread( struct thread *thread, int check_limit )
259 int old_count = thread->suspend;
260 if (thread->suspend < MAXIMUM_SUSPEND_COUNT || !check_limit)
262 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
264 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
268 /* resume a thread */
269 int resume_thread( struct thread *thread )
271 int old_count = thread->suspend;
272 if (thread->suspend > 0)
274 if (!(--thread->suspend + thread->process->suspend)) continue_thread( thread );
279 /* suspend all threads but the current */
280 void suspend_all_threads( void )
282 struct thread *thread;
283 for ( thread = first_thread; thread; thread = thread->next )
284 if ( thread != current )
285 suspend_thread( thread, 0 );
288 /* resume all threads but the current */
289 void resume_all_threads( void )
291 struct thread *thread;
292 for ( thread = first_thread; thread; thread = thread->next )
293 if ( thread != current )
294 resume_thread( thread );
297 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
298 int add_queue( struct object *obj, struct wait_queue_entry *entry )
302 entry->prev = obj->tail;
304 if (obj->tail) obj->tail->next = entry;
305 else obj->head = entry;
310 /* remove a thread from an object wait queue */
311 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
313 if (entry->next) entry->next->prev = entry->prev;
314 else obj->tail = entry->prev;
315 if (entry->prev) entry->prev->next = entry->next;
316 else obj->head = entry->next;
317 release_object( obj );
321 static void end_wait( struct thread *thread )
323 struct thread_wait *wait = thread->wait;
324 struct wait_queue_entry *entry;
328 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
329 entry->obj->ops->remove_queue( entry->obj, entry );
330 if (wait->user) remove_timeout_user( wait->user );
335 /* build the thread wait structure */
336 static int wait_on( int count, struct object *objects[], int flags,
337 int timeout, sleep_reply func )
339 struct thread_wait *wait;
340 struct wait_queue_entry *entry;
343 if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
344 current->wait = wait;
349 if (flags & SELECT_TIMEOUT)
351 gettimeofday( &wait->timeout, 0 );
352 add_timeout( &wait->timeout, timeout );
355 for (i = 0, entry = wait->queues; i < count; i++, entry++)
357 struct object *obj = objects[i];
358 entry->thread = current;
359 if (!obj->ops->add_queue( obj, entry ))
369 /* check if the thread waiting condition is satisfied */
370 static int check_wait( struct thread *thread, struct object **object )
373 struct thread_wait *wait = thread->wait;
374 struct wait_queue_entry *entry = wait->queues;
378 if (wait->flags & SELECT_ALL)
381 /* Note: we must check them all anyway, as some objects may
382 * want to do something when signaled, even if others are not */
383 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
384 not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
385 if (not_ok) goto other_checks;
386 /* Wait satisfied: tell it to all objects */
388 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
389 if (entry->obj->ops->satisfied( entry->obj, thread ))
390 signaled = STATUS_ABANDONED_WAIT_0;
395 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
397 if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
398 /* Wait satisfied: tell it to the object */
400 *object = entry->obj;
401 if (entry->obj->ops->satisfied( entry->obj, thread ))
402 signaled = i + STATUS_ABANDONED_WAIT_0;
408 if ((wait->flags & SELECT_ALERTABLE) && thread->apc_head) return STATUS_USER_APC;
409 if (wait->flags & SELECT_TIMEOUT)
412 gettimeofday( &now, NULL );
413 if (!time_before( &now, &wait->timeout )) return STATUS_TIMEOUT;
418 /* build a reply to the select request */
419 static void build_select_reply( struct thread *thread, struct object *obj, int signaled )
421 struct select_request *req = get_req_ptr( thread );
422 req->signaled = signaled;
425 /* attempt to wake up a thread */
426 /* return 1 if OK, 0 if the wait condition is still not satisfied */
427 static int wake_thread( struct thread *thread )
430 struct object *object;
431 if ((signaled = check_wait( thread, &object )) == -1) return 0;
433 thread->wait->reply( thread, object, signaled );
438 /* thread wait timeout */
439 static void thread_timeout( void *ptr )
441 struct thread *thread = ptr;
442 if (debug_level) fprintf( stderr, "%08x: *timeout*\n", (unsigned int)thread );
443 assert( thread->wait );
445 thread->wait->user = NULL;
446 thread->wait->reply( thread, NULL, STATUS_TIMEOUT );
448 send_reply( thread );
451 /* sleep on a list of objects */
452 int sleep_on( int count, struct object *objects[], int flags, int timeout, sleep_reply func )
454 assert( !current->wait );
455 if (!wait_on( count, objects, flags, timeout, func )) return 0;
456 if (wake_thread( current )) return 1;
457 /* now we need to wait */
458 if (flags & SELECT_TIMEOUT)
460 if (!(current->wait->user = add_timeout_user( ¤t->wait->timeout,
461 thread_timeout, current )))
470 /* select on a list of handles */
471 static int select_on( int count, int *handles, int flags, int timeout )
475 struct object *objects[MAXIMUM_WAIT_OBJECTS];
477 if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
479 set_error( STATUS_INVALID_PARAMETER );
482 for (i = 0; i < count; i++)
484 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
487 if (i == count) ret = sleep_on( count, objects, flags, timeout, build_select_reply );
488 while (--i >= 0) release_object( objects[i] );
492 /* attempt to wake threads sleeping on the object wait queue */
493 void wake_up( struct object *obj, int max )
495 struct wait_queue_entry *entry = obj->head;
499 struct thread *thread = entry->thread;
501 if (wake_thread( thread ))
503 send_reply( thread );
504 if (max && !--max) break;
509 /* queue an async procedure call */
510 int thread_queue_apc( struct thread *thread, struct object *owner, void *func,
511 enum apc_type type, int nb_args, ... )
513 struct thread_apc *apc;
515 /* cancel a possible previous APC with the same owner */
516 if (owner) thread_cancel_apc( thread, owner );
518 if (!(apc = mem_alloc( sizeof(*apc) + (nb_args-1)*sizeof(apc->args[0]) ))) return 0;
519 apc->prev = thread->apc_tail;
524 apc->nb_args = nb_args;
529 va_start( args, nb_args );
530 for (i = 0; i < nb_args; i++) apc->args[i] = va_arg( args, void * );
533 thread->apc_tail = apc;
534 if (!apc->prev) /* first one */
536 thread->apc_head = apc;
537 if (thread->wait && wake_thread( thread )) send_reply( thread );
542 /* cancel the async procedure call owned by a specific object */
543 void thread_cancel_apc( struct thread *thread, struct object *owner )
545 struct thread_apc *apc;
546 for (apc = thread->apc_head; apc; apc = apc->next)
548 if (apc->owner != owner) continue;
549 if (apc->next) apc->next->prev = apc->prev;
550 else thread->apc_tail = apc->prev;
551 if (apc->prev) apc->prev->next = apc->next;
552 else thread->apc_head = apc->next;
558 /* remove the head apc from the queue; the returned pointer must be freed by the caller */
559 static struct thread_apc *thread_dequeue_apc( struct thread *thread )
561 struct thread_apc *apc = thread->apc_head;
564 if (apc->next) apc->next->prev = NULL;
565 else thread->apc_tail = NULL;
566 thread->apc_head = apc->next;
571 /* retrieve an LDT selector entry */
572 static void get_selector_entry( struct thread *thread, int entry,
573 unsigned int *base, unsigned int *limit,
574 unsigned char *flags )
576 if (!thread->process->ldt_copy)
578 set_error( STATUS_ACCESS_DENIED );
583 set_error( STATUS_INVALID_PARAMETER ); /* FIXME */
586 if (suspend_for_ptrace( thread ))
588 unsigned char flags_buf[4];
589 int *addr = (int *)thread->process->ldt_copy + entry;
590 if (read_thread_int( thread, addr, base ) == -1) goto done;
591 if (read_thread_int( thread, addr + 8192, limit ) == -1) goto done;
592 addr = (int *)thread->process->ldt_copy + 2*8192 + (entry >> 2);
593 if (read_thread_int( thread, addr, (int *)flags_buf ) == -1) goto done;
594 *flags = flags_buf[entry & 3];
596 resume_thread( thread );
600 /* kill a thread on the spot */
601 void kill_thread( struct thread *thread, int violent_death )
603 if (thread->state == TERMINATED) return; /* already killed */
604 thread->state = TERMINATED;
605 if (current == thread) current = NULL;
607 fprintf( stderr,"%08x: *killed* exit_code=%d\n",
608 (unsigned int)thread, thread->exit_code );
612 /* if it is waiting on the socket, we don't need to send a SIGTERM */
615 debug_exit_thread( thread );
616 abandon_mutexes( thread );
617 remove_process_thread( thread->process, thread );
618 wake_up( &thread->obj, 0 );
619 detach_thread( thread, violent_death ? SIGTERM : 0 );
620 remove_select_user( &thread->obj );
621 munmap( thread->buffer, MAX_REQUEST_LENGTH );
622 thread->buffer = (void *)-1;
623 release_object( thread );
626 /* take a snapshot of currently running threads */
627 struct thread_snapshot *thread_snap( int *count )
629 struct thread_snapshot *snapshot, *ptr;
630 struct thread *thread;
633 for (thread = first_thread; thread; thread = thread->next)
634 if (thread->state != TERMINATED) total++;
635 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
637 for (thread = first_thread; thread; thread = thread->next)
639 if (thread->state == TERMINATED) continue;
640 ptr->thread = thread;
641 ptr->count = thread->obj.refcount;
642 ptr->priority = thread->priority;
643 grab_object( thread );
650 /* signal that we are finished booting on the client side */
651 DECL_HANDLER(boot_done)
653 debug_level = max( debug_level, req->debug_level );
654 /* Make sure last_req is initialized */
655 current->last_req = REQ_BOOT_DONE;
656 if (current == booting_thread)
658 booting_thread = (struct thread *)~0UL; /* make sure it doesn't match other threads */
659 lock_master_socket(0); /* allow other clients now */
663 /* create a new thread */
664 DECL_HANDLER(new_thread)
666 struct thread *thread;
669 if (socketpair( AF_UNIX, SOCK_STREAM, 0, sock ) != -1)
671 if ((thread = create_thread( sock[0], current->process )))
673 if (req->suspend) thread->suspend++;
675 if ((req->handle = alloc_handle( current->process, thread,
676 THREAD_ALL_ACCESS, req->inherit )) != -1)
678 set_reply_fd( current, sock[1] );
679 /* thread object will be released when the thread gets killed */
680 add_process_thread( current->process, thread );
683 release_object( thread );
687 else file_set_error();
690 /* retrieve the thread buffer file descriptor */
691 DECL_HANDLER(get_thread_buffer)
693 fatal_protocol_error( current, "get_thread_buffer: should never get called directly\n" );
696 /* initialize a new thread */
697 DECL_HANDLER(init_thread)
699 if (current->unix_pid)
701 fatal_protocol_error( current, "init_thread: already running\n" );
704 current->unix_pid = req->unix_pid;
705 current->teb = req->teb;
706 if (current->suspend + current->process->suspend > 0) stop_thread( current );
707 if (current->process->running_threads > 1)
708 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
711 /* terminate a thread */
712 DECL_HANDLER(terminate_thread)
714 struct thread *thread;
718 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
720 thread->exit_code = req->exit_code;
721 if (thread != current) kill_thread( thread, 1 );
725 req->last = (thread->process->running_threads == 1);
727 release_object( thread );
731 /* fetch information about a thread */
732 DECL_HANDLER(get_thread_info)
734 struct thread *thread;
735 int handle = req->handle;
737 if (handle == -1) thread = get_thread_from_id( req->tid_in );
738 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
742 req->tid = get_thread_id( thread );
743 req->teb = thread->teb;
744 req->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STILL_ACTIVE;
745 req->priority = thread->priority;
746 release_object( thread );
750 /* set information about a thread */
751 DECL_HANDLER(set_thread_info)
753 struct thread *thread;
755 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
757 set_thread_info( thread, req );
758 release_object( thread );
762 /* suspend a thread */
763 DECL_HANDLER(suspend_thread)
765 struct thread *thread;
767 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
769 req->count = suspend_thread( thread, 1 );
770 release_object( thread );
774 /* resume a thread */
775 DECL_HANDLER(resume_thread)
777 struct thread *thread;
779 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
781 req->count = resume_thread( thread );
782 release_object( thread );
786 /* select on a handle list */
789 int count = get_req_data_size(req) / sizeof(int);
790 if (!select_on( count, get_req_data(req), req->flags, req->timeout ))
794 /* queue an APC for a thread */
795 DECL_HANDLER(queue_apc)
797 struct thread *thread;
798 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
800 thread_queue_apc( thread, NULL, req->func, APC_USER, 1, req->param );
801 release_object( thread );
805 /* get next APC to call */
806 DECL_HANDLER(get_apc)
808 struct thread_apc *apc;
813 if (!(apc = thread_dequeue_apc( current )))
817 req->type = APC_NONE;
818 set_req_data_size( req, 0 );
821 /* Optimization: ignore APCs that have a NULL func; they are only used
822 * to wake up a thread, but since we got here the thread woke up already.
824 if (apc->func) break;
827 size = apc->nb_args * sizeof(apc->args[0]);
828 if (size > get_req_data_size(req)) size = get_req_data_size(req);
829 req->func = apc->func;
830 req->type = apc->type;
831 memcpy( get_req_data(req), apc->args, size );
832 set_req_data_size( req, size );
836 /* fetch a selector entry for a thread */
837 DECL_HANDLER(get_selector_entry)
839 struct thread *thread;
840 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
842 get_selector_entry( thread, req->entry, &req->base, &req->limit, &req->flags );
843 release_object( thread );