user32/tests: Don't run unicode tests if not supported.
[wine/hacks.git] / server / thread.c
blobec1b16170fc9339b6cfe831c9ab5b81cbf03b244
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 /* thread queues */
55 struct thread_wait
57 struct thread_wait *next; /* next wait structure for this thread */
58 struct thread *thread; /* owner thread */
59 int count; /* count of objects */
60 int flags;
61 void *cookie; /* magic cookie to return to client */
62 struct timeval timeout;
63 struct timeout_user *user;
64 struct wait_queue_entry queues[1];
67 /* asynchronous procedure calls */
69 struct thread_apc
71 struct object obj; /* object header */
72 struct list entry; /* queue linked list */
73 struct thread *caller; /* thread that queued this apc */
74 struct object *owner; /* object that queued this apc */
75 int executed; /* has it been executed by the client? */
76 apc_call_t call; /* call arguments */
77 apc_result_t result; /* call results once executed */
80 static void dump_thread_apc( struct object *obj, int verbose );
81 static int thread_apc_signaled( struct object *obj, struct thread *thread );
82 static void thread_apc_destroy( struct object *obj );
83 static void clear_apc_queue( struct list *queue );
85 static const struct object_ops thread_apc_ops =
87 sizeof(struct thread_apc), /* size */
88 dump_thread_apc, /* dump */
89 add_queue, /* add_queue */
90 remove_queue, /* remove_queue */
91 thread_apc_signaled, /* signaled */
92 no_satisfied, /* satisfied */
93 no_signal, /* signal */
94 no_get_fd, /* get_fd */
95 no_map_access, /* map_access */
96 no_lookup_name, /* lookup_name */
97 no_open_file, /* open_file */
98 no_close_handle, /* close_handle */
99 thread_apc_destroy /* destroy */
103 /* thread operations */
105 static void dump_thread( struct object *obj, int verbose );
106 static int thread_signaled( struct object *obj, struct thread *thread );
107 static unsigned int thread_map_access( struct object *obj, unsigned int access );
108 static void thread_poll_event( struct fd *fd, int event );
109 static void destroy_thread( struct object *obj );
111 static const struct object_ops thread_ops =
113 sizeof(struct thread), /* size */
114 dump_thread, /* dump */
115 add_queue, /* add_queue */
116 remove_queue, /* remove_queue */
117 thread_signaled, /* signaled */
118 no_satisfied, /* satisfied */
119 no_signal, /* signal */
120 no_get_fd, /* get_fd */
121 thread_map_access, /* map_access */
122 no_lookup_name, /* lookup_name */
123 no_open_file, /* open_file */
124 no_close_handle, /* close_handle */
125 destroy_thread /* destroy */
128 static const struct fd_ops thread_fd_ops =
130 NULL, /* get_poll_events */
131 thread_poll_event, /* poll_event */
132 no_flush, /* flush */
133 no_get_file_info, /* get_file_info */
134 no_queue_async, /* queue_async */
135 no_cancel_async /* cancel_async */
138 static struct list thread_list = LIST_INIT(thread_list);
140 /* initialize the structure for a newly allocated thread */
141 static inline void init_thread_structure( struct thread *thread )
143 int i;
145 thread->unix_pid = -1; /* not known yet */
146 thread->unix_tid = -1; /* not known yet */
147 thread->context = NULL;
148 thread->suspend_context = NULL;
149 thread->teb = NULL;
150 thread->debug_ctx = NULL;
151 thread->debug_event = NULL;
152 thread->debug_break = 0;
153 thread->queue = NULL;
154 thread->wait = NULL;
155 thread->error = 0;
156 thread->req_data = NULL;
157 thread->req_toread = 0;
158 thread->reply_data = NULL;
159 thread->reply_towrite = 0;
160 thread->request_fd = NULL;
161 thread->reply_fd = NULL;
162 thread->wait_fd = NULL;
163 thread->state = RUNNING;
164 thread->exit_code = 0;
165 thread->priority = 0;
166 thread->affinity = 1;
167 thread->suspend = 0;
168 thread->desktop_users = 0;
169 thread->token = NULL;
171 thread->creation_time = current_time;
172 thread->exit_time.tv_sec = thread->exit_time.tv_usec = 0;
174 list_init( &thread->mutex_list );
175 list_init( &thread->system_apc );
176 list_init( &thread->user_apc );
178 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
179 thread->inflight[i].server = thread->inflight[i].client = -1;
182 /* check if address looks valid for a client-side data structure (TEB etc.) */
183 static inline int is_valid_address( void *addr )
185 return addr && !((unsigned long)addr % sizeof(int));
188 /* create a new thread */
189 struct thread *create_thread( int fd, struct process *process )
191 struct thread *thread;
193 if (!(thread = alloc_object( &thread_ops ))) return NULL;
195 init_thread_structure( thread );
197 thread->process = (struct process *)grab_object( process );
198 thread->desktop = process->desktop;
199 if (!current) current = thread;
201 list_add_head( &thread_list, &thread->entry );
203 if (!(thread->id = alloc_ptid( thread )))
205 release_object( thread );
206 return NULL;
208 if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj )))
210 release_object( thread );
211 return NULL;
214 set_fd_events( thread->request_fd, POLLIN ); /* start listening to events */
215 add_process_thread( thread->process, thread );
216 return thread;
219 /* handle a client event */
220 static void thread_poll_event( struct fd *fd, int event )
222 struct thread *thread = get_fd_user( fd );
223 assert( thread->obj.ops == &thread_ops );
225 if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
226 else if (event & POLLIN) read_request( thread );
227 else if (event & POLLOUT) write_reply( thread );
230 /* cleanup everything that is no longer needed by a dead thread */
231 /* used by destroy_thread and kill_thread */
232 static void cleanup_thread( struct thread *thread )
234 int i;
236 clear_apc_queue( &thread->system_apc );
237 clear_apc_queue( &thread->user_apc );
238 free( thread->req_data );
239 free( thread->reply_data );
240 if (thread->request_fd) release_object( thread->request_fd );
241 if (thread->reply_fd) release_object( thread->reply_fd );
242 if (thread->wait_fd) release_object( thread->wait_fd );
243 free( thread->suspend_context );
244 free_msg_queue( thread );
245 cleanup_clipboard_thread(thread);
246 destroy_thread_windows( thread );
247 close_thread_desktop( thread );
248 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
250 if (thread->inflight[i].client != -1)
252 close( thread->inflight[i].server );
253 thread->inflight[i].client = thread->inflight[i].server = -1;
256 thread->req_data = NULL;
257 thread->reply_data = NULL;
258 thread->request_fd = NULL;
259 thread->reply_fd = NULL;
260 thread->wait_fd = NULL;
261 thread->context = NULL;
262 thread->suspend_context = NULL;
263 thread->desktop = 0;
266 /* destroy a thread when its refcount is 0 */
267 static void destroy_thread( struct object *obj )
269 struct thread *thread = (struct thread *)obj;
270 assert( obj->ops == &thread_ops );
272 assert( !thread->debug_ctx ); /* cannot still be debugging something */
273 list_remove( &thread->entry );
274 cleanup_thread( thread );
275 release_object( thread->process );
276 if (thread->id) free_ptid( thread->id );
277 if (thread->token) release_object( thread->token );
280 /* dump a thread on stdout for debugging purposes */
281 static void dump_thread( struct object *obj, int verbose )
283 struct thread *thread = (struct thread *)obj;
284 assert( obj->ops == &thread_ops );
286 fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d teb=%p state=%d\n",
287 thread->id, thread->unix_pid, thread->unix_tid, thread->teb, thread->state );
290 static int thread_signaled( struct object *obj, struct thread *thread )
292 struct thread *mythread = (struct thread *)obj;
293 return (mythread->state == TERMINATED);
296 static unsigned int thread_map_access( struct object *obj, unsigned int access )
298 if (access & GENERIC_READ) access |= STANDARD_RIGHTS_READ | SYNCHRONIZE;
299 if (access & GENERIC_WRITE) access |= STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
300 if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
301 if (access & GENERIC_ALL) access |= THREAD_ALL_ACCESS;
302 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
305 static void dump_thread_apc( struct object *obj, int verbose )
307 struct thread_apc *apc = (struct thread_apc *)obj;
308 assert( obj->ops == &thread_apc_ops );
310 fprintf( stderr, "APC owner=%p type=%u\n", apc->owner, apc->call.type );
313 static int thread_apc_signaled( struct object *obj, struct thread *thread )
315 struct thread_apc *apc = (struct thread_apc *)obj;
316 return apc->executed;
319 static void thread_apc_destroy( struct object *obj )
321 struct thread_apc *apc = (struct thread_apc *)obj;
322 if (apc->caller) release_object( apc->caller );
323 if (apc->owner) release_object( apc->owner );
326 /* queue an async procedure call */
327 static struct thread_apc *create_apc( struct object *owner, const apc_call_t *call_data )
329 struct thread_apc *apc;
331 if ((apc = alloc_object( &thread_apc_ops )))
333 apc->call = *call_data;
334 apc->caller = NULL;
335 apc->owner = owner;
336 apc->executed = 0;
337 apc->result.type = APC_NONE;
338 if (owner) grab_object( owner );
340 return apc;
343 /* get a thread pointer from a thread id (and increment the refcount) */
344 struct thread *get_thread_from_id( thread_id_t id )
346 struct object *obj = get_ptid_entry( id );
348 if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
349 set_error( STATUS_INVALID_CID );
350 return NULL;
353 /* get a thread from a handle (and increment the refcount) */
354 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
356 return (struct thread *)get_handle_obj( current->process, handle,
357 access, &thread_ops );
360 /* find a thread from a Unix tid */
361 struct thread *get_thread_from_tid( int tid )
363 struct thread *thread;
365 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
367 if (thread->unix_tid == tid) return thread;
369 return NULL;
372 /* find a thread from a Unix pid */
373 struct thread *get_thread_from_pid( int pid )
375 struct thread *thread;
377 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
379 if (thread->unix_pid == pid) return thread;
381 return NULL;
384 /* set all information about a thread */
385 static void set_thread_info( struct thread *thread,
386 const struct set_thread_info_request *req )
388 if (req->mask & SET_THREAD_INFO_PRIORITY)
389 thread->priority = req->priority;
390 if (req->mask & SET_THREAD_INFO_AFFINITY)
392 if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
393 else thread->affinity = req->affinity;
395 if (req->mask & SET_THREAD_INFO_TOKEN)
396 security_set_thread_token( thread, req->token );
399 /* stop a thread (at the Unix level) */
400 void stop_thread( struct thread *thread )
402 if (thread->context) return; /* already inside a debug event, no need for a signal */
403 /* can't stop a thread while initialisation is in progress */
404 if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
407 /* suspend a thread */
408 static int suspend_thread( struct thread *thread )
410 int old_count = thread->suspend;
411 if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
413 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
415 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
416 return old_count;
419 /* resume a thread */
420 static int resume_thread( struct thread *thread )
422 int old_count = thread->suspend;
423 if (thread->suspend > 0)
425 if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
427 return old_count;
430 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
431 int add_queue( struct object *obj, struct wait_queue_entry *entry )
433 grab_object( obj );
434 entry->obj = obj;
435 list_add_tail( &obj->wait_queue, &entry->entry );
436 return 1;
439 /* remove a thread from an object wait queue */
440 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
442 list_remove( &entry->entry );
443 release_object( obj );
446 /* finish waiting */
447 static void end_wait( struct thread *thread )
449 struct thread_wait *wait = thread->wait;
450 struct wait_queue_entry *entry;
451 int i;
453 assert( wait );
454 thread->wait = wait->next;
455 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
456 entry->obj->ops->remove_queue( entry->obj, entry );
457 if (wait->user) remove_timeout_user( wait->user );
458 free( wait );
461 /* build the thread wait structure */
462 static int wait_on( int count, struct object *objects[], int flags, const abs_time_t *timeout )
464 struct thread_wait *wait;
465 struct wait_queue_entry *entry;
466 int i;
468 if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
469 wait->next = current->wait;
470 wait->thread = current;
471 wait->count = count;
472 wait->flags = flags;
473 wait->user = NULL;
474 current->wait = wait;
475 if (flags & SELECT_TIMEOUT)
477 wait->timeout.tv_sec = timeout->sec;
478 wait->timeout.tv_usec = timeout->usec;
481 for (i = 0, entry = wait->queues; i < count; i++, entry++)
483 struct object *obj = objects[i];
484 entry->thread = current;
485 if (!obj->ops->add_queue( obj, entry ))
487 wait->count = i;
488 end_wait( current );
489 return 0;
492 return 1;
495 /* check if the thread waiting condition is satisfied */
496 static int check_wait( struct thread *thread )
498 int i, signaled;
499 struct thread_wait *wait = thread->wait;
500 struct wait_queue_entry *entry = wait->queues;
502 /* Suspended threads may not acquire locks, but they can run system APCs */
503 if (thread->process->suspend + thread->suspend > 0)
505 if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
506 return STATUS_USER_APC;
507 return -1;
510 assert( wait );
511 if (wait->flags & SELECT_ALL)
513 int not_ok = 0;
514 /* Note: we must check them all anyway, as some objects may
515 * want to do something when signaled, even if others are not */
516 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
517 not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
518 if (not_ok) goto other_checks;
519 /* Wait satisfied: tell it to all objects */
520 signaled = 0;
521 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
522 if (entry->obj->ops->satisfied( entry->obj, thread ))
523 signaled = STATUS_ABANDONED_WAIT_0;
524 return signaled;
526 else
528 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
530 if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
531 /* Wait satisfied: tell it to the object */
532 signaled = i;
533 if (entry->obj->ops->satisfied( entry->obj, thread ))
534 signaled = i + STATUS_ABANDONED_WAIT_0;
535 return signaled;
539 other_checks:
540 if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty(&thread->system_apc)) return STATUS_USER_APC;
541 if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
542 if (wait->flags & SELECT_TIMEOUT)
544 if (!time_before( &current_time, &wait->timeout )) return STATUS_TIMEOUT;
546 return -1;
549 /* send the wakeup signal to a thread */
550 static int send_thread_wakeup( struct thread *thread, void *cookie, int signaled )
552 struct wake_up_reply reply;
553 int ret;
555 reply.cookie = cookie;
556 reply.signaled = signaled;
557 if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
558 return 0;
559 if (ret >= 0)
560 fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
561 else if (errno == EPIPE)
562 kill_thread( thread, 0 ); /* normal death */
563 else
564 fatal_protocol_perror( thread, "write" );
565 return -1;
568 /* attempt to wake up a thread */
569 /* return >0 if OK, 0 if the wait condition is still not satisfied */
570 int wake_thread( struct thread *thread )
572 int signaled, count;
573 void *cookie;
575 for (count = 0; thread->wait; count++)
577 if ((signaled = check_wait( thread )) == -1) break;
579 cookie = thread->wait->cookie;
580 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
581 thread->id, signaled, cookie );
582 end_wait( thread );
583 if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
584 break;
586 return count;
589 /* thread wait timeout */
590 static void thread_timeout( void *ptr )
592 struct thread_wait *wait = ptr;
593 struct thread *thread = wait->thread;
594 void *cookie = wait->cookie;
596 wait->user = NULL;
597 if (thread->wait != wait) return; /* not the top-level wait, ignore it */
598 if (thread->suspend + thread->process->suspend > 0) return; /* suspended, ignore it */
600 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
601 thread->id, (int)STATUS_TIMEOUT, cookie );
602 end_wait( thread );
603 if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
604 /* check if other objects have become signaled in the meantime */
605 wake_thread( thread );
608 /* try signaling an event flag, a semaphore or a mutex */
609 static int signal_object( obj_handle_t handle )
611 struct object *obj;
612 int ret = 0;
614 obj = get_handle_obj( current->process, handle, 0, NULL );
615 if (obj)
617 ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
618 release_object( obj );
620 return ret;
623 /* select on a list of handles */
624 static void select_on( int count, void *cookie, const obj_handle_t *handles,
625 int flags, const abs_time_t *timeout, obj_handle_t signal_obj )
627 int ret, i;
628 struct object *objects[MAXIMUM_WAIT_OBJECTS];
630 if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
632 set_error( STATUS_INVALID_PARAMETER );
633 return;
635 for (i = 0; i < count; i++)
637 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
638 break;
641 if (i < count) goto done;
642 if (!wait_on( count, objects, flags, timeout )) goto done;
644 /* signal the object */
645 if (signal_obj)
647 if (!signal_object( signal_obj ))
649 end_wait( current );
650 goto done;
652 /* check if we woke ourselves up */
653 if (!current->wait) goto done;
656 if ((ret = check_wait( current )) != -1)
658 /* condition is already satisfied */
659 end_wait( current );
660 set_error( ret );
661 goto done;
664 /* now we need to wait */
665 if (flags & SELECT_TIMEOUT)
667 if (!(current->wait->user = add_timeout_user( &current->wait->timeout,
668 thread_timeout, current->wait )))
670 end_wait( current );
671 goto done;
674 current->wait->cookie = cookie;
675 set_error( STATUS_PENDING );
677 done:
678 while (--i >= 0) release_object( objects[i] );
681 /* attempt to wake threads sleeping on the object wait queue */
682 void wake_up( struct object *obj, int max )
684 struct list *ptr, *next;
686 LIST_FOR_EACH_SAFE( ptr, next, &obj->wait_queue )
688 struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
689 if (wake_thread( entry->thread ))
691 if (max && !--max) break;
696 /* return the apc queue to use for a given apc type */
697 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
699 switch(type)
701 case APC_NONE:
702 case APC_USER:
703 case APC_TIMER:
704 return &thread->user_apc;
705 default:
706 return &thread->system_apc;
710 /* queue an existing APC to a given thread */
711 static int queue_apc( struct process *process, struct thread *thread, struct thread_apc *apc )
713 struct list *queue;
715 if (!thread) /* find a suitable thread inside the process */
717 struct thread *candidate;
719 /* first try to find a waiting thread */
720 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
722 if (candidate->state == TERMINATED) continue;
723 if (process->suspend || candidate->suspend ||
724 (candidate->wait && (candidate->wait->flags & SELECT_INTERRUPTIBLE)))
726 thread = candidate;
727 break;
730 if (!thread)
732 /* then use the first one that accepts a signal */
733 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
735 if (send_thread_signal( candidate, SIGUSR1 ))
737 thread = candidate;
738 break;
742 if (!thread) return 0; /* nothing found */
744 else
746 if (thread->state == TERMINATED) return 0;
747 /* cancel a possible previous APC with the same owner */
748 if (apc->owner) thread_cancel_apc( thread, apc->owner, apc->call.type );
751 queue = get_apc_queue( thread, apc->call.type );
752 grab_object( apc );
753 list_add_tail( queue, &apc->entry );
754 if (!list_prev( queue, &apc->entry )) /* first one */
755 wake_thread( thread );
757 return 1;
760 /* queue an async procedure call */
761 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
763 struct thread_apc *apc;
764 int ret = 0;
766 if ((apc = create_apc( owner, call_data )))
768 ret = queue_apc( NULL, thread, apc );
769 release_object( apc );
771 return ret;
774 /* cancel the async procedure call owned by a specific object */
775 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
777 struct thread_apc *apc;
778 struct list *queue = get_apc_queue( thread, type );
780 LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
782 if (apc->owner != owner) continue;
783 list_remove( &apc->entry );
784 apc->executed = 1;
785 wake_up( &apc->obj, 0 );
786 release_object( apc );
787 return;
791 /* remove the head apc from the queue; the returned object must be released by the caller */
792 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
794 struct thread_apc *apc = NULL;
795 struct list *ptr = list_head( &thread->system_apc );
797 if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
798 if (ptr)
800 apc = LIST_ENTRY( ptr, struct thread_apc, entry );
801 list_remove( ptr );
803 return apc;
806 /* clear an APC queue, cancelling all the APCs on it */
807 static void clear_apc_queue( struct list *queue )
809 struct list *ptr;
811 while ((ptr = list_head( queue )))
813 struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
814 list_remove( &apc->entry );
815 apc->executed = 1;
816 wake_up( &apc->obj, 0 );
817 release_object( apc );
821 /* add an fd to the inflight list */
822 /* return list index, or -1 on error */
823 int thread_add_inflight_fd( struct thread *thread, int client, int server )
825 int i;
827 if (server == -1) return -1;
828 if (client == -1)
830 close( server );
831 return -1;
834 /* first check if we already have an entry for this fd */
835 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
836 if (thread->inflight[i].client == client)
838 close( thread->inflight[i].server );
839 thread->inflight[i].server = server;
840 return i;
843 /* now find a free spot to store it */
844 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
845 if (thread->inflight[i].client == -1)
847 thread->inflight[i].client = client;
848 thread->inflight[i].server = server;
849 return i;
851 return -1;
854 /* get an inflight fd and purge it from the list */
855 /* the fd must be closed when no longer used */
856 int thread_get_inflight_fd( struct thread *thread, int client )
858 int i, ret;
860 if (client == -1) return -1;
864 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
866 if (thread->inflight[i].client == client)
868 ret = thread->inflight[i].server;
869 thread->inflight[i].server = thread->inflight[i].client = -1;
870 return ret;
873 } while (!receive_fd( thread->process )); /* in case it is still in the socket buffer */
874 return -1;
877 /* kill a thread on the spot */
878 void kill_thread( struct thread *thread, int violent_death )
880 if (thread->state == TERMINATED) return; /* already killed */
881 thread->state = TERMINATED;
882 thread->exit_time = current_time;
883 if (current == thread) current = NULL;
884 if (debug_level)
885 fprintf( stderr,"%04x: *killed* exit_code=%d\n",
886 thread->id, thread->exit_code );
887 if (thread->wait)
889 while (thread->wait) end_wait( thread );
890 send_thread_wakeup( thread, NULL, STATUS_PENDING );
891 /* if it is waiting on the socket, we don't need to send a SIGTERM */
892 violent_death = 0;
894 kill_console_processes( thread, 0 );
895 debug_exit_thread( thread );
896 abandon_mutexes( thread );
897 wake_up( &thread->obj, 0 );
898 if (violent_death) send_thread_signal( thread, SIGTERM );
899 cleanup_thread( thread );
900 remove_process_thread( thread->process, thread );
901 release_object( thread );
904 /* trigger a breakpoint event in a given thread */
905 void break_thread( struct thread *thread )
907 struct debug_event_exception data;
909 assert( thread->context );
911 data.record.ExceptionCode = STATUS_BREAKPOINT;
912 data.record.ExceptionFlags = EXCEPTION_CONTINUABLE;
913 data.record.ExceptionRecord = NULL;
914 data.record.ExceptionAddress = get_context_ip( thread->context );
915 data.record.NumberParameters = 0;
916 data.first = 1;
917 generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
918 thread->debug_break = 0;
921 /* take a snapshot of currently running threads */
922 struct thread_snapshot *thread_snap( int *count )
924 struct thread_snapshot *snapshot, *ptr;
925 struct thread *thread;
926 int total = 0;
928 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
929 if (thread->state != TERMINATED) total++;
930 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
931 ptr = snapshot;
932 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
934 if (thread->state == TERMINATED) continue;
935 ptr->thread = thread;
936 ptr->count = thread->obj.refcount;
937 ptr->priority = thread->priority;
938 grab_object( thread );
939 ptr++;
941 *count = total;
942 return snapshot;
945 /* gets the current impersonation token */
946 struct token *thread_get_impersonation_token( struct thread *thread )
948 if (thread->token)
949 return thread->token;
950 else
951 return thread->process->token;
954 /* create a new thread */
955 DECL_HANDLER(new_thread)
957 struct thread *thread;
958 int request_fd = thread_get_inflight_fd( current, req->request_fd );
960 if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
962 if (request_fd != -1) close( request_fd );
963 set_error( STATUS_INVALID_HANDLE );
964 return;
967 if ((thread = create_thread( request_fd, current->process )))
969 if (req->suspend) thread->suspend++;
970 reply->tid = get_thread_id( thread );
971 if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
973 /* thread object will be released when the thread gets killed */
974 return;
976 kill_thread( thread, 1 );
980 /* initialize a new thread */
981 DECL_HANDLER(init_thread)
983 struct process *process = current->process;
984 int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
985 int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
987 if (current->reply_fd) /* already initialised */
989 set_error( STATUS_INVALID_PARAMETER );
990 goto error;
993 if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
995 current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj );
996 reply_fd = -1;
997 if (!current->reply_fd) goto error;
999 if (wait_fd == -1)
1001 set_error( STATUS_TOO_MANY_OPENED_FILES ); /* most likely reason */
1002 return;
1004 if (!(current->wait_fd = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj )))
1005 return;
1007 if (!is_valid_address(req->teb) || !is_valid_address(req->peb) || !is_valid_address(req->ldt_copy))
1009 set_error( STATUS_INVALID_PARAMETER );
1010 return;
1013 current->unix_pid = req->unix_pid;
1014 current->unix_tid = req->unix_tid;
1015 current->teb = req->teb;
1017 if (!process->peb) /* first thread, initialize the process too */
1019 process->unix_pid = current->unix_pid;
1020 process->peb = req->peb;
1021 process->ldt_copy = req->ldt_copy;
1022 reply->info_size = init_process( current );
1024 else
1026 if (process->unix_pid != current->unix_pid)
1027 process->unix_pid = -1; /* can happen with linuxthreads */
1028 if (current->suspend + process->suspend > 0) stop_thread( current );
1029 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
1031 debug_level = max( debug_level, req->debug_level );
1033 reply->pid = get_process_id( process );
1034 reply->tid = get_thread_id( current );
1035 reply->version = SERVER_PROTOCOL_VERSION;
1036 reply->server_start.sec = server_start_time.tv_sec;
1037 reply->server_start.usec = server_start_time.tv_usec;
1038 return;
1040 error:
1041 if (reply_fd != -1) close( reply_fd );
1042 if (wait_fd != -1) close( wait_fd );
1045 /* terminate a thread */
1046 DECL_HANDLER(terminate_thread)
1048 struct thread *thread;
1050 reply->self = 0;
1051 reply->last = 0;
1052 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1054 thread->exit_code = req->exit_code;
1055 if (thread != current) kill_thread( thread, 1 );
1056 else
1058 reply->self = 1;
1059 reply->last = (thread->process->running_threads == 1);
1061 release_object( thread );
1065 /* open a handle to a thread */
1066 DECL_HANDLER(open_thread)
1068 struct thread *thread = get_thread_from_id( req->tid );
1070 reply->handle = 0;
1071 if (thread)
1073 reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1074 release_object( thread );
1078 /* fetch information about a thread */
1079 DECL_HANDLER(get_thread_info)
1081 struct thread *thread;
1082 obj_handle_t handle = req->handle;
1084 if (!handle) thread = get_thread_from_id( req->tid_in );
1085 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1087 if (thread)
1089 reply->pid = get_process_id( thread->process );
1090 reply->tid = get_thread_id( thread );
1091 reply->teb = thread->teb;
1092 reply->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1093 reply->priority = thread->priority;
1094 reply->affinity = thread->affinity;
1095 reply->creation_time.sec = thread->creation_time.tv_sec;
1096 reply->creation_time.usec = thread->creation_time.tv_usec;
1097 reply->exit_time.sec = thread->exit_time.tv_sec;
1098 reply->exit_time.usec = thread->exit_time.tv_usec;
1099 reply->last = thread->process->running_threads == 1;
1101 release_object( thread );
1105 /* set information about a thread */
1106 DECL_HANDLER(set_thread_info)
1108 struct thread *thread;
1110 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1112 set_thread_info( thread, req );
1113 release_object( thread );
1117 /* suspend a thread */
1118 DECL_HANDLER(suspend_thread)
1120 struct thread *thread;
1122 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1124 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1125 else reply->count = suspend_thread( thread );
1126 release_object( thread );
1130 /* resume a thread */
1131 DECL_HANDLER(resume_thread)
1133 struct thread *thread;
1135 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1137 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1138 else reply->count = resume_thread( thread );
1139 release_object( thread );
1143 /* select on a handle list */
1144 DECL_HANDLER(select)
1146 int count = get_req_data_size() / sizeof(obj_handle_t);
1147 select_on( count, req->cookie, get_req_data(), req->flags, &req->timeout, req->signal );
1150 /* queue an APC for a thread or process */
1151 DECL_HANDLER(queue_apc)
1153 struct thread *thread = NULL;
1154 struct process *process = NULL;
1155 struct thread_apc *apc;
1157 if (!(apc = create_apc( NULL, &req->call ))) return;
1159 switch (apc->call.type)
1161 case APC_NONE:
1162 case APC_USER:
1163 thread = get_thread_from_handle( req->thread, THREAD_SET_CONTEXT );
1164 break;
1165 case APC_VIRTUAL_ALLOC:
1166 case APC_VIRTUAL_FREE:
1167 case APC_VIRTUAL_PROTECT:
1168 case APC_VIRTUAL_FLUSH:
1169 case APC_VIRTUAL_LOCK:
1170 case APC_VIRTUAL_UNLOCK:
1171 case APC_UNMAP_VIEW:
1172 process = get_process_from_handle( req->process, PROCESS_VM_OPERATION );
1173 break;
1174 case APC_VIRTUAL_QUERY:
1175 process = get_process_from_handle( req->process, PROCESS_QUERY_INFORMATION );
1176 break;
1177 case APC_MAP_VIEW:
1178 process = get_process_from_handle( req->process, PROCESS_VM_OPERATION );
1179 if (process && process != current->process)
1181 /* duplicate the handle into the target process */
1182 obj_handle_t handle = duplicate_handle( current->process, apc->call.map_view.handle,
1183 process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1184 if (handle) apc->call.map_view.handle = handle;
1185 else
1187 release_object( process );
1188 process = NULL;
1191 break;
1192 case APC_CREATE_THREAD:
1193 process = get_process_from_handle( req->process, PROCESS_CREATE_THREAD );
1194 break;
1195 default:
1196 set_error( STATUS_INVALID_PARAMETER );
1197 break;
1200 if (thread)
1202 if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1203 release_object( thread );
1205 else if (process)
1207 reply->self = (process == current->process);
1208 if (!reply->self)
1210 obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1211 if (handle)
1213 if (queue_apc( process, NULL, apc ))
1215 apc->caller = (struct thread *)grab_object( current );
1216 reply->handle = handle;
1218 else
1220 close_handle( current->process, handle );
1221 set_error( STATUS_PROCESS_IS_TERMINATING );
1225 release_object( process );
1228 release_object( apc );
1231 /* get next APC to call */
1232 DECL_HANDLER(get_apc)
1234 struct thread_apc *apc;
1235 int system_only = !req->alertable;
1237 if (req->prev)
1239 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev,
1240 0, &thread_apc_ops ))) return;
1241 apc->result = req->result;
1242 apc->executed = 1;
1243 if (apc->result.type == APC_CREATE_THREAD) /* transfer the handle to the caller process */
1245 obj_handle_t handle = duplicate_handle( current->process, apc->result.create_thread.handle,
1246 apc->caller->process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1247 close_handle( current->process, apc->result.create_thread.handle );
1248 apc->result.create_thread.handle = handle;
1249 clear_error(); /* ignore errors from the above calls */
1251 else if (apc->result.type == APC_ASYNC_IO)
1253 if (apc->owner) async_set_result( apc->owner, apc->result.async_io.status );
1255 wake_up( &apc->obj, 0 );
1256 close_handle( current->process, req->prev );
1257 release_object( apc );
1260 if (current->suspend + current->process->suspend > 0) system_only = 1;
1262 for (;;)
1264 if (!(apc = thread_dequeue_apc( current, system_only )))
1266 /* no more APCs */
1267 set_error( STATUS_PENDING );
1268 return;
1270 /* Optimization: ignore APC_NONE calls, they are only used to
1271 * wake up a thread, but since we got here the thread woke up already.
1273 if (apc->call.type != APC_NONE) break;
1274 apc->executed = 1;
1275 wake_up( &apc->obj, 0 );
1276 release_object( apc );
1279 if ((reply->handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1280 reply->call = apc->call;
1281 release_object( apc );
1284 /* Get the result of an APC call */
1285 DECL_HANDLER(get_apc_result)
1287 struct thread_apc *apc;
1289 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1290 0, &thread_apc_ops ))) return;
1291 if (!apc->executed) set_error( STATUS_PENDING );
1292 else
1294 reply->result = apc->result;
1295 /* close the handle directly to avoid an extra round-trip */
1296 close_handle( current->process, req->handle );
1298 release_object( apc );
1301 /* retrieve the current context of a thread */
1302 DECL_HANDLER(get_thread_context)
1304 struct thread *thread;
1305 CONTEXT *context;
1307 if (get_reply_max_size() < sizeof(CONTEXT))
1309 set_error( STATUS_INVALID_PARAMETER );
1310 return;
1312 if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1314 if (req->suspend)
1316 if (thread != current || !thread->suspend_context)
1318 /* not suspended, shouldn't happen */
1319 set_error( STATUS_INVALID_PARAMETER );
1321 else
1323 if (thread->context == thread->suspend_context) thread->context = NULL;
1324 set_reply_data_ptr( thread->suspend_context, sizeof(CONTEXT) );
1325 thread->suspend_context = NULL;
1328 else if (thread != current && !thread->context)
1330 /* thread is not suspended, retry (if it's still running) */
1331 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1332 else set_error( STATUS_PENDING );
1334 else if ((context = set_reply_data_size( sizeof(CONTEXT) )))
1336 unsigned int flags = get_context_system_regs( req->flags );
1338 memset( context, 0, sizeof(CONTEXT) );
1339 context->ContextFlags = get_context_cpu_flag();
1340 if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1341 if (flags) get_thread_context( thread, context, flags );
1343 reply->self = (thread == current);
1344 release_object( thread );
1347 /* set the current context of a thread */
1348 DECL_HANDLER(set_thread_context)
1350 struct thread *thread;
1352 if (get_req_data_size() < sizeof(CONTEXT))
1354 set_error( STATUS_INVALID_PARAMETER );
1355 return;
1357 if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1359 if (req->suspend)
1361 if (thread != current || thread->context)
1363 /* nested suspend or exception, shouldn't happen */
1364 set_error( STATUS_INVALID_PARAMETER );
1366 else if ((thread->suspend_context = mem_alloc( sizeof(CONTEXT) )))
1368 memcpy( thread->suspend_context, get_req_data(), sizeof(CONTEXT) );
1369 thread->context = thread->suspend_context;
1370 if (thread->debug_break) break_thread( thread );
1373 else if (thread != current && !thread->context)
1375 /* thread is not suspended, retry (if it's still running) */
1376 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1377 else set_error( STATUS_PENDING );
1379 else
1381 const CONTEXT *context = get_req_data();
1382 unsigned int flags = get_context_system_regs( req->flags );
1384 if (flags) set_thread_context( thread, context, flags );
1385 if (thread->context && !get_error())
1386 copy_context( thread->context, context, req->flags & ~flags );
1388 reply->self = (thread == current);
1389 release_object( thread );
1392 /* fetch a selector entry for a thread */
1393 DECL_HANDLER(get_selector_entry)
1395 struct thread *thread;
1396 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1398 get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1399 release_object( thread );