user32/tests: Avoid a few unneeded test failures in sysparams.c.
[wine/hacks.git] / server / thread.c
blob5520d6876c38f28f4ed8257b7bb9d845661026f3
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
39 #include "ntstatus.h"
40 #define WIN32_NO_STATUS
41 #include "windef.h"
42 #include "winternl.h"
44 #include "file.h"
45 #include "handle.h"
46 #include "process.h"
47 #include "thread.h"
48 #include "request.h"
49 #include "user.h"
50 #include "security.h"
53 #define CPU_FLAG(cpu) (1 << (cpu))
54 #ifdef __i386__
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);
64 #else
65 #error Unsupported CPU
66 #endif
68 /* thread queues */
70 struct thread_wait
72 struct thread_wait *next; /* next wait structure for this thread */
73 struct thread *thread; /* owner thread */
74 int count; /* count of objects */
75 int flags;
76 client_ptr_t cookie; /* magic cookie to return to client */
77 timeout_t timeout;
78 struct timeout_user *user;
79 struct wait_queue_entry queues[1];
82 /* asynchronous procedure calls */
84 struct thread_apc
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 */
153 NULL, /* flush */
154 NULL, /* get_fd_type */
155 NULL, /* ioctl */
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 )
166 int i;
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;
172 thread->teb = 0;
173 thread->debug_ctx = NULL;
174 thread->debug_event = NULL;
175 thread->debug_break = 0;
176 thread->queue = NULL;
177 thread->wait = NULL;
178 thread->error = 0;
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;
190 thread->suspend = 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 );
229 return NULL;
231 if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj, 0 )))
233 release_object( thread );
234 return NULL;
237 set_fd_events( thread->request_fd, POLLIN ); /* start listening to events */
238 add_process_thread( thread->process, thread );
239 return 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 )
257 int i;
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;
286 thread->desktop = 0;
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;
357 apc->caller = NULL;
358 apc->owner = owner;
359 apc->executed = 0;
360 apc->result.type = APC_NONE;
361 if (owner) grab_object( owner );
363 return apc;
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 );
373 return NULL;
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;
392 return NULL;
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;
404 return NULL;
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;
427 else
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 );
453 return old_count;
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 );
464 return old_count;
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 )
470 grab_object( obj );
471 entry->obj = obj;
472 list_add_tail( &obj->wait_queue, &entry->entry );
473 return 1;
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 );
483 /* finish waiting */
484 static void end_wait( struct thread *thread )
486 struct thread_wait *wait = thread->wait;
487 struct wait_queue_entry *entry;
488 int i;
490 assert( wait );
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 );
495 free( wait );
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;
503 unsigned int i;
505 if (!(wait = mem_alloc( FIELD_OFFSET(struct thread_wait, queues[count]) ))) return 0;
506 wait->next = current->wait;
507 wait->thread = current;
508 wait->count = count;
509 wait->flags = flags;
510 wait->user = NULL;
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 ))
520 wait->count = i;
521 end_wait( current );
522 return 0;
525 return 1;
528 /* check if the thread waiting condition is satisfied */
529 static int check_wait( struct thread *thread )
531 int i, signaled;
532 struct thread_wait *wait = thread->wait;
533 struct wait_queue_entry *entry = wait->queues;
535 assert( wait );
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)
545 int not_ok = 0;
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 */
552 signaled = 0;
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;
556 return signaled;
558 else
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 */
564 signaled = i;
565 if (entry->obj->ops->satisfied( entry->obj, thread ))
566 signaled = i + STATUS_ABANDONED_WAIT_0;
567 return signaled;
571 other_checks:
572 if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
573 if (wait->timeout <= current_time) return STATUS_TIMEOUT;
574 return -1;
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;
581 int ret;
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))
587 return 0;
588 if (ret >= 0)
589 fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
590 else if (errno == EPIPE)
591 kill_thread( thread, 0 ); /* normal death */
592 else
593 fatal_protocol_perror( thread, "write" );
594 return -1;
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 )
601 int signaled, count;
602 client_ptr_t cookie;
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 );
610 end_wait( thread );
611 if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
612 break;
614 return count;
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;
624 wait->user = NULL;
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 );
629 end_wait( thread );
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 )
638 struct object *obj;
639 int ret = 0;
641 obj = get_handle_obj( current->process, handle, 0, NULL );
642 if (obj)
644 ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
645 release_object( obj );
647 return ret;
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 )
654 int ret;
655 unsigned int i;
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 );
663 return 0;
665 for (i = 0; i < count; i++)
667 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
668 break;
671 if (i < count) goto done;
672 if (!wait_on( count, objects, flags, timeout )) goto done;
674 /* signal the object */
675 if (signal_obj)
677 if (!signal_object( signal_obj ))
679 end_wait( current );
680 goto done;
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 */
689 end_wait( current );
690 set_error( ret );
691 goto done;
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 )))
700 end_wait( current );
701 goto done;
704 current->wait->cookie = cookie;
705 set_error( STATUS_PENDING );
707 done:
708 while (i > 0) release_object( objects[--i] );
709 return timeout;
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 )
730 switch(type)
732 case APC_NONE:
733 case APC_USER:
734 case APC_TIMER:
735 return &thread->user_apc;
736 default:
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 )
751 struct list *queue;
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 ))
763 thread = candidate;
764 break;
767 if (!thread)
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 ))
774 thread = candidate;
775 break;
779 if (!thread) return 0; /* nothing found */
780 queue = get_apc_queue( thread, apc->call.type );
782 else
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 );
795 grab_object( apc );
796 list_add_tail( queue, &apc->entry );
797 if (!list_prev( queue, &apc->entry )) /* first one */
798 wake_thread( thread );
800 return 1;
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;
807 int ret = 0;
809 if ((apc = create_apc( owner, call_data )))
811 ret = queue_apc( NULL, thread, apc );
812 release_object( apc );
814 return ret;
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 );
827 apc->executed = 1;
828 wake_up( &apc->obj, 0 );
829 release_object( apc );
830 return;
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 );
841 if (ptr)
843 apc = LIST_ENTRY( ptr, struct thread_apc, entry );
844 list_remove( ptr );
846 return apc;
849 /* clear an APC queue, cancelling all the APCs on it */
850 static void clear_apc_queue( struct list *queue )
852 struct list *ptr;
854 while ((ptr = list_head( queue )))
856 struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
857 list_remove( &apc->entry );
858 apc->executed = 1;
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 )
868 int i;
870 if (server == -1) return -1;
871 if (client == -1)
873 close( server );
874 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;
883 return i;
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;
892 return i;
894 return -1;
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 )
901 int i, ret;
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;
913 return ret;
916 } while (!receive_fd( thread->process )); /* in case it is still in the socket buffer */
917 return -1;
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;
927 if (debug_level)
928 fprintf( stderr,"%04x: *killed* exit_code=%d\n",
929 thread->id, thread->exit_code );
930 if (thread->wait)
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 */
935 violent_death = 0;
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 /* trigger a breakpoint event in a given thread */
948 void break_thread( struct thread *thread )
950 debug_event_t data;
952 assert( thread->context );
954 memset( &data, 0, sizeof(data) );
955 data.exception.first = 1;
956 data.exception.exc_code = STATUS_BREAKPOINT;
957 data.exception.flags = EXCEPTION_CONTINUABLE;
958 data.exception.address = get_context_ip( thread->context );
959 generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
960 thread->debug_break = 0;
963 /* take a snapshot of currently running threads */
964 struct thread_snapshot *thread_snap( int *count )
966 struct thread_snapshot *snapshot, *ptr;
967 struct thread *thread;
968 int total = 0;
970 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
971 if (thread->state != TERMINATED) total++;
972 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
973 ptr = snapshot;
974 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
976 if (thread->state == TERMINATED) continue;
977 ptr->thread = thread;
978 ptr->count = thread->obj.refcount;
979 ptr->priority = thread->priority;
980 grab_object( thread );
981 ptr++;
983 *count = total;
984 return snapshot;
987 /* gets the current impersonation token */
988 struct token *thread_get_impersonation_token( struct thread *thread )
990 if (thread->token)
991 return thread->token;
992 else
993 return thread->process->token;
996 /* create a new thread */
997 DECL_HANDLER(new_thread)
999 struct thread *thread;
1000 int request_fd = thread_get_inflight_fd( current, req->request_fd );
1002 if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
1004 if (request_fd != -1) close( request_fd );
1005 set_error( STATUS_INVALID_HANDLE );
1006 return;
1009 if ((thread = create_thread( request_fd, current->process )))
1011 if (req->suspend) thread->suspend++;
1012 reply->tid = get_thread_id( thread );
1013 if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
1015 /* thread object will be released when the thread gets killed */
1016 return;
1018 kill_thread( thread, 1 );
1022 /* initialize a new thread */
1023 DECL_HANDLER(init_thread)
1025 struct process *process = current->process;
1026 int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
1027 int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
1029 if (current->reply_fd) /* already initialised */
1031 set_error( STATUS_INVALID_PARAMETER );
1032 goto error;
1035 if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
1037 current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj, 0 );
1038 reply_fd = -1;
1039 if (!current->reply_fd) goto error;
1041 if (wait_fd == -1)
1043 set_error( STATUS_TOO_MANY_OPENED_FILES ); /* most likely reason */
1044 return;
1046 if (!(current->wait_fd = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj, 0 )))
1047 return;
1049 if (!is_valid_address(req->teb))
1051 set_error( STATUS_INVALID_PARAMETER );
1052 return;
1055 current->unix_pid = req->unix_pid;
1056 current->unix_tid = req->unix_tid;
1057 current->teb = req->teb;
1059 if (!process->peb) /* first thread, initialize the process too */
1061 if (!CPU_FLAG(req->cpu) || !(supported_cpus & CPU_FLAG(req->cpu)))
1063 set_error( STATUS_NOT_SUPPORTED );
1064 return;
1066 process->unix_pid = current->unix_pid;
1067 process->peb = req->entry;
1068 process->cpu = req->cpu;
1069 reply->info_size = init_process( current );
1071 else
1073 if (req->cpu != process->cpu)
1075 set_error( STATUS_INVALID_PARAMETER );
1076 return;
1078 if (process->unix_pid != current->unix_pid)
1079 process->unix_pid = -1; /* can happen with linuxthreads */
1080 if (current->suspend + process->suspend > 0) stop_thread( current );
1081 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, &req->entry );
1083 debug_level = max( debug_level, req->debug_level );
1085 reply->pid = get_process_id( process );
1086 reply->tid = get_thread_id( current );
1087 reply->version = SERVER_PROTOCOL_VERSION;
1088 reply->server_start = server_start_time;
1089 reply->all_cpus = supported_cpus;
1090 return;
1092 error:
1093 if (reply_fd != -1) close( reply_fd );
1094 if (wait_fd != -1) close( wait_fd );
1097 /* terminate a thread */
1098 DECL_HANDLER(terminate_thread)
1100 struct thread *thread;
1102 reply->self = 0;
1103 reply->last = 0;
1104 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1106 thread->exit_code = req->exit_code;
1107 if (thread != current) kill_thread( thread, 1 );
1108 else
1110 reply->self = 1;
1111 reply->last = (thread->process->running_threads == 1);
1113 release_object( thread );
1117 /* open a handle to a thread */
1118 DECL_HANDLER(open_thread)
1120 struct thread *thread = get_thread_from_id( req->tid );
1122 reply->handle = 0;
1123 if (thread)
1125 reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1126 release_object( thread );
1130 /* fetch information about a thread */
1131 DECL_HANDLER(get_thread_info)
1133 struct thread *thread;
1134 obj_handle_t handle = req->handle;
1136 if (!handle) thread = get_thread_from_id( req->tid_in );
1137 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1139 if (thread)
1141 reply->pid = get_process_id( thread->process );
1142 reply->tid = get_thread_id( thread );
1143 reply->teb = thread->teb;
1144 reply->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1145 reply->priority = thread->priority;
1146 reply->affinity = thread->affinity;
1147 reply->creation_time = thread->creation_time;
1148 reply->exit_time = thread->exit_time;
1149 reply->last = thread->process->running_threads == 1;
1151 release_object( thread );
1155 /* set information about a thread */
1156 DECL_HANDLER(set_thread_info)
1158 struct thread *thread;
1160 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1162 set_thread_info( thread, req );
1163 release_object( thread );
1167 /* suspend a thread */
1168 DECL_HANDLER(suspend_thread)
1170 struct thread *thread;
1172 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1174 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1175 else reply->count = suspend_thread( thread );
1176 release_object( thread );
1180 /* resume a thread */
1181 DECL_HANDLER(resume_thread)
1183 struct thread *thread;
1185 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1187 reply->count = resume_thread( thread );
1188 release_object( thread );
1192 /* select on a handle list */
1193 DECL_HANDLER(select)
1195 struct thread_apc *apc;
1196 unsigned int count;
1197 const apc_result_t *result = get_req_data();
1198 const obj_handle_t *handles = (const obj_handle_t *)(result + 1);
1200 if (get_req_data_size() < sizeof(*result))
1202 set_error( STATUS_INVALID_PARAMETER );
1203 return;
1205 count = (get_req_data_size() - sizeof(*result)) / sizeof(obj_handle_t);
1207 /* first store results of previous apc */
1208 if (req->prev_apc)
1210 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev_apc,
1211 0, &thread_apc_ops ))) return;
1212 apc->result = *result;
1213 apc->executed = 1;
1214 if (apc->result.type == APC_CREATE_THREAD) /* transfer the handle to the caller process */
1216 obj_handle_t handle = duplicate_handle( current->process, apc->result.create_thread.handle,
1217 apc->caller->process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1218 close_handle( current->process, apc->result.create_thread.handle );
1219 apc->result.create_thread.handle = handle;
1220 clear_error(); /* ignore errors from the above calls */
1222 else if (apc->result.type == APC_ASYNC_IO)
1224 if (apc->owner)
1225 async_set_result( apc->owner, apc->result.async_io.status,
1226 apc->result.async_io.total, apc->result.async_io.apc );
1228 wake_up( &apc->obj, 0 );
1229 close_handle( current->process, req->prev_apc );
1230 release_object( apc );
1233 reply->timeout = select_on( count, req->cookie, handles, req->flags, req->timeout, req->signal );
1235 if (get_error() == STATUS_USER_APC)
1237 for (;;)
1239 if (!(apc = thread_dequeue_apc( current, !(req->flags & SELECT_ALERTABLE) )))
1240 break;
1241 /* Optimization: ignore APC_NONE calls, they are only used to
1242 * wake up a thread, but since we got here the thread woke up already.
1244 if (apc->call.type != APC_NONE)
1246 if ((reply->apc_handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1247 reply->call = apc->call;
1248 release_object( apc );
1249 break;
1251 apc->executed = 1;
1252 wake_up( &apc->obj, 0 );
1253 release_object( apc );
1258 /* queue an APC for a thread or process */
1259 DECL_HANDLER(queue_apc)
1261 struct thread *thread = NULL;
1262 struct process *process = NULL;
1263 struct thread_apc *apc;
1265 if (!(apc = create_apc( NULL, &req->call ))) return;
1267 switch (apc->call.type)
1269 case APC_NONE:
1270 case APC_USER:
1271 thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT );
1272 break;
1273 case APC_VIRTUAL_ALLOC:
1274 case APC_VIRTUAL_FREE:
1275 case APC_VIRTUAL_PROTECT:
1276 case APC_VIRTUAL_FLUSH:
1277 case APC_VIRTUAL_LOCK:
1278 case APC_VIRTUAL_UNLOCK:
1279 case APC_UNMAP_VIEW:
1280 process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1281 break;
1282 case APC_VIRTUAL_QUERY:
1283 process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION );
1284 break;
1285 case APC_MAP_VIEW:
1286 process = get_process_from_handle( req->handle, PROCESS_VM_OPERATION );
1287 if (process && process != current->process)
1289 /* duplicate the handle into the target process */
1290 obj_handle_t handle = duplicate_handle( current->process, apc->call.map_view.handle,
1291 process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1292 if (handle) apc->call.map_view.handle = handle;
1293 else
1295 release_object( process );
1296 process = NULL;
1299 break;
1300 case APC_CREATE_THREAD:
1301 process = get_process_from_handle( req->handle, PROCESS_CREATE_THREAD );
1302 break;
1303 default:
1304 set_error( STATUS_INVALID_PARAMETER );
1305 break;
1308 if (thread)
1310 if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1311 release_object( thread );
1313 else if (process)
1315 reply->self = (process == current->process);
1316 if (!reply->self)
1318 obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1319 if (handle)
1321 if (queue_apc( process, NULL, apc ))
1323 apc->caller = (struct thread *)grab_object( current );
1324 reply->handle = handle;
1326 else
1328 close_handle( current->process, handle );
1329 set_error( STATUS_PROCESS_IS_TERMINATING );
1333 release_object( process );
1336 release_object( apc );
1339 /* Get the result of an APC call */
1340 DECL_HANDLER(get_apc_result)
1342 struct thread_apc *apc;
1344 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1345 0, &thread_apc_ops ))) return;
1346 if (!apc->executed) set_error( STATUS_PENDING );
1347 else
1349 reply->result = apc->result;
1350 /* close the handle directly to avoid an extra round-trip */
1351 close_handle( current->process, req->handle );
1353 release_object( apc );
1356 /* retrieve the current context of a thread */
1357 DECL_HANDLER(get_thread_context)
1359 struct thread *thread;
1360 CONTEXT *context;
1362 if (get_reply_max_size() < sizeof(CONTEXT))
1364 set_error( STATUS_INVALID_PARAMETER );
1365 return;
1367 if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1369 if (req->suspend)
1371 if (thread != current || !thread->suspend_context)
1373 /* not suspended, shouldn't happen */
1374 set_error( STATUS_INVALID_PARAMETER );
1376 else
1378 if (thread->context == thread->suspend_context) thread->context = NULL;
1379 set_reply_data_ptr( thread->suspend_context, sizeof(CONTEXT) );
1380 thread->suspend_context = NULL;
1383 else if (thread != current && !thread->context)
1385 /* thread is not suspended, retry (if it's still running) */
1386 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1387 else set_error( STATUS_PENDING );
1389 else if ((context = set_reply_data_size( sizeof(CONTEXT) )))
1391 unsigned int flags = get_context_system_regs( req->flags );
1393 memset( context, 0, sizeof(CONTEXT) );
1394 context->ContextFlags = get_context_cpu_flag();
1395 if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1396 if (flags) get_thread_context( thread, context, flags );
1398 reply->self = (thread == current);
1399 release_object( thread );
1402 /* set the current context of a thread */
1403 DECL_HANDLER(set_thread_context)
1405 struct thread *thread;
1407 if (get_req_data_size() < sizeof(CONTEXT))
1409 set_error( STATUS_INVALID_PARAMETER );
1410 return;
1412 if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1414 if (req->suspend)
1416 if (thread != current || thread->context)
1418 /* nested suspend or exception, shouldn't happen */
1419 set_error( STATUS_INVALID_PARAMETER );
1421 else if ((thread->suspend_context = mem_alloc( sizeof(CONTEXT) )))
1423 memcpy( thread->suspend_context, get_req_data(), sizeof(CONTEXT) );
1424 thread->context = thread->suspend_context;
1425 if (thread->debug_break) break_thread( thread );
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
1436 const CONTEXT *context = get_req_data();
1437 unsigned int flags = get_context_system_regs( req->flags );
1439 if (flags) set_thread_context( thread, context, flags );
1440 if (thread->context && !get_error())
1441 copy_context( thread->context, context, req->flags & ~flags );
1443 reply->self = (thread == current);
1444 release_object( thread );
1447 /* fetch a selector entry for a thread */
1448 DECL_HANDLER(get_selector_entry)
1450 struct thread *thread;
1451 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1453 get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1454 release_object( thread );