push 150847dede558b39567907bd3738046f0ea247b2
[wine/hacks.git] / server / thread.c
blob979beda7888005b8e73e7e332bbbbe994fdea73e
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_SCHED_H
36 #include <sched.h>
37 #endif
38 #ifdef HAVE_POLL_H
39 #include <poll.h>
40 #endif
42 #include "ntstatus.h"
43 #define WIN32_NO_STATUS
44 #include "windef.h"
45 #include "winternl.h"
47 #include "file.h"
48 #include "handle.h"
49 #include "process.h"
50 #include "thread.h"
51 #include "request.h"
52 #include "user.h"
53 #include "security.h"
56 /* thread queues */
58 struct thread_wait
60 struct thread_wait *next; /* next wait structure for this thread */
61 struct thread *thread; /* owner thread */
62 int count; /* count of objects */
63 int flags;
64 void *cookie; /* magic cookie to return to client */
65 timeout_t timeout;
66 struct timeout_user *user;
67 struct wait_queue_entry queues[1];
70 /* asynchronous procedure calls */
72 struct thread_apc
74 struct object obj; /* object header */
75 struct list entry; /* queue linked list */
76 struct thread *caller; /* thread that queued this apc */
77 struct object *owner; /* object that queued this apc */
78 int executed; /* has it been executed by the client? */
79 apc_call_t call; /* call arguments */
80 apc_result_t result; /* call results once executed */
83 static void dump_thread_apc( struct object *obj, int verbose );
84 static int thread_apc_signaled( struct object *obj, struct thread *thread );
85 static void thread_apc_destroy( struct object *obj );
86 static void clear_apc_queue( struct list *queue );
88 static const struct object_ops thread_apc_ops =
90 sizeof(struct thread_apc), /* size */
91 dump_thread_apc, /* dump */
92 add_queue, /* add_queue */
93 remove_queue, /* remove_queue */
94 thread_apc_signaled, /* signaled */
95 no_satisfied, /* satisfied */
96 no_signal, /* signal */
97 no_get_fd, /* get_fd */
98 no_map_access, /* map_access */
99 no_lookup_name, /* lookup_name */
100 no_open_file, /* open_file */
101 no_close_handle, /* close_handle */
102 thread_apc_destroy /* destroy */
106 /* thread operations */
108 static void dump_thread( struct object *obj, int verbose );
109 static int thread_signaled( struct object *obj, struct thread *thread );
110 static unsigned int thread_map_access( struct object *obj, unsigned int access );
111 static void thread_poll_event( struct fd *fd, int event );
112 static void destroy_thread( struct object *obj );
114 static const struct object_ops thread_ops =
116 sizeof(struct thread), /* size */
117 dump_thread, /* dump */
118 add_queue, /* add_queue */
119 remove_queue, /* remove_queue */
120 thread_signaled, /* signaled */
121 no_satisfied, /* satisfied */
122 no_signal, /* signal */
123 no_get_fd, /* get_fd */
124 thread_map_access, /* map_access */
125 no_lookup_name, /* lookup_name */
126 no_open_file, /* open_file */
127 no_close_handle, /* close_handle */
128 destroy_thread /* destroy */
131 static const struct fd_ops thread_fd_ops =
133 NULL, /* get_poll_events */
134 thread_poll_event, /* poll_event */
135 NULL, /* flush */
136 NULL, /* get_fd_type */
137 NULL, /* ioctl */
138 NULL, /* queue_async */
139 NULL, /* reselect_async */
140 NULL /* cancel_async */
143 static struct list thread_list = LIST_INIT(thread_list);
145 /* initialize the structure for a newly allocated thread */
146 static inline void init_thread_structure( struct thread *thread )
148 int i;
150 thread->unix_pid = -1; /* not known yet */
151 thread->unix_tid = -1; /* not known yet */
152 thread->context = NULL;
153 thread->suspend_context = NULL;
154 thread->teb = NULL;
155 thread->debug_ctx = NULL;
156 thread->debug_event = NULL;
157 thread->debug_break = 0;
158 thread->queue = NULL;
159 thread->wait = NULL;
160 thread->error = 0;
161 thread->req_data = NULL;
162 thread->req_toread = 0;
163 thread->reply_data = NULL;
164 thread->reply_towrite = 0;
165 thread->request_fd = NULL;
166 thread->reply_fd = NULL;
167 thread->wait_fd = NULL;
168 thread->state = RUNNING;
169 thread->exit_code = 0;
170 thread->priority = 0;
171 thread->affinity = 1;
172 thread->suspend = 0;
173 thread->desktop_users = 0;
174 thread->token = NULL;
176 thread->creation_time = current_time;
177 thread->exit_time = 0;
179 list_init( &thread->mutex_list );
180 list_init( &thread->system_apc );
181 list_init( &thread->user_apc );
183 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
184 thread->inflight[i].server = thread->inflight[i].client = -1;
187 /* check if address looks valid for a client-side data structure (TEB etc.) */
188 static inline int is_valid_address( void *addr )
190 return addr && !((unsigned long)addr % sizeof(int));
193 /* create a new thread */
194 struct thread *create_thread( int fd, struct process *process )
196 struct thread *thread;
198 if (!(thread = alloc_object( &thread_ops ))) return NULL;
200 init_thread_structure( thread );
202 thread->process = (struct process *)grab_object( process );
203 thread->desktop = process->desktop;
204 if (!current) current = thread;
206 list_add_head( &thread_list, &thread->entry );
208 if (!(thread->id = alloc_ptid( thread )))
210 release_object( thread );
211 return NULL;
213 if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj, 0 )))
215 release_object( thread );
216 return NULL;
219 set_fd_events( thread->request_fd, POLLIN ); /* start listening to events */
220 add_process_thread( thread->process, thread );
221 return thread;
224 /* handle a client event */
225 static void thread_poll_event( struct fd *fd, int event )
227 struct thread *thread = get_fd_user( fd );
228 assert( thread->obj.ops == &thread_ops );
230 if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
231 else if (event & POLLIN) read_request( thread );
232 else if (event & POLLOUT) write_reply( thread );
235 /* cleanup everything that is no longer needed by a dead thread */
236 /* used by destroy_thread and kill_thread */
237 static void cleanup_thread( struct thread *thread )
239 int i;
241 clear_apc_queue( &thread->system_apc );
242 clear_apc_queue( &thread->user_apc );
243 free( thread->req_data );
244 free( thread->reply_data );
245 if (thread->request_fd) release_object( thread->request_fd );
246 if (thread->reply_fd) release_object( thread->reply_fd );
247 if (thread->wait_fd) release_object( thread->wait_fd );
248 free( thread->suspend_context );
249 free_msg_queue( thread );
250 cleanup_clipboard_thread(thread);
251 destroy_thread_windows( thread );
252 close_thread_desktop( thread );
253 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
255 if (thread->inflight[i].client != -1)
257 close( thread->inflight[i].server );
258 thread->inflight[i].client = thread->inflight[i].server = -1;
261 thread->req_data = NULL;
262 thread->reply_data = NULL;
263 thread->request_fd = NULL;
264 thread->reply_fd = NULL;
265 thread->wait_fd = NULL;
266 thread->context = NULL;
267 thread->suspend_context = NULL;
268 thread->desktop = 0;
271 /* destroy a thread when its refcount is 0 */
272 static void destroy_thread( struct object *obj )
274 struct thread *thread = (struct thread *)obj;
275 assert( obj->ops == &thread_ops );
277 assert( !thread->debug_ctx ); /* cannot still be debugging something */
278 list_remove( &thread->entry );
279 cleanup_thread( thread );
280 release_object( thread->process );
281 if (thread->id) free_ptid( thread->id );
282 if (thread->token) release_object( thread->token );
285 /* dump a thread on stdout for debugging purposes */
286 static void dump_thread( struct object *obj, int verbose )
288 struct thread *thread = (struct thread *)obj;
289 assert( obj->ops == &thread_ops );
291 fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d teb=%p state=%d\n",
292 thread->id, thread->unix_pid, thread->unix_tid, thread->teb, thread->state );
295 static int thread_signaled( struct object *obj, struct thread *thread )
297 struct thread *mythread = (struct thread *)obj;
298 return (mythread->state == TERMINATED);
301 static unsigned int thread_map_access( struct object *obj, unsigned int access )
303 if (access & GENERIC_READ) access |= STANDARD_RIGHTS_READ | SYNCHRONIZE;
304 if (access & GENERIC_WRITE) access |= STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
305 if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
306 if (access & GENERIC_ALL) access |= THREAD_ALL_ACCESS;
307 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
310 static void dump_thread_apc( struct object *obj, int verbose )
312 struct thread_apc *apc = (struct thread_apc *)obj;
313 assert( obj->ops == &thread_apc_ops );
315 fprintf( stderr, "APC owner=%p type=%u\n", apc->owner, apc->call.type );
318 static int thread_apc_signaled( struct object *obj, struct thread *thread )
320 struct thread_apc *apc = (struct thread_apc *)obj;
321 return apc->executed;
324 static void thread_apc_destroy( struct object *obj )
326 struct thread_apc *apc = (struct thread_apc *)obj;
327 if (apc->caller) release_object( apc->caller );
328 if (apc->owner) release_object( apc->owner );
331 /* queue an async procedure call */
332 static struct thread_apc *create_apc( struct object *owner, const apc_call_t *call_data )
334 struct thread_apc *apc;
336 if ((apc = alloc_object( &thread_apc_ops )))
338 apc->call = *call_data;
339 apc->caller = NULL;
340 apc->owner = owner;
341 apc->executed = 0;
342 apc->result.type = APC_NONE;
343 if (owner) grab_object( owner );
345 return apc;
348 /* get a thread pointer from a thread id (and increment the refcount) */
349 struct thread *get_thread_from_id( thread_id_t id )
351 struct object *obj = get_ptid_entry( id );
353 if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
354 set_error( STATUS_INVALID_CID );
355 return NULL;
358 /* get a thread from a handle (and increment the refcount) */
359 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
361 return (struct thread *)get_handle_obj( current->process, handle,
362 access, &thread_ops );
365 /* find a thread from a Unix tid */
366 struct thread *get_thread_from_tid( int tid )
368 struct thread *thread;
370 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
372 if (thread->unix_tid == tid) return thread;
374 return NULL;
377 /* find a thread from a Unix pid */
378 struct thread *get_thread_from_pid( int pid )
380 struct thread *thread;
382 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
384 if (thread->unix_pid == pid) return thread;
386 return NULL;
389 #define THREAD_PRIORITY_REALTIME_HIGHEST 6
390 #define THREAD_PRIORITY_REALTIME_LOWEST -7
392 static void set_thread_priority( int unix_tid, int ntprio )
394 #ifdef HAVE_SCHED_H
395 struct sched_param param;
396 int result, scheduler;
398 assert( unix_tid != -1 );
400 /*fprintf( stderr, "wineserver: set thread priority: %d\n", ntprio);*/
401 if (ntprio == THREAD_PRIORITY_TIME_CRITICAL)
403 param.sched_priority = 1;
404 scheduler = SCHED_FIFO;
406 /* TODO: add other priorities that have any effect (e.g. idle) */
407 else
409 param.sched_priority = 0;
410 scheduler = SCHED_OTHER;
413 result = sched_setscheduler( unix_tid, scheduler, &param );
415 if (result == 0)
417 static int once = 1;
418 if(once && ntprio == THREAD_PRIORITY_TIME_CRITICAL)
420 fprintf( stderr, "wineserver: successfull set thread priority: %d (only printed once)\n", ntprio);
421 once = 0;
423 return;
426 if (result == -EPERM)
428 /* TODO: set to some sane fallback priority (a prior set priority may have succeded) */
429 static int once = 1;
430 if(once)
432 fprintf( stderr, "wineserver: Failed (EPERM) to change the priority of a thread to: %d (only printed once)\n", ntprio );
433 once = 0;
435 return;
437 else
439 fprintf( stderr, "wineserver: Failed (with %d) to change the priority of a thread to: %d\n", result, ntprio);
442 perror( "wineserver: sched_setscheduler" );
443 #endif
446 /* set all information about a thread */
447 static void set_thread_info( struct thread *thread,
448 const struct set_thread_info_request *req )
450 if (req->mask & SET_THREAD_INFO_PRIORITY)
452 int max = THREAD_PRIORITY_HIGHEST;
453 int min = THREAD_PRIORITY_LOWEST;
454 if (thread->process->priority == PROCESS_PRIOCLASS_REALTIME)
456 max = THREAD_PRIORITY_REALTIME_HIGHEST;
457 min = THREAD_PRIORITY_REALTIME_LOWEST;
459 if ((req->priority >= min && req->priority <= max) ||
460 req->priority == THREAD_PRIORITY_IDLE ||
461 req->priority == THREAD_PRIORITY_TIME_CRITICAL)
463 if ((thread->priority != req->priority) && (thread->unix_tid != -1))
464 set_thread_priority( thread->unix_tid, req->priority );
465 thread->priority = req->priority;
467 else
468 set_error( STATUS_INVALID_PARAMETER );
470 if (req->mask & SET_THREAD_INFO_AFFINITY)
472 if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
473 else thread->affinity = req->affinity;
475 if (req->mask & SET_THREAD_INFO_TOKEN)
476 security_set_thread_token( thread, req->token );
479 /* stop a thread (at the Unix level) */
480 void stop_thread( struct thread *thread )
482 if (thread->context) return; /* already inside a debug event, no need for a signal */
483 /* can't stop a thread while initialisation is in progress */
484 if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
487 /* suspend a thread */
488 static int suspend_thread( struct thread *thread )
490 int old_count = thread->suspend;
491 if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
493 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
495 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
496 return old_count;
499 /* resume a thread */
500 static int resume_thread( struct thread *thread )
502 int old_count = thread->suspend;
503 if (thread->suspend > 0)
505 if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
507 return old_count;
510 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
511 int add_queue( struct object *obj, struct wait_queue_entry *entry )
513 grab_object( obj );
514 entry->obj = obj;
515 list_add_tail( &obj->wait_queue, &entry->entry );
516 return 1;
519 /* remove a thread from an object wait queue */
520 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
522 list_remove( &entry->entry );
523 release_object( obj );
526 /* finish waiting */
527 static void end_wait( struct thread *thread )
529 struct thread_wait *wait = thread->wait;
530 struct wait_queue_entry *entry;
531 int i;
533 assert( wait );
534 thread->wait = wait->next;
535 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
536 entry->obj->ops->remove_queue( entry->obj, entry );
537 if (wait->user) remove_timeout_user( wait->user );
538 free( wait );
541 /* build the thread wait structure */
542 static int wait_on( unsigned int count, struct object *objects[], int flags, timeout_t timeout )
544 struct thread_wait *wait;
545 struct wait_queue_entry *entry;
546 unsigned int i;
548 if (!(wait = mem_alloc( FIELD_OFFSET(struct thread_wait, queues[count]) ))) return 0;
549 wait->next = current->wait;
550 wait->thread = current;
551 wait->count = count;
552 wait->flags = flags;
553 wait->user = NULL;
554 wait->timeout = timeout;
555 current->wait = wait;
557 for (i = 0, entry = wait->queues; i < count; i++, entry++)
559 struct object *obj = objects[i];
560 entry->thread = current;
561 if (!obj->ops->add_queue( obj, entry ))
563 wait->count = i;
564 end_wait( current );
565 return 0;
568 return 1;
571 /* check if the thread waiting condition is satisfied */
572 static int check_wait( struct thread *thread )
574 int i, signaled;
575 struct thread_wait *wait = thread->wait;
576 struct wait_queue_entry *entry = wait->queues;
578 assert( wait );
580 if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
581 return STATUS_USER_APC;
583 /* Suspended threads may not acquire locks, but they can run system APCs */
584 if (thread->process->suspend + thread->suspend > 0) return -1;
586 if (wait->flags & SELECT_ALL)
588 int not_ok = 0;
589 /* Note: we must check them all anyway, as some objects may
590 * want to do something when signaled, even if others are not */
591 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
592 not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
593 if (not_ok) goto other_checks;
594 /* Wait satisfied: tell it to all objects */
595 signaled = 0;
596 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
597 if (entry->obj->ops->satisfied( entry->obj, thread ))
598 signaled = STATUS_ABANDONED_WAIT_0;
599 return signaled;
601 else
603 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
605 if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
606 /* Wait satisfied: tell it to the object */
607 signaled = i;
608 if (entry->obj->ops->satisfied( entry->obj, thread ))
609 signaled = i + STATUS_ABANDONED_WAIT_0;
610 return signaled;
614 other_checks:
615 if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
616 if (wait->timeout <= current_time) return STATUS_TIMEOUT;
617 return -1;
620 /* send the wakeup signal to a thread */
621 static int send_thread_wakeup( struct thread *thread, void *cookie, int signaled )
623 struct wake_up_reply reply;
624 int ret;
626 reply.cookie = cookie;
627 reply.signaled = signaled;
628 if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
629 return 0;
630 if (ret >= 0)
631 fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
632 else if (errno == EPIPE)
633 kill_thread( thread, 0 ); /* normal death */
634 else
635 fatal_protocol_perror( thread, "write" );
636 return -1;
639 /* attempt to wake up a thread */
640 /* return >0 if OK, 0 if the wait condition is still not satisfied */
641 int wake_thread( struct thread *thread )
643 int signaled, count;
644 void *cookie;
646 for (count = 0; thread->wait; count++)
648 if ((signaled = check_wait( thread )) == -1) break;
650 cookie = thread->wait->cookie;
651 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
652 thread->id, signaled, cookie );
653 end_wait( thread );
654 if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
655 break;
657 return count;
660 /* thread wait timeout */
661 static void thread_timeout( void *ptr )
663 struct thread_wait *wait = ptr;
664 struct thread *thread = wait->thread;
665 void *cookie = wait->cookie;
667 wait->user = NULL;
668 if (thread->wait != wait) return; /* not the top-level wait, ignore it */
669 if (thread->suspend + thread->process->suspend > 0) return; /* suspended, ignore it */
671 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
672 thread->id, (int)STATUS_TIMEOUT, cookie );
673 end_wait( thread );
674 if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
675 /* check if other objects have become signaled in the meantime */
676 wake_thread( thread );
679 /* try signaling an event flag, a semaphore or a mutex */
680 static int signal_object( obj_handle_t handle )
682 struct object *obj;
683 int ret = 0;
685 obj = get_handle_obj( current->process, handle, 0, NULL );
686 if (obj)
688 ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
689 release_object( obj );
691 return ret;
694 /* select on a list of handles */
695 static timeout_t select_on( unsigned int count, void *cookie, const obj_handle_t *handles,
696 int flags, timeout_t timeout, obj_handle_t signal_obj )
698 int ret;
699 unsigned int i;
700 struct object *objects[MAXIMUM_WAIT_OBJECTS];
702 if (timeout <= 0) timeout = current_time - timeout;
704 if (count > MAXIMUM_WAIT_OBJECTS)
706 set_error( STATUS_INVALID_PARAMETER );
707 return 0;
709 for (i = 0; i < count; i++)
711 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
712 break;
715 if (i < count) goto done;
716 if (!wait_on( count, objects, flags, timeout )) goto done;
718 /* signal the object */
719 if (signal_obj)
721 if (!signal_object( signal_obj ))
723 end_wait( current );
724 goto done;
726 /* check if we woke ourselves up */
727 if (!current->wait) goto done;
730 if ((ret = check_wait( current )) != -1)
732 /* condition is already satisfied */
733 end_wait( current );
734 set_error( ret );
735 goto done;
738 /* now we need to wait */
739 if (current->wait->timeout != TIMEOUT_INFINITE)
741 if (!(current->wait->user = add_timeout_user( current->wait->timeout,
742 thread_timeout, current->wait )))
744 end_wait( current );
745 goto done;
748 current->wait->cookie = cookie;
749 set_error( STATUS_PENDING );
751 done:
752 while (i > 0) release_object( objects[--i] );
753 return timeout;
756 /* attempt to wake threads sleeping on the object wait queue */
757 void wake_up( struct object *obj, int max )
759 struct list *ptr, *next;
761 LIST_FOR_EACH_SAFE( ptr, next, &obj->wait_queue )
763 struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
764 if (wake_thread( entry->thread ))
766 if (max && !--max) break;
771 /* return the apc queue to use for a given apc type */
772 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
774 switch(type)
776 case APC_NONE:
777 case APC_USER:
778 case APC_TIMER:
779 return &thread->user_apc;
780 default:
781 return &thread->system_apc;
785 /* check if thread is currently waiting for a (system) apc */
786 static inline int is_in_apc_wait( struct thread *thread )
788 return (thread->process->suspend || thread->suspend ||
789 (thread->wait && (thread->wait->flags & SELECT_INTERRUPTIBLE)));
792 /* queue an existing APC to a given thread */
793 static int queue_apc( struct process *process, struct thread *thread, struct thread_apc *apc )
795 struct list *queue;
797 if (!thread) /* find a suitable thread inside the process */
799 struct thread *candidate;
801 /* first try to find a waiting thread */
802 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
804 if (candidate->state == TERMINATED) continue;
805 if (is_in_apc_wait( candidate ))
807 thread = candidate;
808 break;
811 if (!thread)
813 /* then use the first one that accepts a signal */
814 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
816 if (send_thread_signal( candidate, SIGUSR1 ))
818 thread = candidate;
819 break;
823 if (!thread) return 0; /* nothing found */
824 queue = get_apc_queue( thread, apc->call.type );
826 else
828 if (thread->state == TERMINATED) return 0;
829 queue = get_apc_queue( thread, apc->call.type );
830 /* send signal for system APCs if needed */
831 if (queue == &thread->system_apc && list_empty( queue ) && !is_in_apc_wait( thread ))
833 if (!send_thread_signal( thread, SIGUSR1 )) return 0;
835 /* cancel a possible previous APC with the same owner */
836 if (apc->owner) thread_cancel_apc( thread, apc->owner, apc->call.type );
839 grab_object( apc );
840 list_add_tail( queue, &apc->entry );
841 if (!list_prev( queue, &apc->entry )) /* first one */
842 wake_thread( thread );
844 return 1;
847 /* queue an async procedure call */
848 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
850 struct thread_apc *apc;
851 int ret = 0;
853 if ((apc = create_apc( owner, call_data )))
855 ret = queue_apc( NULL, thread, apc );
856 release_object( apc );
858 return ret;
861 /* cancel the async procedure call owned by a specific object */
862 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
864 struct thread_apc *apc;
865 struct list *queue = get_apc_queue( thread, type );
867 LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
869 if (apc->owner != owner) continue;
870 list_remove( &apc->entry );
871 apc->executed = 1;
872 wake_up( &apc->obj, 0 );
873 release_object( apc );
874 return;
878 /* remove the head apc from the queue; the returned object must be released by the caller */
879 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
881 struct thread_apc *apc = NULL;
882 struct list *ptr = list_head( &thread->system_apc );
884 if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
885 if (ptr)
887 apc = LIST_ENTRY( ptr, struct thread_apc, entry );
888 list_remove( ptr );
890 return apc;
893 /* clear an APC queue, cancelling all the APCs on it */
894 static void clear_apc_queue( struct list *queue )
896 struct list *ptr;
898 while ((ptr = list_head( queue )))
900 struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
901 list_remove( &apc->entry );
902 apc->executed = 1;
903 wake_up( &apc->obj, 0 );
904 release_object( apc );
908 /* add an fd to the inflight list */
909 /* return list index, or -1 on error */
910 int thread_add_inflight_fd( struct thread *thread, int client, int server )
912 int i;
914 if (server == -1) return -1;
915 if (client == -1)
917 close( server );
918 return -1;
921 /* first check if we already have an entry for this fd */
922 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
923 if (thread->inflight[i].client == client)
925 close( thread->inflight[i].server );
926 thread->inflight[i].server = server;
927 return i;
930 /* now find a free spot to store it */
931 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
932 if (thread->inflight[i].client == -1)
934 thread->inflight[i].client = client;
935 thread->inflight[i].server = server;
936 return i;
938 return -1;
941 /* get an inflight fd and purge it from the list */
942 /* the fd must be closed when no longer used */
943 int thread_get_inflight_fd( struct thread *thread, int client )
945 int i, ret;
947 if (client == -1) return -1;
951 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
953 if (thread->inflight[i].client == client)
955 ret = thread->inflight[i].server;
956 thread->inflight[i].server = thread->inflight[i].client = -1;
957 return ret;
960 } while (!receive_fd( thread->process )); /* in case it is still in the socket buffer */
961 return -1;
964 /* kill a thread on the spot */
965 void kill_thread( struct thread *thread, int violent_death )
967 if (thread->state == TERMINATED) return; /* already killed */
968 thread->state = TERMINATED;
969 thread->exit_time = current_time;
970 if (current == thread) current = NULL;
971 if (debug_level)
972 fprintf( stderr,"%04x: *killed* exit_code=%d\n",
973 thread->id, thread->exit_code );
974 if (thread->wait)
976 while (thread->wait) end_wait( thread );
977 send_thread_wakeup( thread, NULL, STATUS_PENDING );
978 /* if it is waiting on the socket, we don't need to send a SIGTERM */
979 violent_death = 0;
981 kill_console_processes( thread, 0 );
982 debug_exit_thread( thread );
983 abandon_mutexes( thread );
984 wake_up( &thread->obj, 0 );
985 if (violent_death) send_thread_signal( thread, SIGTERM );
986 cleanup_thread( thread );
987 remove_process_thread( thread->process, thread );
988 release_object( thread );
991 /* trigger a breakpoint event in a given thread */
992 void break_thread( struct thread *thread )
994 struct debug_event_exception data;
996 assert( thread->context );
998 data.record.ExceptionCode = STATUS_BREAKPOINT;
999 data.record.ExceptionFlags = EXCEPTION_CONTINUABLE;
1000 data.record.ExceptionRecord = NULL;
1001 data.record.ExceptionAddress = get_context_ip( thread->context );
1002 data.record.NumberParameters = 0;
1003 data.first = 1;
1004 generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
1005 thread->debug_break = 0;
1008 /* take a snapshot of currently running threads */
1009 struct thread_snapshot *thread_snap( int *count )
1011 struct thread_snapshot *snapshot, *ptr;
1012 struct thread *thread;
1013 int total = 0;
1015 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1016 if (thread->state != TERMINATED) total++;
1017 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
1018 ptr = snapshot;
1019 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1021 if (thread->state == TERMINATED) continue;
1022 ptr->thread = thread;
1023 ptr->count = thread->obj.refcount;
1024 ptr->priority = thread->priority;
1025 grab_object( thread );
1026 ptr++;
1028 *count = total;
1029 return snapshot;
1032 /* gets the current impersonation token */
1033 struct token *thread_get_impersonation_token( struct thread *thread )
1035 if (thread->token)
1036 return thread->token;
1037 else
1038 return thread->process->token;
1041 /* create a new thread */
1042 DECL_HANDLER(new_thread)
1044 struct thread *thread;
1045 int request_fd = thread_get_inflight_fd( current, req->request_fd );
1047 if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
1049 if (request_fd != -1) close( request_fd );
1050 set_error( STATUS_INVALID_HANDLE );
1051 return;
1054 if ((thread = create_thread( request_fd, current->process )))
1056 if (req->suspend) thread->suspend++;
1057 reply->tid = get_thread_id( thread );
1058 if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
1060 /* thread object will be released when the thread gets killed */
1061 return;
1063 kill_thread( thread, 1 );
1067 /* initialize a new thread */
1068 DECL_HANDLER(init_thread)
1070 struct process *process = current->process;
1071 int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
1072 int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
1074 if (current->reply_fd) /* already initialised */
1076 set_error( STATUS_INVALID_PARAMETER );
1077 goto error;
1080 if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
1082 current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj, 0 );
1083 reply_fd = -1;
1084 if (!current->reply_fd) goto error;
1086 if (wait_fd == -1)
1088 set_error( STATUS_TOO_MANY_OPENED_FILES ); /* most likely reason */
1089 return;
1091 if (!(current->wait_fd = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj, 0 )))
1092 return;
1094 if (!is_valid_address(req->teb) || !is_valid_address(req->peb) || !is_valid_address(req->ldt_copy))
1096 set_error( STATUS_INVALID_PARAMETER );
1097 return;
1100 current->unix_pid = req->unix_pid;
1101 current->unix_tid = req->unix_tid;
1102 current->teb = req->teb;
1104 if (!process->peb) /* first thread, initialize the process too */
1106 process->unix_pid = current->unix_pid;
1107 process->peb = req->peb;
1108 process->ldt_copy = req->ldt_copy;
1109 reply->info_size = init_process( current );
1111 else
1113 if (process->unix_pid != current->unix_pid)
1114 process->unix_pid = -1; /* can happen with linuxthreads */
1115 if (current->suspend + process->suspend > 0) stop_thread( current );
1116 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
1118 debug_level = max( debug_level, req->debug_level );
1120 /* we may have raced with a SetThreadPriority call */
1121 if (current->priority != THREAD_PRIORITY_NORMAL)
1122 set_thread_priority( current->unix_tid, current->priority );
1124 reply->pid = get_process_id( process );
1125 reply->tid = get_thread_id( current );
1126 reply->version = SERVER_PROTOCOL_VERSION;
1127 reply->server_start = server_start_time;
1128 return;
1130 error:
1131 if (reply_fd != -1) close( reply_fd );
1132 if (wait_fd != -1) close( wait_fd );
1135 /* terminate a thread */
1136 DECL_HANDLER(terminate_thread)
1138 struct thread *thread;
1140 reply->self = 0;
1141 reply->last = 0;
1142 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1144 thread->exit_code = req->exit_code;
1145 if (thread != current) kill_thread( thread, 1 );
1146 else
1148 reply->self = 1;
1149 reply->last = (thread->process->running_threads == 1);
1151 release_object( thread );
1155 /* open a handle to a thread */
1156 DECL_HANDLER(open_thread)
1158 struct thread *thread = get_thread_from_id( req->tid );
1160 reply->handle = 0;
1161 if (thread)
1163 reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1164 release_object( thread );
1168 /* fetch information about a thread */
1169 DECL_HANDLER(get_thread_info)
1171 struct thread *thread;
1172 obj_handle_t handle = req->handle;
1174 if (!handle) thread = get_thread_from_id( req->tid_in );
1175 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1177 if (thread)
1179 reply->pid = get_process_id( thread->process );
1180 reply->tid = get_thread_id( thread );
1181 reply->teb = thread->teb;
1182 reply->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1183 reply->priority = thread->priority;
1184 reply->affinity = thread->affinity;
1185 reply->creation_time = thread->creation_time;
1186 reply->exit_time = thread->exit_time;
1187 reply->last = thread->process->running_threads == 1;
1189 release_object( thread );
1193 /* set information about a thread */
1194 DECL_HANDLER(set_thread_info)
1196 struct thread *thread;
1198 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1200 set_thread_info( thread, req );
1201 release_object( thread );
1205 /* suspend a thread */
1206 DECL_HANDLER(suspend_thread)
1208 struct thread *thread;
1210 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1212 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1213 else reply->count = suspend_thread( thread );
1214 release_object( thread );
1218 /* resume a thread */
1219 DECL_HANDLER(resume_thread)
1221 struct thread *thread;
1223 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1225 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1226 else reply->count = resume_thread( thread );
1227 release_object( thread );
1231 /* select on a handle list */
1232 DECL_HANDLER(select)
1234 struct thread_apc *apc;
1235 unsigned int count;
1236 const apc_result_t *result = get_req_data();
1237 const obj_handle_t *handles = (const obj_handle_t *)(result + 1);
1239 if (get_req_data_size() < sizeof(*result))
1241 set_error( STATUS_INVALID_PARAMETER );
1242 return;
1244 count = (get_req_data_size() - sizeof(*result)) / sizeof(obj_handle_t);
1246 /* first store results of previous apc */
1247 if (req->prev_apc)
1249 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev_apc,
1250 0, &thread_apc_ops ))) return;
1251 apc->result = *result;
1252 apc->executed = 1;
1253 if (apc->result.type == APC_CREATE_THREAD) /* transfer the handle to the caller process */
1255 obj_handle_t handle = duplicate_handle( current->process, apc->result.create_thread.handle,
1256 apc->caller->process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1257 close_handle( current->process, apc->result.create_thread.handle );
1258 apc->result.create_thread.handle = handle;
1259 clear_error(); /* ignore errors from the above calls */
1261 else if (apc->result.type == APC_ASYNC_IO)
1263 if (apc->owner) async_set_result( apc->owner, apc->result.async_io.status );
1265 wake_up( &apc->obj, 0 );
1266 close_handle( current->process, req->prev_apc );
1267 release_object( apc );
1270 reply->timeout = select_on( count, req->cookie, handles, req->flags, req->timeout, req->signal );
1272 if (get_error() == STATUS_USER_APC)
1274 for (;;)
1276 if (!(apc = thread_dequeue_apc( current, !(req->flags & SELECT_ALERTABLE) )))
1277 break;
1278 /* Optimization: ignore APC_NONE calls, they are only used to
1279 * wake up a thread, but since we got here the thread woke up already.
1281 if (apc->call.type != APC_NONE)
1283 if ((reply->apc_handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1284 reply->call = apc->call;
1285 release_object( apc );
1286 break;
1288 apc->executed = 1;
1289 wake_up( &apc->obj, 0 );
1290 release_object( apc );
1295 /* queue an APC for a thread or process */
1296 DECL_HANDLER(queue_apc)
1298 struct thread *thread = NULL;
1299 struct process *process = NULL;
1300 struct thread_apc *apc;
1302 if (!(apc = create_apc( NULL, &req->call ))) return;
1304 switch (apc->call.type)
1306 case APC_NONE:
1307 case APC_USER:
1308 thread = get_thread_from_handle( req->thread, THREAD_SET_CONTEXT );
1309 break;
1310 case APC_VIRTUAL_ALLOC:
1311 case APC_VIRTUAL_FREE:
1312 case APC_VIRTUAL_PROTECT:
1313 case APC_VIRTUAL_FLUSH:
1314 case APC_VIRTUAL_LOCK:
1315 case APC_VIRTUAL_UNLOCK:
1316 case APC_UNMAP_VIEW:
1317 process = get_process_from_handle( req->process, PROCESS_VM_OPERATION );
1318 break;
1319 case APC_VIRTUAL_QUERY:
1320 process = get_process_from_handle( req->process, PROCESS_QUERY_INFORMATION );
1321 break;
1322 case APC_MAP_VIEW:
1323 process = get_process_from_handle( req->process, PROCESS_VM_OPERATION );
1324 if (process && process != current->process)
1326 /* duplicate the handle into the target process */
1327 obj_handle_t handle = duplicate_handle( current->process, apc->call.map_view.handle,
1328 process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1329 if (handle) apc->call.map_view.handle = handle;
1330 else
1332 release_object( process );
1333 process = NULL;
1336 break;
1337 case APC_CREATE_THREAD:
1338 process = get_process_from_handle( req->process, PROCESS_CREATE_THREAD );
1339 break;
1340 default:
1341 set_error( STATUS_INVALID_PARAMETER );
1342 break;
1345 if (thread)
1347 if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1348 release_object( thread );
1350 else if (process)
1352 reply->self = (process == current->process);
1353 if (!reply->self)
1355 obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1356 if (handle)
1358 if (queue_apc( process, NULL, apc ))
1360 apc->caller = (struct thread *)grab_object( current );
1361 reply->handle = handle;
1363 else
1365 close_handle( current->process, handle );
1366 set_error( STATUS_PROCESS_IS_TERMINATING );
1370 release_object( process );
1373 release_object( apc );
1376 /* Get the result of an APC call */
1377 DECL_HANDLER(get_apc_result)
1379 struct thread_apc *apc;
1381 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1382 0, &thread_apc_ops ))) return;
1383 if (!apc->executed) set_error( STATUS_PENDING );
1384 else
1386 reply->result = apc->result;
1387 /* close the handle directly to avoid an extra round-trip */
1388 close_handle( current->process, req->handle );
1390 release_object( apc );
1393 /* retrieve the current context of a thread */
1394 DECL_HANDLER(get_thread_context)
1396 struct thread *thread;
1397 CONTEXT *context;
1399 if (get_reply_max_size() < sizeof(CONTEXT))
1401 set_error( STATUS_INVALID_PARAMETER );
1402 return;
1404 if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1406 if (req->suspend)
1408 if (thread != current || !thread->suspend_context)
1410 /* not suspended, shouldn't happen */
1411 set_error( STATUS_INVALID_PARAMETER );
1413 else
1415 if (thread->context == thread->suspend_context) thread->context = NULL;
1416 set_reply_data_ptr( thread->suspend_context, sizeof(CONTEXT) );
1417 thread->suspend_context = NULL;
1420 else if (thread != current && !thread->context)
1422 /* thread is not suspended, retry (if it's still running) */
1423 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1424 else set_error( STATUS_PENDING );
1426 else if ((context = set_reply_data_size( sizeof(CONTEXT) )))
1428 unsigned int flags = get_context_system_regs( req->flags );
1430 memset( context, 0, sizeof(CONTEXT) );
1431 context->ContextFlags = get_context_cpu_flag();
1432 if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1433 if (flags) get_thread_context( thread, context, flags );
1435 reply->self = (thread == current);
1436 release_object( thread );
1439 /* set the current context of a thread */
1440 DECL_HANDLER(set_thread_context)
1442 struct thread *thread;
1444 if (get_req_data_size() < sizeof(CONTEXT))
1446 set_error( STATUS_INVALID_PARAMETER );
1447 return;
1449 if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1451 if (req->suspend)
1453 if (thread != current || thread->context)
1455 /* nested suspend or exception, shouldn't happen */
1456 set_error( STATUS_INVALID_PARAMETER );
1458 else if ((thread->suspend_context = mem_alloc( sizeof(CONTEXT) )))
1460 memcpy( thread->suspend_context, get_req_data(), sizeof(CONTEXT) );
1461 thread->context = thread->suspend_context;
1462 if (thread->debug_break) break_thread( thread );
1465 else if (thread != current && !thread->context)
1467 /* thread is not suspended, retry (if it's still running) */
1468 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1469 else set_error( STATUS_PENDING );
1471 else
1473 const CONTEXT *context = get_req_data();
1474 unsigned int flags = get_context_system_regs( req->flags );
1476 if (flags) set_thread_context( thread, context, flags );
1477 if (thread->context && !get_error())
1478 copy_context( thread->context, context, req->flags & ~flags );
1480 reply->self = (thread == current);
1481 release_object( thread );
1484 /* fetch a selector entry for a thread */
1485 DECL_HANDLER(get_selector_entry)
1487 struct thread *thread;
1488 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1490 get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1491 release_object( thread );