2 * Server-side thread management
4 * Copyright (C) 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "wine/port.h"
32 #include <sys/types.h>
40 #define WIN32_NO_STATUS
53 #define CPU_FLAG(cpu) (1 << (cpu))
55 static const unsigned int supported_cpus = CPU_FLAG(CPU_x86);
56 #elif defined(__x86_64__)
57 static const unsigned int supported_cpus = CPU_FLAG(CPU_x86_64) | CPU_FLAG(CPU_x86);
58 #elif defined(__ALPHA__)
59 static const unsigned int supported_cpus = CPU_FLAG(CPU_ALPHA);
60 #elif defined(__powerpc__)
61 static const unsigned int supported_cpus = CPU_FLAG(CPU_POWERPC);
62 #elif defined(__sparc__)
63 static const unsigned int supported_cpus = CPU_FLAG(CPU_SPARC);
65 #error Unsupported CPU
72 struct thread_wait *next; /* next wait structure for this thread */
73 struct thread *thread; /* owner thread */
74 int count; /* count of objects */
76 client_ptr_t cookie; /* magic cookie to return to client */
78 struct timeout_user *user;
79 struct wait_queue_entry queues[1];
82 /* asynchronous procedure calls */
86 struct object obj; /* object header */
87 struct list entry; /* queue linked list */
88 struct thread *caller; /* thread that queued this apc */
89 struct object *owner; /* object that queued this apc */
90 int executed; /* has it been executed by the client? */
91 apc_call_t call; /* call arguments */
92 apc_result_t result; /* call results once executed */
95 static void dump_thread_apc( struct object *obj, int verbose );
96 static int thread_apc_signaled( struct object *obj, struct thread *thread );
97 static void thread_apc_destroy( struct object *obj );
98 static void clear_apc_queue( struct list *queue );
100 static const struct object_ops thread_apc_ops =
102 sizeof(struct thread_apc), /* size */
103 dump_thread_apc, /* dump */
104 no_get_type, /* get_type */
105 add_queue, /* add_queue */
106 remove_queue, /* remove_queue */
107 thread_apc_signaled, /* signaled */
108 no_satisfied, /* satisfied */
109 no_signal, /* signal */
110 no_get_fd, /* get_fd */
111 no_map_access, /* map_access */
112 default_get_sd, /* get_sd */
113 default_set_sd, /* set_sd */
114 no_lookup_name, /* lookup_name */
115 no_open_file, /* open_file */
116 no_close_handle, /* close_handle */
117 thread_apc_destroy /* destroy */
121 /* thread operations */
123 static void dump_thread( struct object *obj, int verbose );
124 static int thread_signaled( struct object *obj, struct thread *thread );
125 static unsigned int thread_map_access( struct object *obj, unsigned int access );
126 static void thread_poll_event( struct fd *fd, int event );
127 static void destroy_thread( struct object *obj );
129 static const struct object_ops thread_ops =
131 sizeof(struct thread), /* size */
132 dump_thread, /* dump */
133 no_get_type, /* get_type */
134 add_queue, /* add_queue */
135 remove_queue, /* remove_queue */
136 thread_signaled, /* signaled */
137 no_satisfied, /* satisfied */
138 no_signal, /* signal */
139 no_get_fd, /* get_fd */
140 thread_map_access, /* map_access */
141 default_get_sd, /* get_sd */
142 default_set_sd, /* set_sd */
143 no_lookup_name, /* lookup_name */
144 no_open_file, /* open_file */
145 no_close_handle, /* close_handle */
146 destroy_thread /* destroy */
149 static const struct fd_ops thread_fd_ops =
151 NULL, /* get_poll_events */
152 thread_poll_event, /* poll_event */
154 NULL, /* get_fd_type */
156 NULL, /* queue_async */
157 NULL, /* reselect_async */
158 NULL /* cancel_async */
161 static struct list thread_list = LIST_INIT(thread_list);
163 /* initialize the structure for a newly allocated thread */
164 static inline void init_thread_structure( struct thread *thread )
168 thread->unix_pid = -1; /* not known yet */
169 thread->unix_tid = -1; /* not known yet */
170 thread->context = NULL;
171 thread->suspend_context = NULL;
173 thread->debug_ctx = NULL;
174 thread->debug_event = NULL;
175 thread->debug_break = 0;
176 thread->queue = NULL;
179 thread->req_data = NULL;
180 thread->req_toread = 0;
181 thread->reply_data = NULL;
182 thread->reply_towrite = 0;
183 thread->request_fd = NULL;
184 thread->reply_fd = NULL;
185 thread->wait_fd = NULL;
186 thread->state = RUNNING;
187 thread->exit_code = 0;
188 thread->priority = 0;
189 thread->affinity = ~0;
191 thread->desktop_users = 0;
192 thread->token = NULL;
194 thread->creation_time = current_time;
195 thread->exit_time = 0;
197 list_init( &thread->mutex_list );
198 list_init( &thread->system_apc );
199 list_init( &thread->user_apc );
201 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
202 thread->inflight[i].server = thread->inflight[i].client = -1;
205 /* check if address looks valid for a client-side data structure (TEB etc.) */
206 static inline int is_valid_address( client_ptr_t addr )
208 return addr && !(addr % sizeof(int));
211 /* create a new thread */
212 struct thread *create_thread( int fd, struct process *process )
214 struct thread *thread;
216 if (!(thread = alloc_object( &thread_ops ))) return NULL;
218 init_thread_structure( thread );
220 thread->process = (struct process *)grab_object( process );
221 thread->desktop = process->desktop;
222 if (!current) current = thread;
224 list_add_head( &thread_list, &thread->entry );
226 if (!(thread->id = alloc_ptid( thread )))
228 release_object( thread );
231 if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj, 0 )))
233 release_object( thread );
237 set_fd_events( thread->request_fd, POLLIN ); /* start listening to events */
238 add_process_thread( thread->process, thread );
242 /* handle a client event */
243 static void thread_poll_event( struct fd *fd, int event )
245 struct thread *thread = get_fd_user( fd );
246 assert( thread->obj.ops == &thread_ops );
248 if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
249 else if (event & POLLIN) read_request( thread );
250 else if (event & POLLOUT) write_reply( thread );
253 /* cleanup everything that is no longer needed by a dead thread */
254 /* used by destroy_thread and kill_thread */
255 static void cleanup_thread( struct thread *thread )
259 clear_apc_queue( &thread->system_apc );
260 clear_apc_queue( &thread->user_apc );
261 free( thread->req_data );
262 free( thread->reply_data );
263 if (thread->request_fd) release_object( thread->request_fd );
264 if (thread->reply_fd) release_object( thread->reply_fd );
265 if (thread->wait_fd) release_object( thread->wait_fd );
266 free( thread->suspend_context );
267 free_msg_queue( thread );
268 cleanup_clipboard_thread(thread);
269 destroy_thread_windows( thread );
270 close_thread_desktop( thread );
271 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
273 if (thread->inflight[i].client != -1)
275 close( thread->inflight[i].server );
276 thread->inflight[i].client = thread->inflight[i].server = -1;
279 thread->req_data = NULL;
280 thread->reply_data = NULL;
281 thread->request_fd = NULL;
282 thread->reply_fd = NULL;
283 thread->wait_fd = NULL;
284 thread->context = NULL;
285 thread->suspend_context = NULL;
289 /* destroy a thread when its refcount is 0 */
290 static void destroy_thread( struct object *obj )
292 struct thread *thread = (struct thread *)obj;
293 assert( obj->ops == &thread_ops );
295 assert( !thread->debug_ctx ); /* cannot still be debugging something */
296 list_remove( &thread->entry );
297 cleanup_thread( thread );
298 release_object( thread->process );
299 if (thread->id) free_ptid( thread->id );
300 if (thread->token) release_object( thread->token );
303 /* dump a thread on stdout for debugging purposes */
304 static void dump_thread( struct object *obj, int verbose )
306 struct thread *thread = (struct thread *)obj;
307 assert( obj->ops == &thread_ops );
309 fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d state=%d\n",
310 thread->id, thread->unix_pid, thread->unix_tid, thread->state );
313 static int thread_signaled( struct object *obj, struct thread *thread )
315 struct thread *mythread = (struct thread *)obj;
316 return (mythread->state == TERMINATED);
319 static unsigned int thread_map_access( struct object *obj, unsigned int access )
321 if (access & GENERIC_READ) access |= STANDARD_RIGHTS_READ | SYNCHRONIZE;
322 if (access & GENERIC_WRITE) access |= STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
323 if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
324 if (access & GENERIC_ALL) access |= THREAD_ALL_ACCESS;
325 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
328 static void dump_thread_apc( struct object *obj, int verbose )
330 struct thread_apc *apc = (struct thread_apc *)obj;
331 assert( obj->ops == &thread_apc_ops );
333 fprintf( stderr, "APC owner=%p type=%u\n", apc->owner, apc->call.type );
336 static int thread_apc_signaled( struct object *obj, struct thread *thread )
338 struct thread_apc *apc = (struct thread_apc *)obj;
339 return apc->executed;
342 static void thread_apc_destroy( struct object *obj )
344 struct thread_apc *apc = (struct thread_apc *)obj;
345 if (apc->caller) release_object( apc->caller );
346 if (apc->owner) release_object( apc->owner );
349 /* queue an async procedure call */
350 static struct thread_apc *create_apc( struct object *owner, const apc_call_t *call_data )
352 struct thread_apc *apc;
354 if ((apc = alloc_object( &thread_apc_ops )))
356 apc->call = *call_data;
360 apc->result.type = APC_NONE;
361 if (owner) grab_object( owner );
366 /* get a thread pointer from a thread id (and increment the refcount) */
367 struct thread *get_thread_from_id( thread_id_t id )
369 struct object *obj = get_ptid_entry( id );
371 if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
372 set_error( STATUS_INVALID_CID );
376 /* get a thread from a handle (and increment the refcount) */
377 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
379 return (struct thread *)get_handle_obj( current->process, handle,
380 access, &thread_ops );
383 /* find a thread from a Unix tid */
384 struct thread *get_thread_from_tid( int tid )
386 struct thread *thread;
388 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
390 if (thread->unix_tid == tid) return thread;
395 /* find a thread from a Unix pid */
396 struct thread *get_thread_from_pid( int pid )
398 struct thread *thread;
400 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
402 if (thread->unix_pid == pid) return thread;
407 #define THREAD_PRIORITY_REALTIME_HIGHEST 6
408 #define THREAD_PRIORITY_REALTIME_LOWEST -7
410 /* set all information about a thread */
411 static void set_thread_info( struct thread *thread,
412 const struct set_thread_info_request *req )
414 if (req->mask & SET_THREAD_INFO_PRIORITY)
416 int max = THREAD_PRIORITY_HIGHEST;
417 int min = THREAD_PRIORITY_LOWEST;
418 if (thread->process->priority == PROCESS_PRIOCLASS_REALTIME)
420 max = THREAD_PRIORITY_REALTIME_HIGHEST;
421 min = THREAD_PRIORITY_REALTIME_LOWEST;
423 if ((req->priority >= min && req->priority <= max) ||
424 req->priority == THREAD_PRIORITY_IDLE ||
425 req->priority == THREAD_PRIORITY_TIME_CRITICAL)
426 thread->priority = req->priority;
428 set_error( STATUS_INVALID_PARAMETER );
430 if (req->mask & SET_THREAD_INFO_AFFINITY)
431 thread->affinity = req->affinity;
432 if (req->mask & SET_THREAD_INFO_TOKEN)
433 security_set_thread_token( thread, req->token );
436 /* stop a thread (at the Unix level) */
437 void stop_thread( struct thread *thread )
439 if (thread->context) return; /* already inside a debug event, no need for a signal */
440 /* can't stop a thread while initialisation is in progress */
441 if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
444 /* suspend a thread */
445 static int suspend_thread( struct thread *thread )
447 int old_count = thread->suspend;
448 if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
450 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
452 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
456 /* resume a thread */
457 static int resume_thread( struct thread *thread )
459 int old_count = thread->suspend;
460 if (thread->suspend > 0)
462 if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
467 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
468 int add_queue( struct object *obj, struct wait_queue_entry *entry )
472 list_add_tail( &obj->wait_queue, &entry->entry );
476 /* remove a thread from an object wait queue */
477 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
479 list_remove( &entry->entry );
480 release_object( obj );
484 static void end_wait( struct thread *thread )
486 struct thread_wait *wait = thread->wait;
487 struct wait_queue_entry *entry;
491 thread->wait = wait->next;
492 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
493 entry->obj->ops->remove_queue( entry->obj, entry );
494 if (wait->user) remove_timeout_user( wait->user );
498 /* build the thread wait structure */
499 static int wait_on( unsigned int count, struct object *objects[], int flags, timeout_t timeout )
501 struct thread_wait *wait;
502 struct wait_queue_entry *entry;
505 if (!(wait = mem_alloc( FIELD_OFFSET(struct thread_wait, queues[count]) ))) return 0;
506 wait->next = current->wait;
507 wait->thread = current;
511 wait->timeout = timeout;
512 current->wait = wait;
514 for (i = 0, entry = wait->queues; i < count; i++, entry++)
516 struct object *obj = objects[i];
517 entry->thread = current;
518 if (!obj->ops->add_queue( obj, entry ))
528 /* check if the thread waiting condition is satisfied */
529 static int check_wait( struct thread *thread )
532 struct thread_wait *wait = thread->wait;
533 struct wait_queue_entry *entry = wait->queues;
537 if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
538 return STATUS_USER_APC;
540 /* Suspended threads may not acquire locks, but they can run system APCs */
541 if (thread->process->suspend + thread->suspend > 0) return -1;
543 if (wait->flags & SELECT_ALL)
546 /* Note: we must check them all anyway, as some objects may
547 * want to do something when signaled, even if others are not */
548 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
549 not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
550 if (not_ok) goto other_checks;
551 /* Wait satisfied: tell it to all objects */
553 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
554 if (entry->obj->ops->satisfied( entry->obj, thread ))
555 signaled = STATUS_ABANDONED_WAIT_0;
560 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
562 if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
563 /* Wait satisfied: tell it to the object */
565 if (entry->obj->ops->satisfied( entry->obj, thread ))
566 signaled = i + STATUS_ABANDONED_WAIT_0;
572 if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
573 if (wait->timeout <= current_time) return STATUS_TIMEOUT;
577 /* send the wakeup signal to a thread */
578 static int send_thread_wakeup( struct thread *thread, client_ptr_t cookie, int signaled )
580 struct wake_up_reply reply;
583 memset( &reply, 0, sizeof(reply) );
584 reply.cookie = cookie;
585 reply.signaled = signaled;
586 if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
589 fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
590 else if (errno == EPIPE)
591 kill_thread( thread, 0 ); /* normal death */
593 fatal_protocol_perror( thread, "write" );
597 /* attempt to wake up a thread */
598 /* return >0 if OK, 0 if the wait condition is still not satisfied */
599 int wake_thread( struct thread *thread )
604 for (count = 0; thread->wait; count++)
606 if ((signaled = check_wait( thread )) == -1) break;
608 cookie = thread->wait->cookie;
609 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d\n", thread->id, signaled );
611 if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
617 /* thread wait timeout */
618 static void thread_timeout( void *ptr )
620 struct thread_wait *wait = ptr;
621 struct thread *thread = wait->thread;
622 client_ptr_t cookie = wait->cookie;
625 if (thread->wait != wait) return; /* not the top-level wait, ignore it */
626 if (thread->suspend + thread->process->suspend > 0) return; /* suspended, ignore it */
628 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=TIMEOUT\n", thread->id );
630 if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
631 /* check if other objects have become signaled in the meantime */
632 wake_thread( thread );
635 /* try signaling an event flag, a semaphore or a mutex */
636 static int signal_object( obj_handle_t handle )
641 obj = get_handle_obj( current->process, handle, 0, NULL );
644 ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
645 release_object( obj );
650 /* select on a list of handles */
651 static timeout_t select_on( unsigned int count, client_ptr_t cookie, const obj_handle_t *handles,
652 int flags, timeout_t timeout, obj_handle_t signal_obj )
656 struct object *objects[MAXIMUM_WAIT_OBJECTS];
658 if (timeout <= 0) timeout = current_time - timeout;
660 if (count > MAXIMUM_WAIT_OBJECTS)
662 set_error( STATUS_INVALID_PARAMETER );
665 for (i = 0; i < count; i++)
667 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
671 if (i < count) goto done;
672 if (!wait_on( count, objects, flags, timeout )) goto done;
674 /* signal the object */
677 if (!signal_object( signal_obj ))
682 /* check if we woke ourselves up */
683 if (!current->wait) goto done;
686 if ((ret = check_wait( current )) != -1)
688 /* condition is already satisfied */
694 /* now we need to wait */
695 if (current->wait->timeout != TIMEOUT_INFINITE)
697 if (!(current->wait->user = add_timeout_user( current->wait->timeout,
698 thread_timeout, current->wait )))
704 current->wait->cookie = cookie;
705 set_error( STATUS_PENDING );
708 while (i > 0) release_object( objects[--i] );
712 /* attempt to wake threads sleeping on the object wait queue */
713 void wake_up( struct object *obj, int max )
715 struct list *ptr, *next;
717 LIST_FOR_EACH_SAFE( ptr, next, &obj->wait_queue )
719 struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
720 if (wake_thread( entry->thread ))
722 if (max && !--max) break;
727 /* return the apc queue to use for a given apc type */
728 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
735 return &thread->user_apc;
737 return &thread->system_apc;
741 /* check if thread is currently waiting for a (system) apc */
742 static inline int is_in_apc_wait( struct thread *thread )
744 return (thread->process->suspend || thread->suspend ||
745 (thread->wait && (thread->wait->flags & SELECT_INTERRUPTIBLE)));
748 /* queue an existing APC to a given thread */
749 static int queue_apc( struct process *process, struct thread *thread, struct thread_apc *apc )
753 if (!thread) /* find a suitable thread inside the process */
755 struct thread *candidate;
757 /* first try to find a waiting thread */
758 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
760 if (candidate->state == TERMINATED) continue;
761 if (is_in_apc_wait( candidate ))
769 /* then use the first one that accepts a signal */
770 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
772 if (send_thread_signal( candidate, SIGUSR1 ))
779 if (!thread) return 0; /* nothing found */
780 queue = get_apc_queue( thread, apc->call.type );
784 if (thread->state == TERMINATED) return 0;
785 queue = get_apc_queue( thread, apc->call.type );
786 /* send signal for system APCs if needed */
787 if (queue == &thread->system_apc && list_empty( queue ) && !is_in_apc_wait( thread ))
789 if (!send_thread_signal( thread, SIGUSR1 )) return 0;
791 /* cancel a possible previous APC with the same owner */
792 if (apc->owner) thread_cancel_apc( thread, apc->owner, apc->call.type );
796 list_add_tail( queue, &apc->entry );
797 if (!list_prev( queue, &apc->entry )) /* first one */
798 wake_thread( thread );
803 /* queue an async procedure call */
804 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
806 struct thread_apc *apc;
809 if ((apc = create_apc( owner, call_data )))
811 ret = queue_apc( NULL, thread, apc );
812 release_object( apc );
817 /* cancel the async procedure call owned by a specific object */
818 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
820 struct thread_apc *apc;
821 struct list *queue = get_apc_queue( thread, type );
823 LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
825 if (apc->owner != owner) continue;
826 list_remove( &apc->entry );
828 wake_up( &apc->obj, 0 );
829 release_object( apc );
834 /* remove the head apc from the queue; the returned object must be released by the caller */
835 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
837 struct thread_apc *apc = NULL;
838 struct list *ptr = list_head( &thread->system_apc );
840 if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
843 apc = LIST_ENTRY( ptr, struct thread_apc, entry );
849 /* clear an APC queue, cancelling all the APCs on it */
850 static void clear_apc_queue( struct list *queue )
854 while ((ptr = list_head( queue )))
856 struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
857 list_remove( &apc->entry );
859 wake_up( &apc->obj, 0 );
860 release_object( apc );
864 /* add an fd to the inflight list */
865 /* return list index, or -1 on error */
866 int thread_add_inflight_fd( struct thread *thread, int client, int server )
870 if (server == -1) return -1;
877 /* first check if we already have an entry for this fd */
878 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
879 if (thread->inflight[i].client == client)
881 close( thread->inflight[i].server );
882 thread->inflight[i].server = server;
886 /* now find a free spot to store it */
887 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
888 if (thread->inflight[i].client == -1)
890 thread->inflight[i].client = client;
891 thread->inflight[i].server = server;
897 /* get an inflight fd and purge it from the list */
898 /* the fd must be closed when no longer used */
899 int thread_get_inflight_fd( struct thread *thread, int client )
903 if (client == -1) return -1;
907 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
909 if (thread->inflight[i].client == client)
911 ret = thread->inflight[i].server;
912 thread->inflight[i].server = thread->inflight[i].client = -1;
916 } while (!receive_fd( thread->process )); /* in case it is still in the socket buffer */
920 /* kill a thread on the spot */
921 void kill_thread( struct thread *thread, int violent_death )
923 if (thread->state == TERMINATED) return; /* already killed */
924 thread->state = TERMINATED;
925 thread->exit_time = current_time;
926 if (current == thread) current = NULL;
928 fprintf( stderr,"%04x: *killed* exit_code=%d\n",
929 thread->id, thread->exit_code );
932 while (thread->wait) end_wait( thread );
933 send_thread_wakeup( thread, 0, STATUS_PENDING );
934 /* if it is waiting on the socket, we don't need to send a SIGQUIT */
937 kill_console_processes( thread, 0 );
938 debug_exit_thread( thread );
939 abandon_mutexes( thread );
940 wake_up( &thread->obj, 0 );
941 if (violent_death) send_thread_signal( thread, SIGQUIT );
942 cleanup_thread( thread );
943 remove_process_thread( thread->process, thread );
944 release_object( thread );
947 /* copy parts of a context structure */
948 static void copy_context( context_t *to, const context_t *from, unsigned int flags )
950 assert( to->cpu == from->cpu );
952 if (flags & SERVER_CTX_CONTROL) to->ctl = from->ctl;
953 if (flags & SERVER_CTX_INTEGER) to->integer = from->integer;
954 if (flags & SERVER_CTX_SEGMENTS) to->seg = from->seg;
955 if (flags & SERVER_CTX_FLOATING_POINT) to->fp = from->fp;
956 if (flags & SERVER_CTX_DEBUG_REGISTERS) to->debug = from->debug;
957 if (flags & SERVER_CTX_EXTENDED_REGISTERS) to->ext = from->ext;
960 /* return the context flags that correspond to system regs */
961 /* (system regs are the ones we can't access on the client side) */
962 static unsigned int get_context_system_regs( enum cpu_type cpu )
966 case CPU_x86: return SERVER_CTX_DEBUG_REGISTERS;
967 case CPU_x86_64: return SERVER_CTX_DEBUG_REGISTERS;
968 case CPU_ALPHA: return 0;
969 case CPU_POWERPC: return 0;
970 case CPU_SPARC: return 0;
975 /* trigger a breakpoint event in a given thread */
976 void break_thread( struct thread *thread )
980 assert( thread->context );
982 memset( &data, 0, sizeof(data) );
983 data.exception.first = 1;
984 data.exception.exc_code = STATUS_BREAKPOINT;
985 data.exception.flags = EXCEPTION_CONTINUABLE;
986 switch (thread->context->cpu)
989 data.exception.address = thread->context->ctl.i386_regs.eip;
992 data.exception.address = thread->context->ctl.x86_64_regs.rip;
995 data.exception.address = thread->context->ctl.alpha_regs.fir;
998 data.exception.address = thread->context->ctl.powerpc_regs.iar;
1001 data.exception.address = thread->context->ctl.sparc_regs.pc;
1004 generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
1005 thread->debug_break = 0;
1008 /* take a snapshot of currently running threads */
1009 struct thread_snapshot *thread_snap( int *count )
1011 struct thread_snapshot *snapshot, *ptr;
1012 struct thread *thread;
1015 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1016 if (thread->state != TERMINATED) total++;
1017 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
1019 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1021 if (thread->state == TERMINATED) continue;
1022 ptr->thread = thread;
1023 ptr->count = thread->obj.refcount;
1024 ptr->priority = thread->priority;
1025 grab_object( thread );
1032 /* gets the current impersonation token */
1033 struct token *thread_get_impersonation_token( struct thread *thread )
1036 return thread->token;
1038 return thread->process->token;
1041 /* create a new thread */
1042 DECL_HANDLER(new_thread)
1044 struct thread *thread;
1045 int request_fd = thread_get_inflight_fd( current, req->request_fd );
1047 if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
1049 if (request_fd != -1) close( request_fd );
1050 set_error( STATUS_INVALID_HANDLE );
1054 if ((thread = create_thread( request_fd, current->process )))
1056 if (req->suspend) thread->suspend++;
1057 reply->tid = get_thread_id( thread );
1058 if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
1060 /* thread object will be released when the thread gets killed */
1063 kill_thread( thread, 1 );
1067 /* initialize a new thread */
1068 DECL_HANDLER(init_thread)
1070 struct process *process = current->process;
1071 int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
1072 int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
1074 if (current->reply_fd) /* already initialised */
1076 set_error( STATUS_INVALID_PARAMETER );
1080 if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
1082 current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, ¤t->obj, 0 );
1084 if (!current->reply_fd) goto error;
1088 set_error( STATUS_TOO_MANY_OPENED_FILES ); /* most likely reason */
1091 if (!(current->wait_fd = create_anonymous_fd( &thread_fd_ops, wait_fd, ¤t->obj, 0 )))
1094 if (!is_valid_address(req->teb))
1096 set_error( STATUS_INVALID_PARAMETER );
1100 current->unix_pid = req->unix_pid;
1101 current->unix_tid = req->unix_tid;
1102 current->teb = req->teb;
1104 if (!process->peb) /* first thread, initialize the process too */
1106 if (!CPU_FLAG(req->cpu) || !(supported_cpus & CPU_FLAG(req->cpu)))
1108 set_error( STATUS_NOT_SUPPORTED );
1111 process->unix_pid = current->unix_pid;
1112 process->peb = req->entry;
1113 process->cpu = req->cpu;
1114 reply->info_size = init_process( current );
1118 if (req->cpu != process->cpu)
1120 set_error( STATUS_INVALID_PARAMETER );
1123 if (process->unix_pid != current->unix_pid)
1124 process->unix_pid = -1; /* can happen with linuxthreads */
1125 if (current->suspend + process->suspend > 0) stop_thread( current );
1126 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, &req->entry );
1128 debug_level = max( debug_level, req->debug_level );
1130 reply->pid = get_process_id( process );
1131 reply->tid = get_thread_id( current );
1132 reply->version = SERVER_PROTOCOL_VERSION;
1133 reply->server_start = server_start_time;
1134 reply->all_cpus = supported_cpus;
1138 if (reply_fd != -1) close( reply_fd );
1139 if (wait_fd != -1) close( wait_fd );
1142 /* terminate a thread */
1143 DECL_HANDLER(terminate_thread)
1145 struct thread *thread;
1149 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1151 thread->exit_code = req->exit_code;
1152 if (thread != current) kill_thread( thread, 1 );
1156 reply->last = (thread->process->running_threads == 1);
1158 release_object( thread );
1162 /* open a handle to a thread */
1163 DECL_HANDLER(open_thread)
1165 struct thread *thread = get_thread_from_id( req->tid );
1170 reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1171 release_object( thread );
1175 /* fetch information about a thread */
1176 DECL_HANDLER(get_thread_info)
1178 struct thread *thread;
1179 obj_handle_t handle = req->handle;
1181 if (!handle) thread = get_thread_from_id( req->tid_in );
1182 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1186 reply->pid = get_process_id( thread->process );
1187 reply->tid = get_thread_id( thread );
1188 reply->teb = thread->teb;
1189 reply->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1190 reply->priority = thread->priority;
1191 reply->affinity = thread->affinity;
1192 reply->creation_time = thread->creation_time;
1193 reply->exit_time = thread->exit_time;
1194 reply->last = thread->process->running_threads == 1;
1196 release_object( thread );
1200 /* set information about a thread */
1201 DECL_HANDLER(set_thread_info)
1203 struct thread *thread;
1205 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1207 set_thread_info( thread, req );
1208 release_object( thread );
1212 /* suspend a thread */
1213 DECL_HANDLER(suspend_thread)
1215 struct thread *thread;
1217 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1219 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1220 else reply->count = suspend_thread( thread );
1221 release_object( thread );
1225 /* resume a thread */
1226 DECL_HANDLER(resume_thread)
1228 struct thread *thread;
1230 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1232 reply->count = resume_thread( thread );
1233 release_object( thread );
1237 /* select on a handle list */
1238 DECL_HANDLER(select)
1240 struct thread_apc *apc;
1242 const apc_result_t *result = get_req_data();
1243 const obj_handle_t *handles = (const obj_handle_t *)(result + 1);
1245 if (get_req_data_size() < sizeof(*result))
1247 set_error( STATUS_INVALID_PARAMETER );
1250 count = (get_req_data_size() - sizeof(*result)) / sizeof(obj_handle_t);
1252 /* first store results of previous apc */
1255 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev_apc,
1256 0, &thread_apc_ops ))) return;
1257 apc->result = *result;
1259 if (apc->result.type == APC_CREATE_THREAD) /* transfer the handle to the caller process */
1261 obj_handle_t handle = duplicate_handle( current->process, apc->result.create_thread.handle,
1262 apc->caller->process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1263 close_handle( current->process, apc->result.create_thread.handle );
1264 apc->result.create_thread.handle = handle;
1265 clear_error(); /* ignore errors from the above calls */
1267 else if (apc->result.type == APC_ASYNC_IO)
1270 async_set_result( apc->owner, apc->result.async_io.status,
1271 apc->result.async_io.total, apc->result.async_io.apc );
1273 wake_up( &apc->obj, 0 );
1274 close_handle( current->process, req->prev_apc );
1275 release_object( apc );
1278 reply->timeout = select_on( count, req->cookie, handles, req->flags, req->timeout, req->signal );
1280 if (get_error() == STATUS_USER_APC)
1284 if (!(apc = thread_dequeue_apc( current, !(req->flags & SELECT_ALERTABLE) )))
1286 /* Optimization: ignore APC_NONE calls, they are only used to
1287 * wake up a thread, but since we got here the thread woke up already.
1289 if (apc->call.type != APC_NONE)
1291 if ((reply->apc_handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1292 reply->call = apc->call;
1293 release_object( apc );
1297 wake_up( &apc->obj, 0 );
1298 release_object( apc );
1303 /* queue an APC for a thread or process */
1304 DECL_HANDLER(queue_apc)
1306 struct thread *thread = NULL;
1307 struct process *process = NULL;
1308 struct thread_apc *apc;
1310 if (!(apc = create_apc( NULL, &req->call ))) return;
1312 switch (apc->call.type)
1316 thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT );
1318 case APC_VIRTUAL_ALLOC:
1319 case APC_VIRTUAL_FREE:
1320 case APC_VIRTUAL_PROTECT:
1321 case APC_VIRTUAL_FLUSH:
1322 case APC_VIRTUAL_LOCK:
1323 case APC_VIRTUAL_UNLOCK:
1324 case APC_UNMAP_VIEW:
1325 process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1327 case APC_VIRTUAL_QUERY:
1328 process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION );
1331 process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1332 if (process && process != current->process)
1334 /* duplicate the handle into the target process */
1335 obj_handle_t handle = duplicate_handle( current->process, apc->call.map_view.handle,
1336 process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1337 if (handle) apc->call.map_view.handle = handle;
1340 release_object( process );
1345 case APC_CREATE_THREAD:
1346 process = get_process_from_handle( req->handle, PROCESS_CREATE_THREAD );
1349 set_error( STATUS_INVALID_PARAMETER );
1355 if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1356 release_object( thread );
1360 reply->self = (process == current->process);
1363 obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1366 if (queue_apc( process, NULL, apc ))
1368 apc->caller = (struct thread *)grab_object( current );
1369 reply->handle = handle;
1373 close_handle( current->process, handle );
1374 set_error( STATUS_PROCESS_IS_TERMINATING );
1378 release_object( process );
1381 release_object( apc );
1384 /* Get the result of an APC call */
1385 DECL_HANDLER(get_apc_result)
1387 struct thread_apc *apc;
1389 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1390 0, &thread_apc_ops ))) return;
1391 if (!apc->executed) set_error( STATUS_PENDING );
1394 reply->result = apc->result;
1395 /* close the handle directly to avoid an extra round-trip */
1396 close_handle( current->process, req->handle );
1398 release_object( apc );
1401 /* retrieve the current context of a thread */
1402 DECL_HANDLER(get_thread_context)
1404 struct thread *thread;
1407 if (get_reply_max_size() < sizeof(context_t))
1409 set_error( STATUS_INVALID_PARAMETER );
1412 if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1416 if (thread != current || !thread->suspend_context)
1418 /* not suspended, shouldn't happen */
1419 set_error( STATUS_INVALID_PARAMETER );
1423 if (thread->context == thread->suspend_context) thread->context = NULL;
1424 set_reply_data_ptr( thread->suspend_context, sizeof(context_t) );
1425 thread->suspend_context = NULL;
1428 else if (thread != current && !thread->context)
1430 /* thread is not suspended, retry (if it's still running) */
1431 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1432 else set_error( STATUS_PENDING );
1434 else if ((context = set_reply_data_size( sizeof(context_t) )))
1436 unsigned int flags = get_context_system_regs( thread->process->cpu );
1438 memset( context, 0, sizeof(context_t) );
1439 context->cpu = thread->process->cpu;
1440 if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1441 if (flags) get_thread_context( thread, context, flags );
1443 reply->self = (thread == current);
1444 release_object( thread );
1447 /* set the current context of a thread */
1448 DECL_HANDLER(set_thread_context)
1450 struct thread *thread;
1451 const context_t *context = get_req_data();
1453 if (get_req_data_size() < sizeof(context_t))
1455 set_error( STATUS_INVALID_PARAMETER );
1458 if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1462 if (thread != current || thread->context || context->cpu != thread->process->cpu)
1464 /* nested suspend or exception, shouldn't happen */
1465 set_error( STATUS_INVALID_PARAMETER );
1467 else if ((thread->suspend_context = mem_alloc( sizeof(context_t) )))
1469 memcpy( thread->suspend_context, get_req_data(), sizeof(context_t) );
1470 thread->context = thread->suspend_context;
1471 if (thread->debug_break) break_thread( thread );
1474 else if (thread != current && !thread->context)
1476 /* thread is not suspended, retry (if it's still running) */
1477 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1478 else set_error( STATUS_PENDING );
1480 else if (context->cpu == thread->process->cpu)
1482 unsigned int system_flags = get_context_system_regs(context->cpu) & context->flags;
1483 unsigned int client_flags = context->flags & ~system_flags;
1485 if (system_flags) set_thread_context( thread, context, system_flags );
1486 if (thread->context && !get_error()) copy_context( thread->context, context, client_flags );
1488 else set_error( STATUS_INVALID_PARAMETER );
1490 reply->self = (thread == current);
1491 release_object( thread );
1494 /* fetch a selector entry for a thread */
1495 DECL_HANDLER(get_selector_entry)
1497 struct thread *thread;
1498 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1500 get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1501 release_object( thread );