quartz: Rework direct sound renderer rework to be more time aware.
[wine/multimedia.git] / server / thread.c
blob05e4121785baaff6047a2faafd77ada8f2a9967d
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 #ifdef __i386__
57 static const unsigned int supported_cpus = CPU_FLAG(CPU_x86);
58 #elif defined(__x86_64__)
59 static const unsigned int supported_cpus = CPU_FLAG(CPU_x86_64) | CPU_FLAG(CPU_x86);
60 #elif defined(__ALPHA__)
61 static const unsigned int supported_cpus = CPU_FLAG(CPU_ALPHA);
62 #elif defined(__powerpc__)
63 static const unsigned int supported_cpus = CPU_FLAG(CPU_POWERPC);
64 #elif defined(__sparc__)
65 static const unsigned int supported_cpus = CPU_FLAG(CPU_SPARC);
66 #elif defined(__arm__)
67 static const unsigned int supported_cpus = CPU_FLAG(CPU_ARM);
68 #else
69 #error Unsupported CPU
70 #endif
72 /* thread queues */
74 struct thread_wait
76 struct thread_wait *next; /* next wait structure for this thread */
77 struct thread *thread; /* owner thread */
78 int count; /* count of objects */
79 int flags;
80 client_ptr_t cookie; /* magic cookie to return to client */
81 timeout_t timeout;
82 struct timeout_user *user;
83 struct wait_queue_entry queues[1];
86 /* asynchronous procedure calls */
88 struct thread_apc
90 struct object obj; /* object header */
91 struct list entry; /* queue linked list */
92 struct thread *caller; /* thread that queued this apc */
93 struct object *owner; /* object that queued this apc */
94 int executed; /* has it been executed by the client? */
95 apc_call_t call; /* call arguments */
96 apc_result_t result; /* call results once executed */
99 static void dump_thread_apc( struct object *obj, int verbose );
100 static int thread_apc_signaled( struct object *obj, struct thread *thread );
101 static void thread_apc_destroy( struct object *obj );
102 static void clear_apc_queue( struct list *queue );
104 static const struct object_ops thread_apc_ops =
106 sizeof(struct thread_apc), /* size */
107 dump_thread_apc, /* dump */
108 no_get_type, /* get_type */
109 add_queue, /* add_queue */
110 remove_queue, /* remove_queue */
111 thread_apc_signaled, /* signaled */
112 no_satisfied, /* satisfied */
113 no_signal, /* signal */
114 no_get_fd, /* get_fd */
115 no_map_access, /* map_access */
116 default_get_sd, /* get_sd */
117 default_set_sd, /* set_sd */
118 no_lookup_name, /* lookup_name */
119 no_open_file, /* open_file */
120 no_close_handle, /* close_handle */
121 thread_apc_destroy /* destroy */
125 /* thread operations */
127 static void dump_thread( struct object *obj, int verbose );
128 static int thread_signaled( struct object *obj, struct thread *thread );
129 static unsigned int thread_map_access( struct object *obj, unsigned int access );
130 static void thread_poll_event( struct fd *fd, int event );
131 static void destroy_thread( struct object *obj );
133 static const struct object_ops thread_ops =
135 sizeof(struct thread), /* size */
136 dump_thread, /* dump */
137 no_get_type, /* get_type */
138 add_queue, /* add_queue */
139 remove_queue, /* remove_queue */
140 thread_signaled, /* signaled */
141 no_satisfied, /* satisfied */
142 no_signal, /* signal */
143 no_get_fd, /* get_fd */
144 thread_map_access, /* map_access */
145 default_get_sd, /* get_sd */
146 default_set_sd, /* set_sd */
147 no_lookup_name, /* lookup_name */
148 no_open_file, /* open_file */
149 no_close_handle, /* close_handle */
150 destroy_thread /* destroy */
153 static const struct fd_ops thread_fd_ops =
155 NULL, /* get_poll_events */
156 thread_poll_event, /* poll_event */
157 NULL, /* flush */
158 NULL, /* get_fd_type */
159 NULL, /* ioctl */
160 NULL, /* queue_async */
161 NULL, /* reselect_async */
162 NULL /* cancel_async */
165 static struct list thread_list = LIST_INIT(thread_list);
167 /* initialize the structure for a newly allocated thread */
168 static inline void init_thread_structure( struct thread *thread )
170 int i;
172 thread->unix_pid = -1; /* not known yet */
173 thread->unix_tid = -1; /* not known yet */
174 thread->context = NULL;
175 thread->suspend_context = NULL;
176 thread->teb = 0;
177 thread->debug_ctx = NULL;
178 thread->debug_event = NULL;
179 thread->debug_break = 0;
180 thread->queue = NULL;
181 thread->wait = NULL;
182 thread->error = 0;
183 thread->req_data = NULL;
184 thread->req_toread = 0;
185 thread->reply_data = NULL;
186 thread->reply_towrite = 0;
187 thread->request_fd = NULL;
188 thread->reply_fd = NULL;
189 thread->wait_fd = NULL;
190 thread->state = RUNNING;
191 thread->exit_code = 0;
192 thread->priority = 0;
193 thread->affinity = ~0;
194 thread->suspend = 0;
195 thread->desktop_users = 0;
196 thread->token = NULL;
198 thread->creation_time = current_time;
199 thread->exit_time = 0;
201 list_init( &thread->mutex_list );
202 list_init( &thread->system_apc );
203 list_init( &thread->user_apc );
205 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
206 thread->inflight[i].server = thread->inflight[i].client = -1;
209 /* check if address looks valid for a client-side data structure (TEB etc.) */
210 static inline int is_valid_address( client_ptr_t addr )
212 return addr && !(addr % sizeof(int));
215 /* create a new thread */
216 struct thread *create_thread( int fd, struct process *process )
218 struct thread *thread;
220 if (!(thread = alloc_object( &thread_ops ))) return NULL;
222 init_thread_structure( thread );
224 thread->process = (struct process *)grab_object( process );
225 thread->desktop = process->desktop;
226 thread->affinity = process->affinity;
227 if (!current) current = thread;
229 list_add_head( &thread_list, &thread->entry );
231 if (!(thread->id = alloc_ptid( thread )))
233 release_object( thread );
234 return NULL;
236 if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj, 0 )))
238 release_object( thread );
239 return NULL;
242 set_fd_events( thread->request_fd, POLLIN ); /* start listening to events */
243 add_process_thread( thread->process, thread );
244 return thread;
247 /* handle a client event */
248 static void thread_poll_event( struct fd *fd, int event )
250 struct thread *thread = get_fd_user( fd );
251 assert( thread->obj.ops == &thread_ops );
253 grab_object( thread );
254 if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
255 else if (event & POLLIN) read_request( thread );
256 else if (event & POLLOUT) write_reply( thread );
257 release_object( thread );
260 /* cleanup everything that is no longer needed by a dead thread */
261 /* used by destroy_thread and kill_thread */
262 static void cleanup_thread( struct thread *thread )
264 int i;
266 clear_apc_queue( &thread->system_apc );
267 clear_apc_queue( &thread->user_apc );
268 free( thread->req_data );
269 free( thread->reply_data );
270 if (thread->request_fd) release_object( thread->request_fd );
271 if (thread->reply_fd) release_object( thread->reply_fd );
272 if (thread->wait_fd) release_object( thread->wait_fd );
273 free( thread->suspend_context );
274 cleanup_clipboard_thread(thread);
275 destroy_thread_windows( thread );
276 free_msg_queue( thread );
277 close_thread_desktop( thread );
278 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
280 if (thread->inflight[i].client != -1)
282 close( thread->inflight[i].server );
283 thread->inflight[i].client = thread->inflight[i].server = -1;
286 thread->req_data = NULL;
287 thread->reply_data = NULL;
288 thread->request_fd = NULL;
289 thread->reply_fd = NULL;
290 thread->wait_fd = NULL;
291 thread->context = NULL;
292 thread->suspend_context = NULL;
293 thread->desktop = 0;
296 /* destroy a thread when its refcount is 0 */
297 static void destroy_thread( struct object *obj )
299 struct thread *thread = (struct thread *)obj;
300 assert( obj->ops == &thread_ops );
302 assert( !thread->debug_ctx ); /* cannot still be debugging something */
303 list_remove( &thread->entry );
304 cleanup_thread( thread );
305 release_object( thread->process );
306 if (thread->id) free_ptid( thread->id );
307 if (thread->token) release_object( thread->token );
310 /* dump a thread on stdout for debugging purposes */
311 static void dump_thread( struct object *obj, int verbose )
313 struct thread *thread = (struct thread *)obj;
314 assert( obj->ops == &thread_ops );
316 fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d state=%d\n",
317 thread->id, thread->unix_pid, thread->unix_tid, thread->state );
320 static int thread_signaled( struct object *obj, struct thread *thread )
322 struct thread *mythread = (struct thread *)obj;
323 return (mythread->state == TERMINATED);
326 static unsigned int thread_map_access( struct object *obj, unsigned int access )
328 if (access & GENERIC_READ) access |= STANDARD_RIGHTS_READ | SYNCHRONIZE;
329 if (access & GENERIC_WRITE) access |= STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
330 if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
331 if (access & GENERIC_ALL) access |= THREAD_ALL_ACCESS;
332 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
335 static void dump_thread_apc( struct object *obj, int verbose )
337 struct thread_apc *apc = (struct thread_apc *)obj;
338 assert( obj->ops == &thread_apc_ops );
340 fprintf( stderr, "APC owner=%p type=%u\n", apc->owner, apc->call.type );
343 static int thread_apc_signaled( struct object *obj, struct thread *thread )
345 struct thread_apc *apc = (struct thread_apc *)obj;
346 return apc->executed;
349 static void thread_apc_destroy( struct object *obj )
351 struct thread_apc *apc = (struct thread_apc *)obj;
352 if (apc->caller) release_object( apc->caller );
353 if (apc->owner) release_object( apc->owner );
356 /* queue an async procedure call */
357 static struct thread_apc *create_apc( struct object *owner, const apc_call_t *call_data )
359 struct thread_apc *apc;
361 if ((apc = alloc_object( &thread_apc_ops )))
363 apc->call = *call_data;
364 apc->caller = NULL;
365 apc->owner = owner;
366 apc->executed = 0;
367 apc->result.type = APC_NONE;
368 if (owner) grab_object( owner );
370 return apc;
373 /* get a thread pointer from a thread id (and increment the refcount) */
374 struct thread *get_thread_from_id( thread_id_t id )
376 struct object *obj = get_ptid_entry( id );
378 if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
379 set_error( STATUS_INVALID_CID );
380 return NULL;
383 /* get a thread from a handle (and increment the refcount) */
384 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
386 return (struct thread *)get_handle_obj( current->process, handle,
387 access, &thread_ops );
390 /* find a thread from a Unix tid */
391 struct thread *get_thread_from_tid( int tid )
393 struct thread *thread;
395 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
397 if (thread->unix_tid == tid) return thread;
399 return NULL;
402 /* find a thread from a Unix pid */
403 struct thread *get_thread_from_pid( int pid )
405 struct thread *thread;
407 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
409 if (thread->unix_pid == pid) return thread;
411 return NULL;
414 int set_thread_affinity( struct thread *thread, affinity_t affinity )
416 int ret = 0;
417 #ifdef HAVE_SCHED_SETAFFINITY
418 if (thread->unix_tid != -1)
420 cpu_set_t set;
421 int i;
422 affinity_t mask;
424 CPU_ZERO( &set );
425 for (i = 0, mask = 1; mask; i++, mask <<= 1)
426 if (affinity & mask) CPU_SET( i, &set );
428 ret = sched_setaffinity( thread->unix_tid, sizeof(set), &set );
430 #endif
431 if (!ret) thread->affinity = affinity;
432 return ret;
435 #define THREAD_PRIORITY_REALTIME_HIGHEST 6
436 #define THREAD_PRIORITY_REALTIME_LOWEST -7
438 /* set all information about a thread */
439 static void set_thread_info( struct thread *thread,
440 const struct set_thread_info_request *req )
442 if (req->mask & SET_THREAD_INFO_PRIORITY)
444 int max = THREAD_PRIORITY_HIGHEST;
445 int min = THREAD_PRIORITY_LOWEST;
446 if (thread->process->priority == PROCESS_PRIOCLASS_REALTIME)
448 max = THREAD_PRIORITY_REALTIME_HIGHEST;
449 min = THREAD_PRIORITY_REALTIME_LOWEST;
451 if ((req->priority >= min && req->priority <= max) ||
452 req->priority == THREAD_PRIORITY_IDLE ||
453 req->priority == THREAD_PRIORITY_TIME_CRITICAL)
454 thread->priority = req->priority;
455 else
456 set_error( STATUS_INVALID_PARAMETER );
458 if (req->mask & SET_THREAD_INFO_AFFINITY)
460 if ((req->affinity & thread->process->affinity) != req->affinity)
461 set_error( STATUS_INVALID_PARAMETER );
462 else if (thread->state == TERMINATED)
463 set_error( STATUS_ACCESS_DENIED );
464 else if (set_thread_affinity( thread, req->affinity ))
465 file_set_error();
467 if (req->mask & SET_THREAD_INFO_TOKEN)
468 security_set_thread_token( thread, req->token );
471 /* stop a thread (at the Unix level) */
472 void stop_thread( struct thread *thread )
474 if (thread->context) return; /* already inside a debug event, no need for a signal */
475 /* can't stop a thread while initialisation is in progress */
476 if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
479 /* suspend a thread */
480 static int suspend_thread( struct thread *thread )
482 int old_count = thread->suspend;
483 if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
485 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
487 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
488 return old_count;
491 /* resume a thread */
492 static int resume_thread( struct thread *thread )
494 int old_count = thread->suspend;
495 if (thread->suspend > 0)
497 if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
499 return old_count;
502 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
503 int add_queue( struct object *obj, struct wait_queue_entry *entry )
505 grab_object( obj );
506 entry->obj = obj;
507 list_add_tail( &obj->wait_queue, &entry->entry );
508 return 1;
511 /* remove a thread from an object wait queue */
512 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
514 list_remove( &entry->entry );
515 release_object( obj );
518 /* finish waiting */
519 static void end_wait( struct thread *thread )
521 struct thread_wait *wait = thread->wait;
522 struct wait_queue_entry *entry;
523 int i;
525 assert( wait );
526 thread->wait = wait->next;
527 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
528 entry->obj->ops->remove_queue( entry->obj, entry );
529 if (wait->user) remove_timeout_user( wait->user );
530 free( wait );
533 /* build the thread wait structure */
534 static int wait_on( unsigned int count, struct object *objects[], int flags, timeout_t timeout )
536 struct thread_wait *wait;
537 struct wait_queue_entry *entry;
538 unsigned int i;
540 if (!(wait = mem_alloc( FIELD_OFFSET(struct thread_wait, queues[count]) ))) return 0;
541 wait->next = current->wait;
542 wait->thread = current;
543 wait->count = count;
544 wait->flags = flags;
545 wait->user = NULL;
546 wait->timeout = timeout;
547 current->wait = wait;
549 for (i = 0, entry = wait->queues; i < count; i++, entry++)
551 struct object *obj = objects[i];
552 entry->thread = current;
553 if (!obj->ops->add_queue( obj, entry ))
555 wait->count = i;
556 end_wait( current );
557 return 0;
560 return 1;
563 /* check if the thread waiting condition is satisfied */
564 static int check_wait( struct thread *thread )
566 int i, signaled;
567 struct thread_wait *wait = thread->wait;
568 struct wait_queue_entry *entry = wait->queues;
570 assert( wait );
572 if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
573 return STATUS_USER_APC;
575 /* Suspended threads may not acquire locks, but they can run system APCs */
576 if (thread->process->suspend + thread->suspend > 0) return -1;
578 if (wait->flags & SELECT_ALL)
580 int not_ok = 0;
581 /* Note: we must check them all anyway, as some objects may
582 * want to do something when signaled, even if others are not */
583 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
584 not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
585 if (not_ok) goto other_checks;
586 /* Wait satisfied: tell it to all objects */
587 signaled = 0;
588 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
589 if (entry->obj->ops->satisfied( entry->obj, thread ))
590 signaled = STATUS_ABANDONED_WAIT_0;
591 return signaled;
593 else
595 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
597 if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
598 /* Wait satisfied: tell it to the object */
599 signaled = i;
600 if (entry->obj->ops->satisfied( entry->obj, thread ))
601 signaled = i + STATUS_ABANDONED_WAIT_0;
602 return signaled;
606 other_checks:
607 if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
608 if (wait->timeout <= current_time) return STATUS_TIMEOUT;
609 return -1;
612 /* send the wakeup signal to a thread */
613 static int send_thread_wakeup( struct thread *thread, client_ptr_t cookie, int signaled )
615 struct wake_up_reply reply;
616 int ret;
618 memset( &reply, 0, sizeof(reply) );
619 reply.cookie = cookie;
620 reply.signaled = signaled;
621 if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
622 return 0;
623 if (ret >= 0)
624 fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
625 else if (errno == EPIPE)
626 kill_thread( thread, 0 ); /* normal death */
627 else
628 fatal_protocol_perror( thread, "write" );
629 return -1;
632 /* attempt to wake up a thread */
633 /* return >0 if OK, 0 if the wait condition is still not satisfied */
634 int wake_thread( struct thread *thread )
636 int signaled, count;
637 client_ptr_t cookie;
639 for (count = 0; thread->wait; count++)
641 if ((signaled = check_wait( thread )) == -1) break;
643 cookie = thread->wait->cookie;
644 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d\n", thread->id, signaled );
645 end_wait( thread );
646 if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
647 break;
649 return count;
652 /* thread wait timeout */
653 static void thread_timeout( void *ptr )
655 struct thread_wait *wait = ptr;
656 struct thread *thread = wait->thread;
657 client_ptr_t cookie = wait->cookie;
659 wait->user = NULL;
660 if (thread->wait != wait) return; /* not the top-level wait, ignore it */
661 if (thread->suspend + thread->process->suspend > 0) return; /* suspended, ignore it */
663 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=TIMEOUT\n", thread->id );
664 end_wait( thread );
665 if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
666 /* check if other objects have become signaled in the meantime */
667 wake_thread( thread );
670 /* try signaling an event flag, a semaphore or a mutex */
671 static int signal_object( obj_handle_t handle )
673 struct object *obj;
674 int ret = 0;
676 obj = get_handle_obj( current->process, handle, 0, NULL );
677 if (obj)
679 ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
680 release_object( obj );
682 return ret;
685 /* select on a list of handles */
686 static timeout_t select_on( unsigned int count, client_ptr_t cookie, const obj_handle_t *handles,
687 int flags, timeout_t timeout, obj_handle_t signal_obj )
689 int ret;
690 unsigned int i;
691 struct object *objects[MAXIMUM_WAIT_OBJECTS];
693 if (timeout <= 0) timeout = current_time - timeout;
695 if (count > MAXIMUM_WAIT_OBJECTS)
697 set_error( STATUS_INVALID_PARAMETER );
698 return 0;
700 for (i = 0; i < count; i++)
702 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
703 break;
706 if (i < count) goto done;
707 if (!wait_on( count, objects, flags, timeout )) goto done;
709 /* signal the object */
710 if (signal_obj)
712 if (!signal_object( signal_obj ))
714 end_wait( current );
715 goto done;
717 /* check if we woke ourselves up */
718 if (!current->wait) goto done;
721 if ((ret = check_wait( current )) != -1)
723 /* condition is already satisfied */
724 end_wait( current );
725 set_error( ret );
726 goto done;
729 /* now we need to wait */
730 if (current->wait->timeout != TIMEOUT_INFINITE)
732 if (!(current->wait->user = add_timeout_user( current->wait->timeout,
733 thread_timeout, current->wait )))
735 end_wait( current );
736 goto done;
739 current->wait->cookie = cookie;
740 set_error( STATUS_PENDING );
742 done:
743 while (i > 0) release_object( objects[--i] );
744 return timeout;
747 /* attempt to wake threads sleeping on the object wait queue */
748 void wake_up( struct object *obj, int max )
750 struct list *ptr;
752 LIST_FOR_EACH( ptr, &obj->wait_queue )
754 struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
755 if (!wake_thread( entry->thread )) continue;
756 if (max && !--max) break;
757 /* restart at the head of the list since a wake up can change the object wait queue */
758 ptr = &obj->wait_queue;
762 /* return the apc queue to use for a given apc type */
763 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
765 switch(type)
767 case APC_NONE:
768 case APC_USER:
769 case APC_TIMER:
770 return &thread->user_apc;
771 default:
772 return &thread->system_apc;
776 /* check if thread is currently waiting for a (system) apc */
777 static inline int is_in_apc_wait( struct thread *thread )
779 return (thread->process->suspend || thread->suspend ||
780 (thread->wait && (thread->wait->flags & SELECT_INTERRUPTIBLE)));
783 /* queue an existing APC to a given thread */
784 static int queue_apc( struct process *process, struct thread *thread, struct thread_apc *apc )
786 struct list *queue;
788 if (!thread) /* find a suitable thread inside the process */
790 struct thread *candidate;
792 /* first try to find a waiting thread */
793 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
795 if (candidate->state == TERMINATED) continue;
796 if (is_in_apc_wait( candidate ))
798 thread = candidate;
799 break;
802 if (!thread)
804 /* then use the first one that accepts a signal */
805 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
807 if (send_thread_signal( candidate, SIGUSR1 ))
809 thread = candidate;
810 break;
814 if (!thread) return 0; /* nothing found */
815 queue = get_apc_queue( thread, apc->call.type );
817 else
819 if (thread->state == TERMINATED) return 0;
820 queue = get_apc_queue( thread, apc->call.type );
821 /* send signal for system APCs if needed */
822 if (queue == &thread->system_apc && list_empty( queue ) && !is_in_apc_wait( thread ))
824 if (!send_thread_signal( thread, SIGUSR1 )) return 0;
826 /* cancel a possible previous APC with the same owner */
827 if (apc->owner) thread_cancel_apc( thread, apc->owner, apc->call.type );
830 grab_object( apc );
831 list_add_tail( queue, &apc->entry );
832 if (!list_prev( queue, &apc->entry )) /* first one */
833 wake_thread( thread );
835 return 1;
838 /* queue an async procedure call */
839 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
841 struct thread_apc *apc;
842 int ret = 0;
844 if ((apc = create_apc( owner, call_data )))
846 ret = queue_apc( NULL, thread, apc );
847 release_object( apc );
849 return ret;
852 /* cancel the async procedure call owned by a specific object */
853 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
855 struct thread_apc *apc;
856 struct list *queue = get_apc_queue( thread, type );
858 LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
860 if (apc->owner != owner) continue;
861 list_remove( &apc->entry );
862 apc->executed = 1;
863 wake_up( &apc->obj, 0 );
864 release_object( apc );
865 return;
869 /* remove the head apc from the queue; the returned object must be released by the caller */
870 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
872 struct thread_apc *apc = NULL;
873 struct list *ptr = list_head( &thread->system_apc );
875 if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
876 if (ptr)
878 apc = LIST_ENTRY( ptr, struct thread_apc, entry );
879 list_remove( ptr );
881 return apc;
884 /* clear an APC queue, cancelling all the APCs on it */
885 static void clear_apc_queue( struct list *queue )
887 struct list *ptr;
889 while ((ptr = list_head( queue )))
891 struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
892 list_remove( &apc->entry );
893 apc->executed = 1;
894 wake_up( &apc->obj, 0 );
895 release_object( apc );
899 /* add an fd to the inflight list */
900 /* return list index, or -1 on error */
901 int thread_add_inflight_fd( struct thread *thread, int client, int server )
903 int i;
905 if (server == -1) return -1;
906 if (client == -1)
908 close( server );
909 return -1;
912 /* first check if we already have an entry for this fd */
913 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
914 if (thread->inflight[i].client == client)
916 close( thread->inflight[i].server );
917 thread->inflight[i].server = server;
918 return i;
921 /* now find a free spot to store it */
922 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
923 if (thread->inflight[i].client == -1)
925 thread->inflight[i].client = client;
926 thread->inflight[i].server = server;
927 return i;
929 return -1;
932 /* get an inflight fd and purge it from the list */
933 /* the fd must be closed when no longer used */
934 int thread_get_inflight_fd( struct thread *thread, int client )
936 int i, ret;
938 if (client == -1) return -1;
942 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
944 if (thread->inflight[i].client == client)
946 ret = thread->inflight[i].server;
947 thread->inflight[i].server = thread->inflight[i].client = -1;
948 return ret;
951 } while (!receive_fd( thread->process )); /* in case it is still in the socket buffer */
952 return -1;
955 /* kill a thread on the spot */
956 void kill_thread( struct thread *thread, int violent_death )
958 if (thread->state == TERMINATED) return; /* already killed */
959 thread->state = TERMINATED;
960 thread->exit_time = current_time;
961 if (current == thread) current = NULL;
962 if (debug_level)
963 fprintf( stderr,"%04x: *killed* exit_code=%d\n",
964 thread->id, thread->exit_code );
965 if (thread->wait)
967 while (thread->wait) end_wait( thread );
968 send_thread_wakeup( thread, 0, STATUS_PENDING );
969 /* if it is waiting on the socket, we don't need to send a SIGQUIT */
970 violent_death = 0;
972 kill_console_processes( thread, 0 );
973 debug_exit_thread( thread );
974 abandon_mutexes( thread );
975 wake_up( &thread->obj, 0 );
976 if (violent_death) send_thread_signal( thread, SIGQUIT );
977 cleanup_thread( thread );
978 remove_process_thread( thread->process, thread );
979 release_object( thread );
982 /* copy parts of a context structure */
983 static void copy_context( context_t *to, const context_t *from, unsigned int flags )
985 assert( to->cpu == from->cpu );
986 to->flags |= flags;
987 if (flags & SERVER_CTX_CONTROL) to->ctl = from->ctl;
988 if (flags & SERVER_CTX_INTEGER) to->integer = from->integer;
989 if (flags & SERVER_CTX_SEGMENTS) to->seg = from->seg;
990 if (flags & SERVER_CTX_FLOATING_POINT) to->fp = from->fp;
991 if (flags & SERVER_CTX_DEBUG_REGISTERS) to->debug = from->debug;
992 if (flags & SERVER_CTX_EXTENDED_REGISTERS) to->ext = from->ext;
995 /* return the context flags that correspond to system regs */
996 /* (system regs are the ones we can't access on the client side) */
997 static unsigned int get_context_system_regs( enum cpu_type cpu )
999 switch (cpu)
1001 case CPU_x86: return SERVER_CTX_DEBUG_REGISTERS;
1002 case CPU_x86_64: return SERVER_CTX_DEBUG_REGISTERS;
1003 case CPU_ALPHA: return 0;
1004 case CPU_POWERPC: return 0;
1005 case CPU_ARM: return 0;
1006 case CPU_SPARC: return 0;
1008 return 0;
1011 /* trigger a breakpoint event in a given thread */
1012 void break_thread( struct thread *thread )
1014 debug_event_t data;
1016 assert( thread->context );
1018 memset( &data, 0, sizeof(data) );
1019 data.exception.first = 1;
1020 data.exception.exc_code = STATUS_BREAKPOINT;
1021 data.exception.flags = EXCEPTION_CONTINUABLE;
1022 switch (thread->context->cpu)
1024 case CPU_x86:
1025 data.exception.address = thread->context->ctl.i386_regs.eip;
1026 break;
1027 case CPU_x86_64:
1028 data.exception.address = thread->context->ctl.x86_64_regs.rip;
1029 break;
1030 case CPU_ALPHA:
1031 data.exception.address = thread->context->ctl.alpha_regs.fir;
1032 break;
1033 case CPU_POWERPC:
1034 data.exception.address = thread->context->ctl.powerpc_regs.iar;
1035 break;
1036 case CPU_SPARC:
1037 data.exception.address = thread->context->ctl.sparc_regs.pc;
1038 break;
1039 case CPU_ARM:
1040 data.exception.address = thread->context->ctl.arm_regs.pc;
1041 break;
1043 generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
1044 thread->debug_break = 0;
1047 /* take a snapshot of currently running threads */
1048 struct thread_snapshot *thread_snap( int *count )
1050 struct thread_snapshot *snapshot, *ptr;
1051 struct thread *thread;
1052 int total = 0;
1054 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1055 if (thread->state != TERMINATED) total++;
1056 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
1057 ptr = snapshot;
1058 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1060 if (thread->state == TERMINATED) continue;
1061 ptr->thread = thread;
1062 ptr->count = thread->obj.refcount;
1063 ptr->priority = thread->priority;
1064 grab_object( thread );
1065 ptr++;
1067 *count = total;
1068 return snapshot;
1071 /* gets the current impersonation token */
1072 struct token *thread_get_impersonation_token( struct thread *thread )
1074 if (thread->token)
1075 return thread->token;
1076 else
1077 return thread->process->token;
1080 /* create a new thread */
1081 DECL_HANDLER(new_thread)
1083 struct thread *thread;
1084 int request_fd = thread_get_inflight_fd( current, req->request_fd );
1086 if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
1088 if (request_fd != -1) close( request_fd );
1089 set_error( STATUS_INVALID_HANDLE );
1090 return;
1093 if ((thread = create_thread( request_fd, current->process )))
1095 if (req->suspend) thread->suspend++;
1096 reply->tid = get_thread_id( thread );
1097 if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
1099 /* thread object will be released when the thread gets killed */
1100 return;
1102 kill_thread( thread, 1 );
1106 /* initialize a new thread */
1107 DECL_HANDLER(init_thread)
1109 unsigned int prefix_cpu_mask = get_prefix_cpu_mask();
1110 struct process *process = current->process;
1111 int wait_fd, reply_fd;
1113 if ((reply_fd = thread_get_inflight_fd( current, req->reply_fd )) == -1)
1115 set_error( STATUS_TOO_MANY_OPENED_FILES );
1116 return;
1118 if ((wait_fd = thread_get_inflight_fd( current, req->wait_fd )) == -1)
1120 set_error( STATUS_TOO_MANY_OPENED_FILES );
1121 goto error;
1124 if (current->reply_fd) /* already initialised */
1126 set_error( STATUS_INVALID_PARAMETER );
1127 goto error;
1130 if (fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
1132 current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj, 0 );
1133 current->wait_fd = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj, 0 );
1134 if (!current->reply_fd || !current->wait_fd) return;
1136 if (!is_valid_address(req->teb))
1138 set_error( STATUS_INVALID_PARAMETER );
1139 return;
1142 current->unix_pid = req->unix_pid;
1143 current->unix_tid = req->unix_tid;
1144 current->teb = req->teb;
1146 if (!process->peb) /* first thread, initialize the process too */
1148 if (!CPU_FLAG(req->cpu) || !(supported_cpus & prefix_cpu_mask & CPU_FLAG(req->cpu)))
1150 if (!(supported_cpus & CPU_64BIT_MASK))
1151 set_error( STATUS_NOT_SUPPORTED );
1152 else
1153 set_error( STATUS_NOT_REGISTRY_FILE ); /* server supports it but not the prefix */
1154 return;
1156 process->unix_pid = current->unix_pid;
1157 process->peb = req->entry;
1158 process->cpu = req->cpu;
1159 reply->info_size = init_process( current );
1161 else
1163 if (req->cpu != process->cpu)
1165 set_error( STATUS_INVALID_PARAMETER );
1166 return;
1168 if (process->unix_pid != current->unix_pid)
1169 process->unix_pid = -1; /* can happen with linuxthreads */
1170 if (current->suspend + process->suspend > 0) stop_thread( current );
1171 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, &req->entry );
1173 debug_level = max( debug_level, req->debug_level );
1174 set_thread_affinity( current, current->affinity );
1176 reply->pid = get_process_id( process );
1177 reply->tid = get_thread_id( current );
1178 reply->version = SERVER_PROTOCOL_VERSION;
1179 reply->server_start = server_start_time;
1180 reply->all_cpus = supported_cpus & prefix_cpu_mask;
1181 return;
1183 error:
1184 if (reply_fd != -1) close( reply_fd );
1185 if (wait_fd != -1) close( wait_fd );
1188 /* terminate a thread */
1189 DECL_HANDLER(terminate_thread)
1191 struct thread *thread;
1193 reply->self = 0;
1194 reply->last = 0;
1195 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1197 thread->exit_code = req->exit_code;
1198 if (thread != current) kill_thread( thread, 1 );
1199 else
1201 reply->self = 1;
1202 reply->last = (thread->process->running_threads == 1);
1204 release_object( thread );
1208 /* open a handle to a thread */
1209 DECL_HANDLER(open_thread)
1211 struct thread *thread = get_thread_from_id( req->tid );
1213 reply->handle = 0;
1214 if (thread)
1216 reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1217 release_object( thread );
1221 /* fetch information about a thread */
1222 DECL_HANDLER(get_thread_info)
1224 struct thread *thread;
1225 obj_handle_t handle = req->handle;
1227 if (!handle) thread = get_thread_from_id( req->tid_in );
1228 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1230 if (thread)
1232 reply->pid = get_process_id( thread->process );
1233 reply->tid = get_thread_id( thread );
1234 reply->teb = thread->teb;
1235 reply->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1236 reply->priority = thread->priority;
1237 reply->affinity = thread->affinity;
1238 reply->creation_time = thread->creation_time;
1239 reply->exit_time = thread->exit_time;
1240 reply->last = thread->process->running_threads == 1;
1242 release_object( thread );
1246 /* set information about a thread */
1247 DECL_HANDLER(set_thread_info)
1249 struct thread *thread;
1251 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1253 set_thread_info( thread, req );
1254 release_object( thread );
1258 /* suspend a thread */
1259 DECL_HANDLER(suspend_thread)
1261 struct thread *thread;
1263 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1265 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1266 else reply->count = suspend_thread( thread );
1267 release_object( thread );
1271 /* resume a thread */
1272 DECL_HANDLER(resume_thread)
1274 struct thread *thread;
1276 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1278 reply->count = resume_thread( thread );
1279 release_object( thread );
1283 /* select on a handle list */
1284 DECL_HANDLER(select)
1286 struct thread_apc *apc;
1287 unsigned int count;
1288 const apc_result_t *result = get_req_data();
1289 const obj_handle_t *handles = (const obj_handle_t *)(result + 1);
1291 if (get_req_data_size() < sizeof(*result))
1293 set_error( STATUS_INVALID_PARAMETER );
1294 return;
1296 count = (get_req_data_size() - sizeof(*result)) / sizeof(obj_handle_t);
1298 /* first store results of previous apc */
1299 if (req->prev_apc)
1301 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev_apc,
1302 0, &thread_apc_ops ))) return;
1303 apc->result = *result;
1304 apc->executed = 1;
1305 if (apc->result.type == APC_CREATE_THREAD) /* transfer the handle to the caller process */
1307 obj_handle_t handle = duplicate_handle( current->process, apc->result.create_thread.handle,
1308 apc->caller->process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1309 close_handle( current->process, apc->result.create_thread.handle );
1310 apc->result.create_thread.handle = handle;
1311 clear_error(); /* ignore errors from the above calls */
1313 else if (apc->result.type == APC_ASYNC_IO)
1315 if (apc->owner)
1316 async_set_result( apc->owner, apc->result.async_io.status,
1317 apc->result.async_io.total, apc->result.async_io.apc );
1319 wake_up( &apc->obj, 0 );
1320 close_handle( current->process, req->prev_apc );
1321 release_object( apc );
1324 reply->timeout = select_on( count, req->cookie, handles, req->flags, req->timeout, req->signal );
1326 if (get_error() == STATUS_USER_APC)
1328 for (;;)
1330 if (!(apc = thread_dequeue_apc( current, !(req->flags & SELECT_ALERTABLE) )))
1331 break;
1332 /* Optimization: ignore APC_NONE calls, they are only used to
1333 * wake up a thread, but since we got here the thread woke up already.
1335 if (apc->call.type != APC_NONE)
1337 if ((reply->apc_handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1338 reply->call = apc->call;
1339 release_object( apc );
1340 break;
1342 apc->executed = 1;
1343 wake_up( &apc->obj, 0 );
1344 release_object( apc );
1349 /* queue an APC for a thread or process */
1350 DECL_HANDLER(queue_apc)
1352 struct thread *thread = NULL;
1353 struct process *process = NULL;
1354 struct thread_apc *apc;
1356 if (!(apc = create_apc( NULL, &req->call ))) return;
1358 switch (apc->call.type)
1360 case APC_NONE:
1361 case APC_USER:
1362 thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT );
1363 break;
1364 case APC_VIRTUAL_ALLOC:
1365 case APC_VIRTUAL_FREE:
1366 case APC_VIRTUAL_PROTECT:
1367 case APC_VIRTUAL_FLUSH:
1368 case APC_VIRTUAL_LOCK:
1369 case APC_VIRTUAL_UNLOCK:
1370 case APC_UNMAP_VIEW:
1371 process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1372 break;
1373 case APC_VIRTUAL_QUERY:
1374 process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION );
1375 break;
1376 case APC_MAP_VIEW:
1377 process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1378 if (process && process != current->process)
1380 /* duplicate the handle into the target process */
1381 obj_handle_t handle = duplicate_handle( current->process, apc->call.map_view.handle,
1382 process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1383 if (handle) apc->call.map_view.handle = handle;
1384 else
1386 release_object( process );
1387 process = NULL;
1390 break;
1391 case APC_CREATE_THREAD:
1392 process = get_process_from_handle( req->handle, PROCESS_CREATE_THREAD );
1393 break;
1394 default:
1395 set_error( STATUS_INVALID_PARAMETER );
1396 break;
1399 if (thread)
1401 if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1402 release_object( thread );
1404 else if (process)
1406 reply->self = (process == current->process);
1407 if (!reply->self)
1409 obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1410 if (handle)
1412 if (queue_apc( process, NULL, apc ))
1414 apc->caller = (struct thread *)grab_object( current );
1415 reply->handle = handle;
1417 else
1419 close_handle( current->process, handle );
1420 set_error( STATUS_PROCESS_IS_TERMINATING );
1424 release_object( process );
1427 release_object( apc );
1430 /* Get the result of an APC call */
1431 DECL_HANDLER(get_apc_result)
1433 struct thread_apc *apc;
1435 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1436 0, &thread_apc_ops ))) return;
1437 if (!apc->executed) set_error( STATUS_PENDING );
1438 else
1440 reply->result = apc->result;
1441 /* close the handle directly to avoid an extra round-trip */
1442 close_handle( current->process, req->handle );
1444 release_object( apc );
1447 /* retrieve the current context of a thread */
1448 DECL_HANDLER(get_thread_context)
1450 struct thread *thread;
1451 context_t *context;
1453 if (get_reply_max_size() < sizeof(context_t))
1455 set_error( STATUS_INVALID_PARAMETER );
1456 return;
1458 if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1460 if (req->suspend)
1462 if (thread != current || !thread->suspend_context)
1464 /* not suspended, shouldn't happen */
1465 set_error( STATUS_INVALID_PARAMETER );
1467 else
1469 if (thread->context == thread->suspend_context) thread->context = NULL;
1470 set_reply_data_ptr( thread->suspend_context, sizeof(context_t) );
1471 thread->suspend_context = NULL;
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 = set_reply_data_size( sizeof(context_t) )))
1482 unsigned int flags = get_context_system_regs( thread->process->cpu );
1484 memset( context, 0, sizeof(context_t) );
1485 context->cpu = thread->process->cpu;
1486 if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1487 if (flags) get_thread_context( thread, context, flags );
1489 reply->self = (thread == current);
1490 release_object( thread );
1493 /* set the current context of a thread */
1494 DECL_HANDLER(set_thread_context)
1496 struct thread *thread;
1497 const context_t *context = get_req_data();
1499 if (get_req_data_size() < sizeof(context_t))
1501 set_error( STATUS_INVALID_PARAMETER );
1502 return;
1504 if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1506 if (req->suspend)
1508 if (thread != current || thread->context || context->cpu != thread->process->cpu)
1510 /* nested suspend or exception, shouldn't happen */
1511 set_error( STATUS_INVALID_PARAMETER );
1513 else if ((thread->suspend_context = mem_alloc( sizeof(context_t) )))
1515 memcpy( thread->suspend_context, get_req_data(), sizeof(context_t) );
1516 thread->context = thread->suspend_context;
1517 if (thread->debug_break) break_thread( thread );
1520 else if (thread != current && !thread->context)
1522 /* thread is not suspended, retry (if it's still running) */
1523 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1524 else set_error( STATUS_PENDING );
1526 else if (context->cpu == thread->process->cpu)
1528 unsigned int system_flags = get_context_system_regs(context->cpu) & context->flags;
1529 unsigned int client_flags = context->flags & ~system_flags;
1531 if (system_flags) set_thread_context( thread, context, system_flags );
1532 if (thread->context && !get_error()) copy_context( thread->context, context, client_flags );
1534 else set_error( STATUS_INVALID_PARAMETER );
1536 reply->self = (thread == current);
1537 release_object( thread );
1540 /* fetch a selector entry for a thread */
1541 DECL_HANDLER(get_selector_entry)
1543 struct thread *thread;
1544 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1546 get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1547 release_object( thread );