localspl: Implement PortIsValid for XcvDataPort.
[wine/gsoc_dplay.git] / server / thread.c
blob5b0268ab7b19aed4880059df56aeb9d64f30346c
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 object *owner; /* object that queued this apc */
74 int executed; /* has it been executed by the client? */
75 apc_call_t call; /* call arguments */
76 apc_result_t result; /* call results once executed */
79 static void dump_thread_apc( struct object *obj, int verbose );
80 static int thread_apc_signaled( struct object *obj, struct thread *thread );
81 static void clear_apc_queue( struct list *queue );
83 static const struct object_ops thread_apc_ops =
85 sizeof(struct thread_apc), /* size */
86 dump_thread_apc, /* dump */
87 add_queue, /* add_queue */
88 remove_queue, /* remove_queue */
89 thread_apc_signaled, /* signaled */
90 no_satisfied, /* satisfied */
91 no_signal, /* signal */
92 no_get_fd, /* get_fd */
93 no_map_access, /* map_access */
94 no_lookup_name, /* lookup_name */
95 no_close_handle, /* close_handle */
96 no_destroy /* destroy */
100 /* thread operations */
102 static void dump_thread( struct object *obj, int verbose );
103 static int thread_signaled( struct object *obj, struct thread *thread );
104 static unsigned int thread_map_access( struct object *obj, unsigned int access );
105 static void thread_poll_event( struct fd *fd, int event );
106 static void destroy_thread( struct object *obj );
108 static const struct object_ops thread_ops =
110 sizeof(struct thread), /* size */
111 dump_thread, /* dump */
112 add_queue, /* add_queue */
113 remove_queue, /* remove_queue */
114 thread_signaled, /* signaled */
115 no_satisfied, /* satisfied */
116 no_signal, /* signal */
117 no_get_fd, /* get_fd */
118 thread_map_access, /* map_access */
119 no_lookup_name, /* lookup_name */
120 no_close_handle, /* close_handle */
121 destroy_thread /* destroy */
124 static const struct fd_ops thread_fd_ops =
126 NULL, /* get_poll_events */
127 thread_poll_event, /* poll_event */
128 no_flush, /* flush */
129 no_get_file_info, /* get_file_info */
130 no_queue_async, /* queue_async */
131 no_cancel_async /* cancel_async */
134 static struct list thread_list = LIST_INIT(thread_list);
136 /* initialize the structure for a newly allocated thread */
137 inline static void init_thread_structure( struct thread *thread )
139 int i;
141 thread->unix_pid = -1; /* not known yet */
142 thread->unix_tid = -1; /* not known yet */
143 thread->context = NULL;
144 thread->suspend_context = NULL;
145 thread->teb = NULL;
146 thread->debug_ctx = NULL;
147 thread->debug_event = NULL;
148 thread->debug_break = 0;
149 thread->queue = NULL;
150 thread->wait = NULL;
151 thread->error = 0;
152 thread->req_data = NULL;
153 thread->req_toread = 0;
154 thread->reply_data = NULL;
155 thread->reply_towrite = 0;
156 thread->request_fd = NULL;
157 thread->reply_fd = NULL;
158 thread->wait_fd = NULL;
159 thread->state = RUNNING;
160 thread->exit_code = 0;
161 thread->priority = 0;
162 thread->affinity = 1;
163 thread->suspend = 0;
164 thread->desktop_users = 0;
165 thread->token = NULL;
167 thread->creation_time = current_time;
168 thread->exit_time.tv_sec = thread->exit_time.tv_usec = 0;
170 list_init( &thread->mutex_list );
171 list_init( &thread->system_apc );
172 list_init( &thread->user_apc );
174 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
175 thread->inflight[i].server = thread->inflight[i].client = -1;
178 /* check if address looks valid for a client-side data structure (TEB etc.) */
179 static inline int is_valid_address( void *addr )
181 return addr && !((unsigned long)addr % sizeof(int));
184 /* create a new thread */
185 struct thread *create_thread( int fd, struct process *process )
187 struct thread *thread;
189 if (!(thread = alloc_object( &thread_ops ))) return NULL;
191 init_thread_structure( thread );
193 thread->process = (struct process *)grab_object( process );
194 thread->desktop = process->desktop;
195 if (!current) current = thread;
197 list_add_head( &thread_list, &thread->entry );
199 if (!(thread->id = alloc_ptid( thread )))
201 release_object( thread );
202 return NULL;
204 if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj )))
206 release_object( thread );
207 return NULL;
210 set_fd_events( thread->request_fd, POLLIN ); /* start listening to events */
211 add_process_thread( thread->process, thread );
212 return thread;
215 /* handle a client event */
216 static void thread_poll_event( struct fd *fd, int event )
218 struct thread *thread = get_fd_user( fd );
219 assert( thread->obj.ops == &thread_ops );
221 if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
222 else if (event & POLLIN) read_request( thread );
223 else if (event & POLLOUT) write_reply( thread );
226 /* cleanup everything that is no longer needed by a dead thread */
227 /* used by destroy_thread and kill_thread */
228 static void cleanup_thread( struct thread *thread )
230 int i;
232 clear_apc_queue( &thread->system_apc );
233 clear_apc_queue( &thread->user_apc );
234 free( thread->req_data );
235 free( thread->reply_data );
236 if (thread->request_fd) release_object( thread->request_fd );
237 if (thread->reply_fd) release_object( thread->reply_fd );
238 if (thread->wait_fd) release_object( thread->wait_fd );
239 free( thread->suspend_context );
240 free_msg_queue( thread );
241 cleanup_clipboard_thread(thread);
242 destroy_thread_windows( thread );
243 close_thread_desktop( thread );
244 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
246 if (thread->inflight[i].client != -1)
248 close( thread->inflight[i].server );
249 thread->inflight[i].client = thread->inflight[i].server = -1;
252 thread->req_data = NULL;
253 thread->reply_data = NULL;
254 thread->request_fd = NULL;
255 thread->reply_fd = NULL;
256 thread->wait_fd = NULL;
257 thread->context = NULL;
258 thread->suspend_context = NULL;
259 thread->desktop = 0;
262 /* destroy a thread when its refcount is 0 */
263 static void destroy_thread( struct object *obj )
265 struct thread *thread = (struct thread *)obj;
266 assert( obj->ops == &thread_ops );
268 assert( !thread->debug_ctx ); /* cannot still be debugging something */
269 list_remove( &thread->entry );
270 cleanup_thread( thread );
271 release_object( thread->process );
272 if (thread->id) free_ptid( thread->id );
273 if (thread->token) release_object( thread->token );
276 /* dump a thread on stdout for debugging purposes */
277 static void dump_thread( struct object *obj, int verbose )
279 struct thread *thread = (struct thread *)obj;
280 assert( obj->ops == &thread_ops );
282 fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d teb=%p state=%d\n",
283 thread->id, thread->unix_pid, thread->unix_tid, thread->teb, thread->state );
286 static int thread_signaled( struct object *obj, struct thread *thread )
288 struct thread *mythread = (struct thread *)obj;
289 return (mythread->state == TERMINATED);
292 static unsigned int thread_map_access( struct object *obj, unsigned int access )
294 if (access & GENERIC_READ) access |= STANDARD_RIGHTS_READ | SYNCHRONIZE;
295 if (access & GENERIC_WRITE) access |= STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
296 if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
297 if (access & GENERIC_ALL) access |= THREAD_ALL_ACCESS;
298 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
301 static void dump_thread_apc( struct object *obj, int verbose )
303 struct thread_apc *apc = (struct thread_apc *)obj;
304 assert( obj->ops == &thread_apc_ops );
306 fprintf( stderr, "APC owner=%p type=%u\n", apc->owner, apc->call.type );
309 static int thread_apc_signaled( struct object *obj, struct thread *thread )
311 struct thread_apc *apc = (struct thread_apc *)obj;
312 return apc->executed;
315 /* queue an async procedure call */
316 static struct thread_apc *create_apc( struct object *owner, const apc_call_t *call_data )
318 struct thread_apc *apc;
320 if ((apc = alloc_object( &thread_apc_ops )))
322 apc->call = *call_data;
323 apc->owner = owner;
324 apc->executed = 0;
325 apc->result.type = APC_NONE;
327 return apc;
330 /* get a thread pointer from a thread id (and increment the refcount) */
331 struct thread *get_thread_from_id( thread_id_t id )
333 struct object *obj = get_ptid_entry( id );
335 if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
336 set_error( STATUS_INVALID_CID );
337 return NULL;
340 /* get a thread from a handle (and increment the refcount) */
341 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
343 return (struct thread *)get_handle_obj( current->process, handle,
344 access, &thread_ops );
347 /* find a thread from a Unix tid */
348 struct thread *get_thread_from_tid( int tid )
350 struct thread *thread;
352 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
354 if (thread->unix_tid == tid) return thread;
356 return NULL;
359 /* find a thread from a Unix pid */
360 struct thread *get_thread_from_pid( int pid )
362 struct thread *thread;
364 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
366 if (thread->unix_pid == pid) return thread;
368 return NULL;
371 /* set all information about a thread */
372 static void set_thread_info( struct thread *thread,
373 const struct set_thread_info_request *req )
375 if (req->mask & SET_THREAD_INFO_PRIORITY)
376 thread->priority = req->priority;
377 if (req->mask & SET_THREAD_INFO_AFFINITY)
379 if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
380 else thread->affinity = req->affinity;
382 if (req->mask & SET_THREAD_INFO_TOKEN)
383 security_set_thread_token( thread, req->token );
386 /* stop a thread (at the Unix level) */
387 void stop_thread( struct thread *thread )
389 if (thread->context) return; /* already inside a debug event, no need for a signal */
390 /* can't stop a thread while initialisation is in progress */
391 if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
394 /* suspend a thread */
395 static int suspend_thread( struct thread *thread )
397 int old_count = thread->suspend;
398 if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
400 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
402 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
403 return old_count;
406 /* resume a thread */
407 static int resume_thread( struct thread *thread )
409 int old_count = thread->suspend;
410 if (thread->suspend > 0)
412 if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
414 return old_count;
417 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
418 int add_queue( struct object *obj, struct wait_queue_entry *entry )
420 grab_object( obj );
421 entry->obj = obj;
422 list_add_tail( &obj->wait_queue, &entry->entry );
423 return 1;
426 /* remove a thread from an object wait queue */
427 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
429 list_remove( &entry->entry );
430 release_object( obj );
433 /* finish waiting */
434 static void end_wait( struct thread *thread )
436 struct thread_wait *wait = thread->wait;
437 struct wait_queue_entry *entry;
438 int i;
440 assert( wait );
441 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
442 entry->obj->ops->remove_queue( entry->obj, entry );
443 if (wait->user) remove_timeout_user( wait->user );
444 thread->wait = wait->next;
445 free( wait );
448 /* build the thread wait structure */
449 static int wait_on( int count, struct object *objects[], int flags, const abs_time_t *timeout )
451 struct thread_wait *wait;
452 struct wait_queue_entry *entry;
453 int i;
455 if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
456 wait->next = current->wait;
457 wait->thread = current;
458 wait->count = count;
459 wait->flags = flags;
460 wait->user = NULL;
461 current->wait = wait;
462 if (flags & SELECT_TIMEOUT)
464 wait->timeout.tv_sec = timeout->sec;
465 wait->timeout.tv_usec = timeout->usec;
468 for (i = 0, entry = wait->queues; i < count; i++, entry++)
470 struct object *obj = objects[i];
471 entry->thread = current;
472 if (!obj->ops->add_queue( obj, entry ))
474 wait->count = i;
475 end_wait( current );
476 return 0;
479 return 1;
482 /* check if the thread waiting condition is satisfied */
483 static int check_wait( struct thread *thread )
485 int i, signaled;
486 struct thread_wait *wait = thread->wait;
487 struct wait_queue_entry *entry = wait->queues;
489 /* Suspended threads may not acquire locks, but they can run system APCs */
490 if (thread->process->suspend + thread->suspend > 0)
492 if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
493 return STATUS_USER_APC;
494 return -1;
497 assert( wait );
498 if (wait->flags & SELECT_ALL)
500 int not_ok = 0;
501 /* Note: we must check them all anyway, as some objects may
502 * want to do something when signaled, even if others are not */
503 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
504 not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
505 if (not_ok) goto other_checks;
506 /* Wait satisfied: tell it to all objects */
507 signaled = 0;
508 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
509 if (entry->obj->ops->satisfied( entry->obj, thread ))
510 signaled = STATUS_ABANDONED_WAIT_0;
511 return signaled;
513 else
515 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
517 if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
518 /* Wait satisfied: tell it to the object */
519 signaled = i;
520 if (entry->obj->ops->satisfied( entry->obj, thread ))
521 signaled = i + STATUS_ABANDONED_WAIT_0;
522 return signaled;
526 other_checks:
527 if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty(&thread->system_apc)) return STATUS_USER_APC;
528 if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
529 if (wait->flags & SELECT_TIMEOUT)
531 if (!time_before( &current_time, &wait->timeout )) return STATUS_TIMEOUT;
533 return -1;
536 /* send the wakeup signal to a thread */
537 static int send_thread_wakeup( struct thread *thread, void *cookie, int signaled )
539 struct wake_up_reply reply;
540 int ret;
542 reply.cookie = cookie;
543 reply.signaled = signaled;
544 if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
545 return 0;
546 if (ret >= 0)
547 fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
548 else if (errno == EPIPE)
549 kill_thread( thread, 0 ); /* normal death */
550 else
551 fatal_protocol_perror( thread, "write" );
552 return -1;
555 /* attempt to wake up a thread */
556 /* return >0 if OK, 0 if the wait condition is still not satisfied */
557 int wake_thread( struct thread *thread )
559 int signaled, count;
560 void *cookie;
562 for (count = 0; thread->wait; count++)
564 if ((signaled = check_wait( thread )) == -1) break;
566 cookie = thread->wait->cookie;
567 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
568 thread->id, signaled, cookie );
569 end_wait( thread );
570 if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
571 break;
573 return count;
576 /* thread wait timeout */
577 static void thread_timeout( void *ptr )
579 struct thread_wait *wait = ptr;
580 struct thread *thread = wait->thread;
581 void *cookie = wait->cookie;
583 wait->user = NULL;
584 if (thread->wait != wait) return; /* not the top-level wait, ignore it */
585 if (thread->suspend + thread->process->suspend > 0) return; /* suspended, ignore it */
587 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
588 thread->id, (int)STATUS_TIMEOUT, cookie );
589 end_wait( thread );
590 if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
591 /* check if other objects have become signaled in the meantime */
592 wake_thread( thread );
595 /* try signaling an event flag, a semaphore or a mutex */
596 static int signal_object( obj_handle_t handle )
598 struct object *obj;
599 int ret = 0;
601 obj = get_handle_obj( current->process, handle, 0, NULL );
602 if (obj)
604 ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
605 release_object( obj );
607 return ret;
610 /* select on a list of handles */
611 static void select_on( int count, void *cookie, const obj_handle_t *handles,
612 int flags, const abs_time_t *timeout, obj_handle_t signal_obj )
614 int ret, i;
615 struct object *objects[MAXIMUM_WAIT_OBJECTS];
617 if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
619 set_error( STATUS_INVALID_PARAMETER );
620 return;
622 for (i = 0; i < count; i++)
624 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
625 break;
628 if (i < count) goto done;
629 if (!wait_on( count, objects, flags, timeout )) goto done;
631 /* signal the object */
632 if (signal_obj)
634 if (!signal_object( signal_obj ))
636 end_wait( current );
637 goto done;
639 /* check if we woke ourselves up */
640 if (!current->wait) goto done;
643 if ((ret = check_wait( current )) != -1)
645 /* condition is already satisfied */
646 end_wait( current );
647 set_error( ret );
648 goto done;
651 /* now we need to wait */
652 if (flags & SELECT_TIMEOUT)
654 if (!(current->wait->user = add_timeout_user( &current->wait->timeout,
655 thread_timeout, current->wait )))
657 end_wait( current );
658 goto done;
661 current->wait->cookie = cookie;
662 set_error( STATUS_PENDING );
664 done:
665 while (--i >= 0) release_object( objects[i] );
668 /* attempt to wake threads sleeping on the object wait queue */
669 void wake_up( struct object *obj, int max )
671 struct list *ptr, *next;
673 LIST_FOR_EACH_SAFE( ptr, next, &obj->wait_queue )
675 struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
676 if (wake_thread( entry->thread ))
678 if (max && !--max) break;
683 /* return the apc queue to use for a given apc type */
684 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
686 switch(type)
688 case APC_NONE:
689 case APC_USER:
690 case APC_TIMER:
691 return &thread->user_apc;
692 default:
693 return &thread->system_apc;
697 /* queue an existing APC to a given thread */
698 static int queue_apc( struct process *process, struct thread *thread, struct thread_apc *apc )
700 struct list *queue;
702 if (!thread) /* find a suitable thread inside the process */
704 struct thread *candidate;
706 /* first try to find a waiting thread */
707 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
709 if (candidate->state == TERMINATED) continue;
710 if (process->suspend || candidate->suspend ||
711 (candidate->wait && (candidate->wait->flags & SELECT_INTERRUPTIBLE)))
713 thread = candidate;
714 break;
717 if (!thread)
719 /* then use the first one that accepts a signal */
720 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
722 if (send_thread_signal( candidate, SIGUSR1 ))
724 thread = candidate;
725 break;
729 if (!thread) return 0; /* nothing found */
731 else
733 if (thread->state == TERMINATED) return 0;
734 /* cancel a possible previous APC with the same owner */
735 if (apc->owner) thread_cancel_apc( thread, apc->owner, apc->call.type );
738 queue = get_apc_queue( thread, apc->call.type );
739 grab_object( apc );
740 list_add_tail( queue, &apc->entry );
741 if (!list_prev( queue, &apc->entry )) /* first one */
742 wake_thread( thread );
744 return 1;
747 /* queue an async procedure call */
748 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
750 struct thread_apc *apc;
751 int ret = 0;
753 if ((apc = create_apc( owner, call_data )))
755 ret = queue_apc( NULL, thread, apc );
756 release_object( apc );
758 return ret;
761 /* cancel the async procedure call owned by a specific object */
762 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
764 struct thread_apc *apc;
765 struct list *queue = get_apc_queue( thread, type );
767 LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
769 if (apc->owner != owner) continue;
770 list_remove( &apc->entry );
771 apc->executed = 1;
772 wake_up( &apc->obj, 0 );
773 release_object( apc );
774 return;
778 /* remove the head apc from the queue; the returned object must be released by the caller */
779 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
781 struct thread_apc *apc = NULL;
782 struct list *ptr = list_head( &thread->system_apc );
784 if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
785 if (ptr)
787 apc = LIST_ENTRY( ptr, struct thread_apc, entry );
788 list_remove( ptr );
790 return apc;
793 /* clear an APC queue, cancelling all the APCs on it */
794 static void clear_apc_queue( struct list *queue )
796 struct list *ptr;
798 while ((ptr = list_head( queue )))
800 struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
801 list_remove( &apc->entry );
802 apc->executed = 1;
803 wake_up( &apc->obj, 0 );
804 release_object( apc );
808 /* add an fd to the inflight list */
809 /* return list index, or -1 on error */
810 int thread_add_inflight_fd( struct thread *thread, int client, int server )
812 int i;
814 if (server == -1) return -1;
815 if (client == -1)
817 close( server );
818 return -1;
821 /* first check if we already have an entry for this fd */
822 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
823 if (thread->inflight[i].client == client)
825 close( thread->inflight[i].server );
826 thread->inflight[i].server = server;
827 return i;
830 /* now find a free spot to store it */
831 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
832 if (thread->inflight[i].client == -1)
834 thread->inflight[i].client = client;
835 thread->inflight[i].server = server;
836 return i;
838 return -1;
841 /* get an inflight fd and purge it from the list */
842 /* the fd must be closed when no longer used */
843 int thread_get_inflight_fd( struct thread *thread, int client )
845 int i, ret;
847 if (client == -1) return -1;
851 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
853 if (thread->inflight[i].client == client)
855 ret = thread->inflight[i].server;
856 thread->inflight[i].server = thread->inflight[i].client = -1;
857 return ret;
860 } while (!receive_fd( thread->process )); /* in case it is still in the socket buffer */
861 return -1;
864 /* kill a thread on the spot */
865 void kill_thread( struct thread *thread, int violent_death )
867 if (thread->state == TERMINATED) return; /* already killed */
868 thread->state = TERMINATED;
869 thread->exit_time = current_time;
870 if (current == thread) current = NULL;
871 if (debug_level)
872 fprintf( stderr,"%04x: *killed* exit_code=%d\n",
873 thread->id, thread->exit_code );
874 if (thread->wait)
876 while (thread->wait) end_wait( thread );
877 send_thread_wakeup( thread, NULL, STATUS_PENDING );
878 /* if it is waiting on the socket, we don't need to send a SIGTERM */
879 violent_death = 0;
881 kill_console_processes( thread, 0 );
882 debug_exit_thread( thread );
883 abandon_mutexes( thread );
884 wake_up( &thread->obj, 0 );
885 if (violent_death) send_thread_signal( thread, SIGTERM );
886 cleanup_thread( thread );
887 remove_process_thread( thread->process, thread );
888 release_object( thread );
891 /* trigger a breakpoint event in a given thread */
892 void break_thread( struct thread *thread )
894 struct debug_event_exception data;
896 assert( thread->context );
898 data.record.ExceptionCode = STATUS_BREAKPOINT;
899 data.record.ExceptionFlags = EXCEPTION_CONTINUABLE;
900 data.record.ExceptionRecord = NULL;
901 data.record.ExceptionAddress = get_context_ip( thread->context );
902 data.record.NumberParameters = 0;
903 data.first = 1;
904 generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
905 thread->debug_break = 0;
908 /* take a snapshot of currently running threads */
909 struct thread_snapshot *thread_snap( int *count )
911 struct thread_snapshot *snapshot, *ptr;
912 struct thread *thread;
913 int total = 0;
915 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
916 if (thread->state != TERMINATED) total++;
917 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
918 ptr = snapshot;
919 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
921 if (thread->state == TERMINATED) continue;
922 ptr->thread = thread;
923 ptr->count = thread->obj.refcount;
924 ptr->priority = thread->priority;
925 grab_object( thread );
926 ptr++;
928 *count = total;
929 return snapshot;
932 /* gets the current impersonation token */
933 struct token *thread_get_impersonation_token( struct thread *thread )
935 if (thread->token)
936 return thread->token;
937 else
938 return thread->process->token;
941 /* create a new thread */
942 DECL_HANDLER(new_thread)
944 struct thread *thread;
945 int request_fd = thread_get_inflight_fd( current, req->request_fd );
947 if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
949 if (request_fd != -1) close( request_fd );
950 set_error( STATUS_INVALID_HANDLE );
951 return;
954 if ((thread = create_thread( request_fd, current->process )))
956 if (req->suspend) thread->suspend++;
957 reply->tid = get_thread_id( thread );
958 if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
960 /* thread object will be released when the thread gets killed */
961 return;
963 kill_thread( thread, 1 );
967 /* initialize a new thread */
968 DECL_HANDLER(init_thread)
970 struct process *process = current->process;
971 int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
972 int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
974 if (current->reply_fd) /* already initialised */
976 set_error( STATUS_INVALID_PARAMETER );
977 goto error;
980 if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
982 current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj );
983 reply_fd = -1;
984 if (!current->reply_fd) goto error;
986 if (wait_fd == -1)
988 set_error( STATUS_TOO_MANY_OPENED_FILES ); /* most likely reason */
989 return;
991 if (!(current->wait_fd = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj )))
992 return;
994 if (!is_valid_address(req->teb) || !is_valid_address(req->peb) || !is_valid_address(req->ldt_copy))
996 set_error( STATUS_INVALID_PARAMETER );
997 return;
1000 current->unix_pid = req->unix_pid;
1001 current->unix_tid = req->unix_tid;
1002 current->teb = req->teb;
1004 if (!process->peb) /* first thread, initialize the process too */
1006 process->unix_pid = current->unix_pid;
1007 process->peb = req->peb;
1008 process->ldt_copy = req->ldt_copy;
1009 reply->info_size = init_process( current );
1011 else
1013 if (process->unix_pid != current->unix_pid)
1014 process->unix_pid = -1; /* can happen with linuxthreads */
1015 if (current->suspend + process->suspend > 0) stop_thread( current );
1016 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
1018 debug_level = max( debug_level, req->debug_level );
1020 reply->pid = get_process_id( process );
1021 reply->tid = get_thread_id( current );
1022 reply->version = SERVER_PROTOCOL_VERSION;
1023 reply->server_start.sec = server_start_time.tv_sec;
1024 reply->server_start.usec = server_start_time.tv_usec;
1025 return;
1027 error:
1028 if (reply_fd != -1) close( reply_fd );
1029 if (wait_fd != -1) close( wait_fd );
1032 /* terminate a thread */
1033 DECL_HANDLER(terminate_thread)
1035 struct thread *thread;
1037 reply->self = 0;
1038 reply->last = 0;
1039 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1041 thread->exit_code = req->exit_code;
1042 if (thread != current) kill_thread( thread, 1 );
1043 else
1045 reply->self = 1;
1046 reply->last = (thread->process->running_threads == 1);
1048 release_object( thread );
1052 /* open a handle to a thread */
1053 DECL_HANDLER(open_thread)
1055 struct thread *thread = get_thread_from_id( req->tid );
1057 reply->handle = 0;
1058 if (thread)
1060 reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1061 release_object( thread );
1065 /* fetch information about a thread */
1066 DECL_HANDLER(get_thread_info)
1068 struct thread *thread;
1069 obj_handle_t handle = req->handle;
1071 if (!handle) thread = get_thread_from_id( req->tid_in );
1072 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1074 if (thread)
1076 reply->pid = get_process_id( thread->process );
1077 reply->tid = get_thread_id( thread );
1078 reply->teb = thread->teb;
1079 reply->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1080 reply->priority = thread->priority;
1081 reply->affinity = thread->affinity;
1082 reply->creation_time.sec = thread->creation_time.tv_sec;
1083 reply->creation_time.usec = thread->creation_time.tv_usec;
1084 reply->exit_time.sec = thread->exit_time.tv_sec;
1085 reply->exit_time.usec = thread->exit_time.tv_usec;
1086 reply->last = thread->process->running_threads == 1;
1088 release_object( thread );
1092 /* set information about a thread */
1093 DECL_HANDLER(set_thread_info)
1095 struct thread *thread;
1097 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1099 set_thread_info( thread, req );
1100 release_object( thread );
1104 /* suspend a thread */
1105 DECL_HANDLER(suspend_thread)
1107 struct thread *thread;
1109 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1111 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1112 else reply->count = suspend_thread( thread );
1113 release_object( thread );
1117 /* resume a thread */
1118 DECL_HANDLER(resume_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 = resume_thread( thread );
1126 release_object( thread );
1130 /* select on a handle list */
1131 DECL_HANDLER(select)
1133 int count = get_req_data_size() / sizeof(obj_handle_t);
1134 select_on( count, req->cookie, get_req_data(), req->flags, &req->timeout, req->signal );
1137 /* queue an APC for a thread or process */
1138 DECL_HANDLER(queue_apc)
1140 struct thread *thread;
1141 struct process *process;
1142 struct thread_apc *apc;
1143 unsigned int access;
1145 if (!(apc = create_apc( NULL, &req->call ))) return;
1147 switch (apc->call.type)
1149 case APC_NONE:
1150 case APC_USER:
1151 if ((thread = get_thread_from_handle( req->thread, THREAD_SET_CONTEXT )))
1153 if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1154 release_object( thread );
1156 break;
1157 case APC_VIRTUAL_ALLOC:
1158 case APC_VIRTUAL_FREE:
1159 case APC_VIRTUAL_QUERY:
1160 case APC_VIRTUAL_PROTECT:
1161 case APC_VIRTUAL_FLUSH:
1162 case APC_VIRTUAL_LOCK:
1163 case APC_VIRTUAL_UNLOCK:
1164 access = (apc->call.type == APC_VIRTUAL_QUERY) ? PROCESS_QUERY_INFORMATION : PROCESS_VM_OPERATION;
1165 if ((process = get_process_from_handle( req->process, access )))
1167 obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1168 if (handle)
1170 if (queue_apc( process, NULL, apc )) reply->handle = handle;
1171 else
1173 close_handle( current->process, handle );
1174 set_error( STATUS_PROCESS_IS_TERMINATING );
1177 release_object( process );
1179 break;
1180 default:
1181 set_error( STATUS_INVALID_PARAMETER );
1182 break;
1184 release_object( apc );
1187 /* get next APC to call */
1188 DECL_HANDLER(get_apc)
1190 struct thread_apc *apc;
1191 int system_only = !req->alertable;
1193 if (req->prev)
1195 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev,
1196 0, &thread_apc_ops ))) return;
1197 apc->result = req->result;
1198 apc->executed = 1;
1199 wake_up( &apc->obj, 0 );
1200 close_handle( current->process, req->prev );
1201 release_object( apc );
1204 if (current->suspend + current->process->suspend > 0) system_only = 1;
1206 for (;;)
1208 if (!(apc = thread_dequeue_apc( current, system_only )))
1210 /* no more APCs */
1211 set_error( STATUS_PENDING );
1212 return;
1214 /* Optimization: ignore APC_NONE calls, they are only used to
1215 * wake up a thread, but since we got here the thread woke up already.
1217 if (apc->call.type != APC_NONE) break;
1218 apc->executed = 1;
1219 wake_up( &apc->obj, 0 );
1220 release_object( apc );
1223 if ((reply->handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1224 reply->call = apc->call;
1225 release_object( apc );
1228 /* Get the result of an APC call */
1229 DECL_HANDLER(get_apc_result)
1231 struct thread_apc *apc;
1233 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1234 0, &thread_apc_ops ))) return;
1235 if (!apc->executed) set_error( STATUS_PENDING );
1236 else
1238 reply->result = apc->result;
1239 /* close the handle directly to avoid an extra round-trip */
1240 close_handle( current->process, req->handle );
1242 release_object( apc );
1245 /* retrieve the current context of a thread */
1246 DECL_HANDLER(get_thread_context)
1248 struct thread *thread;
1249 CONTEXT *context;
1251 if (get_reply_max_size() < sizeof(CONTEXT))
1253 set_error( STATUS_INVALID_PARAMETER );
1254 return;
1256 if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1258 if (req->suspend)
1260 if (thread != current || !thread->suspend_context)
1262 /* not suspended, shouldn't happen */
1263 set_error( STATUS_INVALID_PARAMETER );
1265 else
1267 if (thread->context == thread->suspend_context) thread->context = NULL;
1268 set_reply_data_ptr( thread->suspend_context, sizeof(CONTEXT) );
1269 thread->suspend_context = NULL;
1272 else if (thread != current && !thread->context)
1274 /* thread is not suspended, retry (if it's still running) */
1275 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1276 else set_error( STATUS_PENDING );
1278 else if ((context = set_reply_data_size( sizeof(CONTEXT) )))
1280 unsigned int flags = get_context_system_regs( req->flags );
1282 memset( context, 0, sizeof(CONTEXT) );
1283 context->ContextFlags = get_context_cpu_flag();
1284 if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1285 if (flags) get_thread_context( thread, context, flags );
1287 reply->self = (thread == current);
1288 release_object( thread );
1291 /* set the current context of a thread */
1292 DECL_HANDLER(set_thread_context)
1294 struct thread *thread;
1296 if (get_req_data_size() < sizeof(CONTEXT))
1298 set_error( STATUS_INVALID_PARAMETER );
1299 return;
1301 if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1303 if (req->suspend)
1305 if (thread != current || thread->context)
1307 /* nested suspend or exception, shouldn't happen */
1308 set_error( STATUS_INVALID_PARAMETER );
1310 else if ((thread->suspend_context = mem_alloc( sizeof(CONTEXT) )))
1312 memcpy( thread->suspend_context, get_req_data(), sizeof(CONTEXT) );
1313 thread->context = thread->suspend_context;
1314 if (thread->debug_break) break_thread( thread );
1317 else if (thread != current && !thread->context)
1319 /* thread is not suspended, retry (if it's still running) */
1320 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1321 else set_error( STATUS_PENDING );
1323 else
1325 const CONTEXT *context = get_req_data();
1326 unsigned int flags = get_context_system_regs( req->flags );
1328 if (flags) set_thread_context( thread, context, flags );
1329 if (thread->context && !get_error())
1330 copy_context( thread->context, context, req->flags & ~flags );
1332 reply->self = (thread == current);
1333 release_object( thread );
1336 /* fetch a selector entry for a thread */
1337 DECL_HANDLER(get_selector_entry)
1339 struct thread *thread;
1340 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1342 get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1343 release_object( thread );