msi: Implement the DeleteServices standard action.
[wine/multimedia.git] / server / thread.c
blobbdb6c3ce62b75def16acf405ae35645751d1d1fe
1 /*
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
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <signal.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/types.h>
33 #include <unistd.h>
34 #include <time.h>
35 #ifdef HAVE_POLL_H
36 #include <poll.h>
37 #endif
38 #ifdef HAVE_SCHED_H
39 #include <sched.h>
40 #endif
42 #include "ntstatus.h"
43 #define WIN32_NO_STATUS
44 #include "windef.h"
45 #include "winternl.h"
47 #include "file.h"
48 #include "handle.h"
49 #include "process.h"
50 #include "thread.h"
51 #include "request.h"
52 #include "user.h"
53 #include "security.h"
56 #define CPU_FLAG(cpu) (1 << (cpu))
57 #ifdef __i386__
58 static const unsigned int supported_cpus = CPU_FLAG(CPU_x86);
59 #elif defined(__x86_64__)
60 static const unsigned int supported_cpus = CPU_FLAG(CPU_x86_64) | CPU_FLAG(CPU_x86);
61 #elif defined(__ALPHA__)
62 static const unsigned int supported_cpus = CPU_FLAG(CPU_ALPHA);
63 #elif defined(__powerpc__)
64 static const unsigned int supported_cpus = CPU_FLAG(CPU_POWERPC);
65 #elif defined(__sparc__)
66 static const unsigned int supported_cpus = CPU_FLAG(CPU_SPARC);
67 #else
68 #error Unsupported CPU
69 #endif
71 /* thread queues */
73 struct thread_wait
75 struct thread_wait *next; /* next wait structure for this thread */
76 struct thread *thread; /* owner thread */
77 int count; /* count of objects */
78 int flags;
79 client_ptr_t cookie; /* magic cookie to return to client */
80 timeout_t timeout;
81 struct timeout_user *user;
82 struct wait_queue_entry queues[1];
85 /* asynchronous procedure calls */
87 struct thread_apc
89 struct object obj; /* object header */
90 struct list entry; /* queue linked list */
91 struct thread *caller; /* thread that queued this apc */
92 struct object *owner; /* object that queued this apc */
93 int executed; /* has it been executed by the client? */
94 apc_call_t call; /* call arguments */
95 apc_result_t result; /* call results once executed */
98 static void dump_thread_apc( struct object *obj, int verbose );
99 static int thread_apc_signaled( struct object *obj, struct thread *thread );
100 static void thread_apc_destroy( struct object *obj );
101 static void clear_apc_queue( struct list *queue );
103 static const struct object_ops thread_apc_ops =
105 sizeof(struct thread_apc), /* size */
106 dump_thread_apc, /* dump */
107 no_get_type, /* get_type */
108 add_queue, /* add_queue */
109 remove_queue, /* remove_queue */
110 thread_apc_signaled, /* signaled */
111 no_satisfied, /* satisfied */
112 no_signal, /* signal */
113 no_get_fd, /* get_fd */
114 no_map_access, /* map_access */
115 default_get_sd, /* get_sd */
116 default_set_sd, /* set_sd */
117 no_lookup_name, /* lookup_name */
118 no_open_file, /* open_file */
119 no_close_handle, /* close_handle */
120 thread_apc_destroy /* destroy */
124 /* thread operations */
126 static void dump_thread( struct object *obj, int verbose );
127 static int thread_signaled( struct object *obj, struct thread *thread );
128 static unsigned int thread_map_access( struct object *obj, unsigned int access );
129 static void thread_poll_event( struct fd *fd, int event );
130 static void destroy_thread( struct object *obj );
132 static const struct object_ops thread_ops =
134 sizeof(struct thread), /* size */
135 dump_thread, /* dump */
136 no_get_type, /* get_type */
137 add_queue, /* add_queue */
138 remove_queue, /* remove_queue */
139 thread_signaled, /* signaled */
140 no_satisfied, /* satisfied */
141 no_signal, /* signal */
142 no_get_fd, /* get_fd */
143 thread_map_access, /* map_access */
144 default_get_sd, /* get_sd */
145 default_set_sd, /* set_sd */
146 no_lookup_name, /* lookup_name */
147 no_open_file, /* open_file */
148 no_close_handle, /* close_handle */
149 destroy_thread /* destroy */
152 static const struct fd_ops thread_fd_ops =
154 NULL, /* get_poll_events */
155 thread_poll_event, /* poll_event */
156 NULL, /* flush */
157 NULL, /* get_fd_type */
158 NULL, /* ioctl */
159 NULL, /* queue_async */
160 NULL, /* reselect_async */
161 NULL /* cancel_async */
164 static struct list thread_list = LIST_INIT(thread_list);
166 /* initialize the structure for a newly allocated thread */
167 static inline void init_thread_structure( struct thread *thread )
169 int i;
171 thread->unix_pid = -1; /* not known yet */
172 thread->unix_tid = -1; /* not known yet */
173 thread->context = NULL;
174 thread->suspend_context = NULL;
175 thread->teb = 0;
176 thread->debug_ctx = NULL;
177 thread->debug_event = NULL;
178 thread->debug_break = 0;
179 thread->queue = NULL;
180 thread->wait = NULL;
181 thread->error = 0;
182 thread->req_data = NULL;
183 thread->req_toread = 0;
184 thread->reply_data = NULL;
185 thread->reply_towrite = 0;
186 thread->request_fd = NULL;
187 thread->reply_fd = NULL;
188 thread->wait_fd = NULL;
189 thread->state = RUNNING;
190 thread->exit_code = 0;
191 thread->priority = 0;
192 thread->affinity = ~0;
193 thread->suspend = 0;
194 thread->desktop_users = 0;
195 thread->token = NULL;
197 thread->creation_time = current_time;
198 thread->exit_time = 0;
200 list_init( &thread->mutex_list );
201 list_init( &thread->system_apc );
202 list_init( &thread->user_apc );
204 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
205 thread->inflight[i].server = thread->inflight[i].client = -1;
208 /* check if address looks valid for a client-side data structure (TEB etc.) */
209 static inline int is_valid_address( client_ptr_t addr )
211 return addr && !(addr % sizeof(int));
214 /* create a new thread */
215 struct thread *create_thread( int fd, struct process *process )
217 struct thread *thread;
219 if (!(thread = alloc_object( &thread_ops ))) return NULL;
221 init_thread_structure( thread );
223 thread->process = (struct process *)grab_object( process );
224 thread->desktop = process->desktop;
225 thread->affinity = process->affinity;
226 if (!current) current = thread;
228 list_add_head( &thread_list, &thread->entry );
230 if (!(thread->id = alloc_ptid( thread )))
232 release_object( thread );
233 return NULL;
235 if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj, 0 )))
237 release_object( thread );
238 return NULL;
241 set_fd_events( thread->request_fd, POLLIN ); /* start listening to events */
242 add_process_thread( thread->process, thread );
243 return thread;
246 /* handle a client event */
247 static void thread_poll_event( struct fd *fd, int event )
249 struct thread *thread = get_fd_user( fd );
250 assert( thread->obj.ops == &thread_ops );
252 if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
253 else if (event & POLLIN) read_request( thread );
254 else if (event & POLLOUT) write_reply( thread );
257 /* cleanup everything that is no longer needed by a dead thread */
258 /* used by destroy_thread and kill_thread */
259 static void cleanup_thread( struct thread *thread )
261 int i;
263 clear_apc_queue( &thread->system_apc );
264 clear_apc_queue( &thread->user_apc );
265 free( thread->req_data );
266 free( thread->reply_data );
267 if (thread->request_fd) release_object( thread->request_fd );
268 if (thread->reply_fd) release_object( thread->reply_fd );
269 if (thread->wait_fd) release_object( thread->wait_fd );
270 free( thread->suspend_context );
271 cleanup_clipboard_thread(thread);
272 destroy_thread_windows( thread );
273 free_msg_queue( thread );
274 close_thread_desktop( thread );
275 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
277 if (thread->inflight[i].client != -1)
279 close( thread->inflight[i].server );
280 thread->inflight[i].client = thread->inflight[i].server = -1;
283 thread->req_data = NULL;
284 thread->reply_data = NULL;
285 thread->request_fd = NULL;
286 thread->reply_fd = NULL;
287 thread->wait_fd = NULL;
288 thread->context = NULL;
289 thread->suspend_context = NULL;
290 thread->desktop = 0;
293 /* destroy a thread when its refcount is 0 */
294 static void destroy_thread( struct object *obj )
296 struct thread *thread = (struct thread *)obj;
297 assert( obj->ops == &thread_ops );
299 assert( !thread->debug_ctx ); /* cannot still be debugging something */
300 list_remove( &thread->entry );
301 cleanup_thread( thread );
302 release_object( thread->process );
303 if (thread->id) free_ptid( thread->id );
304 if (thread->token) release_object( thread->token );
307 /* dump a thread on stdout for debugging purposes */
308 static void dump_thread( struct object *obj, int verbose )
310 struct thread *thread = (struct thread *)obj;
311 assert( obj->ops == &thread_ops );
313 fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d state=%d\n",
314 thread->id, thread->unix_pid, thread->unix_tid, thread->state );
317 static int thread_signaled( struct object *obj, struct thread *thread )
319 struct thread *mythread = (struct thread *)obj;
320 return (mythread->state == TERMINATED);
323 static unsigned int thread_map_access( struct object *obj, unsigned int access )
325 if (access & GENERIC_READ) access |= STANDARD_RIGHTS_READ | SYNCHRONIZE;
326 if (access & GENERIC_WRITE) access |= STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
327 if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
328 if (access & GENERIC_ALL) access |= THREAD_ALL_ACCESS;
329 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
332 static void dump_thread_apc( struct object *obj, int verbose )
334 struct thread_apc *apc = (struct thread_apc *)obj;
335 assert( obj->ops == &thread_apc_ops );
337 fprintf( stderr, "APC owner=%p type=%u\n", apc->owner, apc->call.type );
340 static int thread_apc_signaled( struct object *obj, struct thread *thread )
342 struct thread_apc *apc = (struct thread_apc *)obj;
343 return apc->executed;
346 static void thread_apc_destroy( struct object *obj )
348 struct thread_apc *apc = (struct thread_apc *)obj;
349 if (apc->caller) release_object( apc->caller );
350 if (apc->owner) release_object( apc->owner );
353 /* queue an async procedure call */
354 static struct thread_apc *create_apc( struct object *owner, const apc_call_t *call_data )
356 struct thread_apc *apc;
358 if ((apc = alloc_object( &thread_apc_ops )))
360 apc->call = *call_data;
361 apc->caller = NULL;
362 apc->owner = owner;
363 apc->executed = 0;
364 apc->result.type = APC_NONE;
365 if (owner) grab_object( owner );
367 return apc;
370 /* get a thread pointer from a thread id (and increment the refcount) */
371 struct thread *get_thread_from_id( thread_id_t id )
373 struct object *obj = get_ptid_entry( id );
375 if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
376 set_error( STATUS_INVALID_CID );
377 return NULL;
380 /* get a thread from a handle (and increment the refcount) */
381 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
383 return (struct thread *)get_handle_obj( current->process, handle,
384 access, &thread_ops );
387 /* find a thread from a Unix tid */
388 struct thread *get_thread_from_tid( int tid )
390 struct thread *thread;
392 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
394 if (thread->unix_tid == tid) return thread;
396 return NULL;
399 /* find a thread from a Unix pid */
400 struct thread *get_thread_from_pid( int pid )
402 struct thread *thread;
404 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
406 if (thread->unix_pid == pid) return thread;
408 return NULL;
411 int set_thread_affinity( struct thread *thread, affinity_t affinity )
413 int ret = 0;
414 #ifdef HAVE_SCHED_SETAFFINITY
415 if (thread->unix_tid != -1)
417 cpu_set_t set;
418 int i;
419 affinity_t mask;
421 CPU_ZERO( &set );
422 for (i = 0, mask = 1; mask; i++, mask <<= 1)
423 if (affinity & mask) CPU_SET( i, &set );
425 ret = sched_setaffinity( thread->unix_tid, sizeof(set), &set );
427 #endif
428 if (!ret) thread->affinity = affinity;
429 return ret;
432 #define THREAD_PRIORITY_REALTIME_HIGHEST 6
433 #define THREAD_PRIORITY_REALTIME_LOWEST -7
435 /* set all information about a thread */
436 static void set_thread_info( struct thread *thread,
437 const struct set_thread_info_request *req )
439 if (req->mask & SET_THREAD_INFO_PRIORITY)
441 int max = THREAD_PRIORITY_HIGHEST;
442 int min = THREAD_PRIORITY_LOWEST;
443 if (thread->process->priority == PROCESS_PRIOCLASS_REALTIME)
445 max = THREAD_PRIORITY_REALTIME_HIGHEST;
446 min = THREAD_PRIORITY_REALTIME_LOWEST;
448 if ((req->priority >= min && req->priority <= max) ||
449 req->priority == THREAD_PRIORITY_IDLE ||
450 req->priority == THREAD_PRIORITY_TIME_CRITICAL)
451 thread->priority = req->priority;
452 else
453 set_error( STATUS_INVALID_PARAMETER );
455 if (req->mask & SET_THREAD_INFO_AFFINITY)
457 if ((req->affinity & thread->process->affinity) != req->affinity)
458 set_error( STATUS_INVALID_PARAMETER );
459 else if (thread->state == TERMINATED)
460 set_error( STATUS_ACCESS_DENIED );
461 else if (set_thread_affinity( thread, req->affinity ))
462 file_set_error();
464 if (req->mask & SET_THREAD_INFO_TOKEN)
465 security_set_thread_token( thread, req->token );
468 /* stop a thread (at the Unix level) */
469 void stop_thread( struct thread *thread )
471 if (thread->context) return; /* already inside a debug event, no need for a signal */
472 /* can't stop a thread while initialisation is in progress */
473 if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
476 /* suspend a thread */
477 static int suspend_thread( struct thread *thread )
479 int old_count = thread->suspend;
480 if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
482 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
484 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
485 return old_count;
488 /* resume a thread */
489 static int resume_thread( struct thread *thread )
491 int old_count = thread->suspend;
492 if (thread->suspend > 0)
494 if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
496 return old_count;
499 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
500 int add_queue( struct object *obj, struct wait_queue_entry *entry )
502 grab_object( obj );
503 entry->obj = obj;
504 list_add_tail( &obj->wait_queue, &entry->entry );
505 return 1;
508 /* remove a thread from an object wait queue */
509 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
511 list_remove( &entry->entry );
512 release_object( obj );
515 /* finish waiting */
516 static void end_wait( struct thread *thread )
518 struct thread_wait *wait = thread->wait;
519 struct wait_queue_entry *entry;
520 int i;
522 assert( wait );
523 thread->wait = wait->next;
524 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
525 entry->obj->ops->remove_queue( entry->obj, entry );
526 if (wait->user) remove_timeout_user( wait->user );
527 free( wait );
530 /* build the thread wait structure */
531 static int wait_on( unsigned int count, struct object *objects[], int flags, timeout_t timeout )
533 struct thread_wait *wait;
534 struct wait_queue_entry *entry;
535 unsigned int i;
537 if (!(wait = mem_alloc( FIELD_OFFSET(struct thread_wait, queues[count]) ))) return 0;
538 wait->next = current->wait;
539 wait->thread = current;
540 wait->count = count;
541 wait->flags = flags;
542 wait->user = NULL;
543 wait->timeout = timeout;
544 current->wait = wait;
546 for (i = 0, entry = wait->queues; i < count; i++, entry++)
548 struct object *obj = objects[i];
549 entry->thread = current;
550 if (!obj->ops->add_queue( obj, entry ))
552 wait->count = i;
553 end_wait( current );
554 return 0;
557 return 1;
560 /* check if the thread waiting condition is satisfied */
561 static int check_wait( struct thread *thread )
563 int i, signaled;
564 struct thread_wait *wait = thread->wait;
565 struct wait_queue_entry *entry = wait->queues;
567 assert( wait );
569 if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
570 return STATUS_USER_APC;
572 /* Suspended threads may not acquire locks, but they can run system APCs */
573 if (thread->process->suspend + thread->suspend > 0) return -1;
575 if (wait->flags & SELECT_ALL)
577 int not_ok = 0;
578 /* Note: we must check them all anyway, as some objects may
579 * want to do something when signaled, even if others are not */
580 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
581 not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
582 if (not_ok) goto other_checks;
583 /* Wait satisfied: tell it to all objects */
584 signaled = 0;
585 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
586 if (entry->obj->ops->satisfied( entry->obj, thread ))
587 signaled = STATUS_ABANDONED_WAIT_0;
588 return signaled;
590 else
592 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
594 if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
595 /* Wait satisfied: tell it to the object */
596 signaled = i;
597 if (entry->obj->ops->satisfied( entry->obj, thread ))
598 signaled = i + STATUS_ABANDONED_WAIT_0;
599 return signaled;
603 other_checks:
604 if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
605 if (wait->timeout <= current_time) return STATUS_TIMEOUT;
606 return -1;
609 /* send the wakeup signal to a thread */
610 static int send_thread_wakeup( struct thread *thread, client_ptr_t cookie, int signaled )
612 struct wake_up_reply reply;
613 int ret;
615 memset( &reply, 0, sizeof(reply) );
616 reply.cookie = cookie;
617 reply.signaled = signaled;
618 if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
619 return 0;
620 if (ret >= 0)
621 fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
622 else if (errno == EPIPE)
623 kill_thread( thread, 0 ); /* normal death */
624 else
625 fatal_protocol_perror( thread, "write" );
626 return -1;
629 /* attempt to wake up a thread */
630 /* return >0 if OK, 0 if the wait condition is still not satisfied */
631 int wake_thread( struct thread *thread )
633 int signaled, count;
634 client_ptr_t cookie;
636 for (count = 0; thread->wait; count++)
638 if ((signaled = check_wait( thread )) == -1) break;
640 cookie = thread->wait->cookie;
641 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d\n", thread->id, signaled );
642 end_wait( thread );
643 if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
644 break;
646 return count;
649 /* thread wait timeout */
650 static void thread_timeout( void *ptr )
652 struct thread_wait *wait = ptr;
653 struct thread *thread = wait->thread;
654 client_ptr_t cookie = wait->cookie;
656 wait->user = NULL;
657 if (thread->wait != wait) return; /* not the top-level wait, ignore it */
658 if (thread->suspend + thread->process->suspend > 0) return; /* suspended, ignore it */
660 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=TIMEOUT\n", thread->id );
661 end_wait( thread );
662 if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
663 /* check if other objects have become signaled in the meantime */
664 wake_thread( thread );
667 /* try signaling an event flag, a semaphore or a mutex */
668 static int signal_object( obj_handle_t handle )
670 struct object *obj;
671 int ret = 0;
673 obj = get_handle_obj( current->process, handle, 0, NULL );
674 if (obj)
676 ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
677 release_object( obj );
679 return ret;
682 /* select on a list of handles */
683 static timeout_t select_on( unsigned int count, client_ptr_t cookie, const obj_handle_t *handles,
684 int flags, timeout_t timeout, obj_handle_t signal_obj )
686 int ret;
687 unsigned int i;
688 struct object *objects[MAXIMUM_WAIT_OBJECTS];
690 if (timeout <= 0) timeout = current_time - timeout;
692 if (count > MAXIMUM_WAIT_OBJECTS)
694 set_error( STATUS_INVALID_PARAMETER );
695 return 0;
697 for (i = 0; i < count; i++)
699 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
700 break;
703 if (i < count) goto done;
704 if (!wait_on( count, objects, flags, timeout )) goto done;
706 /* signal the object */
707 if (signal_obj)
709 if (!signal_object( signal_obj ))
711 end_wait( current );
712 goto done;
714 /* check if we woke ourselves up */
715 if (!current->wait) goto done;
718 if ((ret = check_wait( current )) != -1)
720 /* condition is already satisfied */
721 end_wait( current );
722 set_error( ret );
723 goto done;
726 /* now we need to wait */
727 if (current->wait->timeout != TIMEOUT_INFINITE)
729 if (!(current->wait->user = add_timeout_user( current->wait->timeout,
730 thread_timeout, current->wait )))
732 end_wait( current );
733 goto done;
736 current->wait->cookie = cookie;
737 set_error( STATUS_PENDING );
739 done:
740 while (i > 0) release_object( objects[--i] );
741 return timeout;
744 /* attempt to wake threads sleeping on the object wait queue */
745 void wake_up( struct object *obj, int max )
747 struct list *ptr;
749 LIST_FOR_EACH( ptr, &obj->wait_queue )
751 struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
752 if (!wake_thread( entry->thread )) continue;
753 if (max && !--max) break;
754 /* restart at the head of the list since a wake up can change the object wait queue */
755 ptr = &obj->wait_queue;
759 /* return the apc queue to use for a given apc type */
760 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
762 switch(type)
764 case APC_NONE:
765 case APC_USER:
766 case APC_TIMER:
767 return &thread->user_apc;
768 default:
769 return &thread->system_apc;
773 /* check if thread is currently waiting for a (system) apc */
774 static inline int is_in_apc_wait( struct thread *thread )
776 return (thread->process->suspend || thread->suspend ||
777 (thread->wait && (thread->wait->flags & SELECT_INTERRUPTIBLE)));
780 /* queue an existing APC to a given thread */
781 static int queue_apc( struct process *process, struct thread *thread, struct thread_apc *apc )
783 struct list *queue;
785 if (!thread) /* find a suitable thread inside the process */
787 struct thread *candidate;
789 /* first try to find a waiting thread */
790 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
792 if (candidate->state == TERMINATED) continue;
793 if (is_in_apc_wait( candidate ))
795 thread = candidate;
796 break;
799 if (!thread)
801 /* then use the first one that accepts a signal */
802 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
804 if (send_thread_signal( candidate, SIGUSR1 ))
806 thread = candidate;
807 break;
811 if (!thread) return 0; /* nothing found */
812 queue = get_apc_queue( thread, apc->call.type );
814 else
816 if (thread->state == TERMINATED) return 0;
817 queue = get_apc_queue( thread, apc->call.type );
818 /* send signal for system APCs if needed */
819 if (queue == &thread->system_apc && list_empty( queue ) && !is_in_apc_wait( thread ))
821 if (!send_thread_signal( thread, SIGUSR1 )) return 0;
823 /* cancel a possible previous APC with the same owner */
824 if (apc->owner) thread_cancel_apc( thread, apc->owner, apc->call.type );
827 grab_object( apc );
828 list_add_tail( queue, &apc->entry );
829 if (!list_prev( queue, &apc->entry )) /* first one */
830 wake_thread( thread );
832 return 1;
835 /* queue an async procedure call */
836 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
838 struct thread_apc *apc;
839 int ret = 0;
841 if ((apc = create_apc( owner, call_data )))
843 ret = queue_apc( NULL, thread, apc );
844 release_object( apc );
846 return ret;
849 /* cancel the async procedure call owned by a specific object */
850 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
852 struct thread_apc *apc;
853 struct list *queue = get_apc_queue( thread, type );
855 LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
857 if (apc->owner != owner) continue;
858 list_remove( &apc->entry );
859 apc->executed = 1;
860 wake_up( &apc->obj, 0 );
861 release_object( apc );
862 return;
866 /* remove the head apc from the queue; the returned object must be released by the caller */
867 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
869 struct thread_apc *apc = NULL;
870 struct list *ptr = list_head( &thread->system_apc );
872 if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
873 if (ptr)
875 apc = LIST_ENTRY( ptr, struct thread_apc, entry );
876 list_remove( ptr );
878 return apc;
881 /* clear an APC queue, cancelling all the APCs on it */
882 static void clear_apc_queue( struct list *queue )
884 struct list *ptr;
886 while ((ptr = list_head( queue )))
888 struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
889 list_remove( &apc->entry );
890 apc->executed = 1;
891 wake_up( &apc->obj, 0 );
892 release_object( apc );
896 /* add an fd to the inflight list */
897 /* return list index, or -1 on error */
898 int thread_add_inflight_fd( struct thread *thread, int client, int server )
900 int i;
902 if (server == -1) return -1;
903 if (client == -1)
905 close( server );
906 return -1;
909 /* first check if we already have an entry for this fd */
910 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
911 if (thread->inflight[i].client == client)
913 close( thread->inflight[i].server );
914 thread->inflight[i].server = server;
915 return i;
918 /* now find a free spot to store it */
919 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
920 if (thread->inflight[i].client == -1)
922 thread->inflight[i].client = client;
923 thread->inflight[i].server = server;
924 return i;
926 return -1;
929 /* get an inflight fd and purge it from the list */
930 /* the fd must be closed when no longer used */
931 int thread_get_inflight_fd( struct thread *thread, int client )
933 int i, ret;
935 if (client == -1) return -1;
939 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
941 if (thread->inflight[i].client == client)
943 ret = thread->inflight[i].server;
944 thread->inflight[i].server = thread->inflight[i].client = -1;
945 return ret;
948 } while (!receive_fd( thread->process )); /* in case it is still in the socket buffer */
949 return -1;
952 /* kill a thread on the spot */
953 void kill_thread( struct thread *thread, int violent_death )
955 if (thread->state == TERMINATED) return; /* already killed */
956 thread->state = TERMINATED;
957 thread->exit_time = current_time;
958 if (current == thread) current = NULL;
959 if (debug_level)
960 fprintf( stderr,"%04x: *killed* exit_code=%d\n",
961 thread->id, thread->exit_code );
962 if (thread->wait)
964 while (thread->wait) end_wait( thread );
965 send_thread_wakeup( thread, 0, STATUS_PENDING );
966 /* if it is waiting on the socket, we don't need to send a SIGQUIT */
967 violent_death = 0;
969 kill_console_processes( thread, 0 );
970 debug_exit_thread( thread );
971 abandon_mutexes( thread );
972 wake_up( &thread->obj, 0 );
973 if (violent_death) send_thread_signal( thread, SIGQUIT );
974 cleanup_thread( thread );
975 remove_process_thread( thread->process, thread );
976 release_object( thread );
979 /* copy parts of a context structure */
980 static void copy_context( context_t *to, const context_t *from, unsigned int flags )
982 assert( to->cpu == from->cpu );
983 to->flags |= flags;
984 if (flags & SERVER_CTX_CONTROL) to->ctl = from->ctl;
985 if (flags & SERVER_CTX_INTEGER) to->integer = from->integer;
986 if (flags & SERVER_CTX_SEGMENTS) to->seg = from->seg;
987 if (flags & SERVER_CTX_FLOATING_POINT) to->fp = from->fp;
988 if (flags & SERVER_CTX_DEBUG_REGISTERS) to->debug = from->debug;
989 if (flags & SERVER_CTX_EXTENDED_REGISTERS) to->ext = from->ext;
992 /* return the context flags that correspond to system regs */
993 /* (system regs are the ones we can't access on the client side) */
994 static unsigned int get_context_system_regs( enum cpu_type cpu )
996 switch (cpu)
998 case CPU_x86: return SERVER_CTX_DEBUG_REGISTERS;
999 case CPU_x86_64: return SERVER_CTX_DEBUG_REGISTERS;
1000 case CPU_ALPHA: return 0;
1001 case CPU_POWERPC: return 0;
1002 case CPU_SPARC: return 0;
1004 return 0;
1007 /* trigger a breakpoint event in a given thread */
1008 void break_thread( struct thread *thread )
1010 debug_event_t data;
1012 assert( thread->context );
1014 memset( &data, 0, sizeof(data) );
1015 data.exception.first = 1;
1016 data.exception.exc_code = STATUS_BREAKPOINT;
1017 data.exception.flags = EXCEPTION_CONTINUABLE;
1018 switch (thread->context->cpu)
1020 case CPU_x86:
1021 data.exception.address = thread->context->ctl.i386_regs.eip;
1022 break;
1023 case CPU_x86_64:
1024 data.exception.address = thread->context->ctl.x86_64_regs.rip;
1025 break;
1026 case CPU_ALPHA:
1027 data.exception.address = thread->context->ctl.alpha_regs.fir;
1028 break;
1029 case CPU_POWERPC:
1030 data.exception.address = thread->context->ctl.powerpc_regs.iar;
1031 break;
1032 case CPU_SPARC:
1033 data.exception.address = thread->context->ctl.sparc_regs.pc;
1034 break;
1036 generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
1037 thread->debug_break = 0;
1040 /* take a snapshot of currently running threads */
1041 struct thread_snapshot *thread_snap( int *count )
1043 struct thread_snapshot *snapshot, *ptr;
1044 struct thread *thread;
1045 int total = 0;
1047 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1048 if (thread->state != TERMINATED) total++;
1049 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
1050 ptr = snapshot;
1051 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1053 if (thread->state == TERMINATED) continue;
1054 ptr->thread = thread;
1055 ptr->count = thread->obj.refcount;
1056 ptr->priority = thread->priority;
1057 grab_object( thread );
1058 ptr++;
1060 *count = total;
1061 return snapshot;
1064 /* gets the current impersonation token */
1065 struct token *thread_get_impersonation_token( struct thread *thread )
1067 if (thread->token)
1068 return thread->token;
1069 else
1070 return thread->process->token;
1073 /* create a new thread */
1074 DECL_HANDLER(new_thread)
1076 struct thread *thread;
1077 int request_fd = thread_get_inflight_fd( current, req->request_fd );
1079 if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
1081 if (request_fd != -1) close( request_fd );
1082 set_error( STATUS_INVALID_HANDLE );
1083 return;
1086 if ((thread = create_thread( request_fd, current->process )))
1088 if (req->suspend) thread->suspend++;
1089 reply->tid = get_thread_id( thread );
1090 if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
1092 /* thread object will be released when the thread gets killed */
1093 return;
1095 kill_thread( thread, 1 );
1099 /* initialize a new thread */
1100 DECL_HANDLER(init_thread)
1102 struct process *process = current->process;
1103 int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
1104 int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
1106 if (current->reply_fd) /* already initialised */
1108 set_error( STATUS_INVALID_PARAMETER );
1109 goto error;
1112 if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
1114 current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj, 0 );
1115 reply_fd = -1;
1116 if (!current->reply_fd) goto error;
1118 if (wait_fd == -1)
1120 set_error( STATUS_TOO_MANY_OPENED_FILES ); /* most likely reason */
1121 return;
1123 if (!(current->wait_fd = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj, 0 )))
1124 return;
1126 if (!is_valid_address(req->teb))
1128 set_error( STATUS_INVALID_PARAMETER );
1129 return;
1132 current->unix_pid = req->unix_pid;
1133 current->unix_tid = req->unix_tid;
1134 current->teb = req->teb;
1136 if (!process->peb) /* first thread, initialize the process too */
1138 if (!CPU_FLAG(req->cpu) || !(supported_cpus & CPU_FLAG(req->cpu)))
1140 set_error( STATUS_NOT_SUPPORTED );
1141 return;
1143 process->unix_pid = current->unix_pid;
1144 process->peb = req->entry;
1145 process->cpu = req->cpu;
1146 reply->info_size = init_process( current );
1148 else
1150 if (req->cpu != process->cpu)
1152 set_error( STATUS_INVALID_PARAMETER );
1153 return;
1155 if (process->unix_pid != current->unix_pid)
1156 process->unix_pid = -1; /* can happen with linuxthreads */
1157 if (current->suspend + process->suspend > 0) stop_thread( current );
1158 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, &req->entry );
1160 debug_level = max( debug_level, req->debug_level );
1161 set_thread_affinity( current, current->affinity );
1163 reply->pid = get_process_id( process );
1164 reply->tid = get_thread_id( current );
1165 reply->version = SERVER_PROTOCOL_VERSION;
1166 reply->server_start = server_start_time;
1167 reply->all_cpus = supported_cpus;
1168 return;
1170 error:
1171 if (reply_fd != -1) close( reply_fd );
1172 if (wait_fd != -1) close( wait_fd );
1175 /* terminate a thread */
1176 DECL_HANDLER(terminate_thread)
1178 struct thread *thread;
1180 reply->self = 0;
1181 reply->last = 0;
1182 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1184 thread->exit_code = req->exit_code;
1185 if (thread != current) kill_thread( thread, 1 );
1186 else
1188 reply->self = 1;
1189 reply->last = (thread->process->running_threads == 1);
1191 release_object( thread );
1195 /* open a handle to a thread */
1196 DECL_HANDLER(open_thread)
1198 struct thread *thread = get_thread_from_id( req->tid );
1200 reply->handle = 0;
1201 if (thread)
1203 reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1204 release_object( thread );
1208 /* fetch information about a thread */
1209 DECL_HANDLER(get_thread_info)
1211 struct thread *thread;
1212 obj_handle_t handle = req->handle;
1214 if (!handle) thread = get_thread_from_id( req->tid_in );
1215 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1217 if (thread)
1219 reply->pid = get_process_id( thread->process );
1220 reply->tid = get_thread_id( thread );
1221 reply->teb = thread->teb;
1222 reply->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1223 reply->priority = thread->priority;
1224 reply->affinity = thread->affinity;
1225 reply->creation_time = thread->creation_time;
1226 reply->exit_time = thread->exit_time;
1227 reply->last = thread->process->running_threads == 1;
1229 release_object( thread );
1233 /* set information about a thread */
1234 DECL_HANDLER(set_thread_info)
1236 struct thread *thread;
1238 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1240 set_thread_info( thread, req );
1241 release_object( thread );
1245 /* suspend a thread */
1246 DECL_HANDLER(suspend_thread)
1248 struct thread *thread;
1250 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1252 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1253 else reply->count = suspend_thread( thread );
1254 release_object( thread );
1258 /* resume a thread */
1259 DECL_HANDLER(resume_thread)
1261 struct thread *thread;
1263 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1265 reply->count = resume_thread( thread );
1266 release_object( thread );
1270 /* select on a handle list */
1271 DECL_HANDLER(select)
1273 struct thread_apc *apc;
1274 unsigned int count;
1275 const apc_result_t *result = get_req_data();
1276 const obj_handle_t *handles = (const obj_handle_t *)(result + 1);
1278 if (get_req_data_size() < sizeof(*result))
1280 set_error( STATUS_INVALID_PARAMETER );
1281 return;
1283 count = (get_req_data_size() - sizeof(*result)) / sizeof(obj_handle_t);
1285 /* first store results of previous apc */
1286 if (req->prev_apc)
1288 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev_apc,
1289 0, &thread_apc_ops ))) return;
1290 apc->result = *result;
1291 apc->executed = 1;
1292 if (apc->result.type == APC_CREATE_THREAD) /* transfer the handle to the caller process */
1294 obj_handle_t handle = duplicate_handle( current->process, apc->result.create_thread.handle,
1295 apc->caller->process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1296 close_handle( current->process, apc->result.create_thread.handle );
1297 apc->result.create_thread.handle = handle;
1298 clear_error(); /* ignore errors from the above calls */
1300 else if (apc->result.type == APC_ASYNC_IO)
1302 if (apc->owner)
1303 async_set_result( apc->owner, apc->result.async_io.status,
1304 apc->result.async_io.total, apc->result.async_io.apc );
1306 wake_up( &apc->obj, 0 );
1307 close_handle( current->process, req->prev_apc );
1308 release_object( apc );
1311 reply->timeout = select_on( count, req->cookie, handles, req->flags, req->timeout, req->signal );
1313 if (get_error() == STATUS_USER_APC)
1315 for (;;)
1317 if (!(apc = thread_dequeue_apc( current, !(req->flags & SELECT_ALERTABLE) )))
1318 break;
1319 /* Optimization: ignore APC_NONE calls, they are only used to
1320 * wake up a thread, but since we got here the thread woke up already.
1322 if (apc->call.type != APC_NONE)
1324 if ((reply->apc_handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1325 reply->call = apc->call;
1326 release_object( apc );
1327 break;
1329 apc->executed = 1;
1330 wake_up( &apc->obj, 0 );
1331 release_object( apc );
1336 /* queue an APC for a thread or process */
1337 DECL_HANDLER(queue_apc)
1339 struct thread *thread = NULL;
1340 struct process *process = NULL;
1341 struct thread_apc *apc;
1343 if (!(apc = create_apc( NULL, &req->call ))) return;
1345 switch (apc->call.type)
1347 case APC_NONE:
1348 case APC_USER:
1349 thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT );
1350 break;
1351 case APC_VIRTUAL_ALLOC:
1352 case APC_VIRTUAL_FREE:
1353 case APC_VIRTUAL_PROTECT:
1354 case APC_VIRTUAL_FLUSH:
1355 case APC_VIRTUAL_LOCK:
1356 case APC_VIRTUAL_UNLOCK:
1357 case APC_UNMAP_VIEW:
1358 process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1359 break;
1360 case APC_VIRTUAL_QUERY:
1361 process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION );
1362 break;
1363 case APC_MAP_VIEW:
1364 process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1365 if (process && process != current->process)
1367 /* duplicate the handle into the target process */
1368 obj_handle_t handle = duplicate_handle( current->process, apc->call.map_view.handle,
1369 process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1370 if (handle) apc->call.map_view.handle = handle;
1371 else
1373 release_object( process );
1374 process = NULL;
1377 break;
1378 case APC_CREATE_THREAD:
1379 process = get_process_from_handle( req->handle, PROCESS_CREATE_THREAD );
1380 break;
1381 default:
1382 set_error( STATUS_INVALID_PARAMETER );
1383 break;
1386 if (thread)
1388 if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1389 release_object( thread );
1391 else if (process)
1393 reply->self = (process == current->process);
1394 if (!reply->self)
1396 obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1397 if (handle)
1399 if (queue_apc( process, NULL, apc ))
1401 apc->caller = (struct thread *)grab_object( current );
1402 reply->handle = handle;
1404 else
1406 close_handle( current->process, handle );
1407 set_error( STATUS_PROCESS_IS_TERMINATING );
1411 release_object( process );
1414 release_object( apc );
1417 /* Get the result of an APC call */
1418 DECL_HANDLER(get_apc_result)
1420 struct thread_apc *apc;
1422 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1423 0, &thread_apc_ops ))) return;
1424 if (!apc->executed) set_error( STATUS_PENDING );
1425 else
1427 reply->result = apc->result;
1428 /* close the handle directly to avoid an extra round-trip */
1429 close_handle( current->process, req->handle );
1431 release_object( apc );
1434 /* retrieve the current context of a thread */
1435 DECL_HANDLER(get_thread_context)
1437 struct thread *thread;
1438 context_t *context;
1440 if (get_reply_max_size() < sizeof(context_t))
1442 set_error( STATUS_INVALID_PARAMETER );
1443 return;
1445 if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1447 if (req->suspend)
1449 if (thread != current || !thread->suspend_context)
1451 /* not suspended, shouldn't happen */
1452 set_error( STATUS_INVALID_PARAMETER );
1454 else
1456 if (thread->context == thread->suspend_context) thread->context = NULL;
1457 set_reply_data_ptr( thread->suspend_context, sizeof(context_t) );
1458 thread->suspend_context = NULL;
1461 else if (thread != current && !thread->context)
1463 /* thread is not suspended, retry (if it's still running) */
1464 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1465 else set_error( STATUS_PENDING );
1467 else if ((context = set_reply_data_size( sizeof(context_t) )))
1469 unsigned int flags = get_context_system_regs( thread->process->cpu );
1471 memset( context, 0, sizeof(context_t) );
1472 context->cpu = thread->process->cpu;
1473 if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1474 if (flags) get_thread_context( thread, context, flags );
1476 reply->self = (thread == current);
1477 release_object( thread );
1480 /* set the current context of a thread */
1481 DECL_HANDLER(set_thread_context)
1483 struct thread *thread;
1484 const context_t *context = get_req_data();
1486 if (get_req_data_size() < sizeof(context_t))
1488 set_error( STATUS_INVALID_PARAMETER );
1489 return;
1491 if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1493 if (req->suspend)
1495 if (thread != current || thread->context || context->cpu != thread->process->cpu)
1497 /* nested suspend or exception, shouldn't happen */
1498 set_error( STATUS_INVALID_PARAMETER );
1500 else if ((thread->suspend_context = mem_alloc( sizeof(context_t) )))
1502 memcpy( thread->suspend_context, get_req_data(), sizeof(context_t) );
1503 thread->context = thread->suspend_context;
1504 if (thread->debug_break) break_thread( thread );
1507 else if (thread != current && !thread->context)
1509 /* thread is not suspended, retry (if it's still running) */
1510 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1511 else set_error( STATUS_PENDING );
1513 else if (context->cpu == thread->process->cpu)
1515 unsigned int system_flags = get_context_system_regs(context->cpu) & context->flags;
1516 unsigned int client_flags = context->flags & ~system_flags;
1518 if (system_flags) set_thread_context( thread, context, system_flags );
1519 if (thread->context && !get_error()) copy_context( thread->context, context, client_flags );
1521 else set_error( STATUS_INVALID_PARAMETER );
1523 reply->self = (thread == current);
1524 release_object( thread );
1527 /* fetch a selector entry for a thread */
1528 DECL_HANDLER(get_selector_entry)
1530 struct thread *thread;
1531 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1533 get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1534 release_object( thread );