push 583922ece91f6a3e6a32c772f3574cd16e6257fa
[wine/hacks.git] / server / thread.c
blob80c4f69efc7e580a021feaa4a621df7f8fa1d09a
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 default_get_sd, /* get_sd */
100 default_set_sd, /* set_sd */
101 no_lookup_name, /* lookup_name */
102 no_open_file, /* open_file */
103 no_close_handle, /* close_handle */
104 thread_apc_destroy /* destroy */
108 /* thread operations */
110 static void dump_thread( struct object *obj, int verbose );
111 static int thread_signaled( struct object *obj, struct thread *thread );
112 static unsigned int thread_map_access( struct object *obj, unsigned int access );
113 static void thread_poll_event( struct fd *fd, int event );
114 static void destroy_thread( struct object *obj );
116 static const struct object_ops thread_ops =
118 sizeof(struct thread), /* size */
119 dump_thread, /* dump */
120 add_queue, /* add_queue */
121 remove_queue, /* remove_queue */
122 thread_signaled, /* signaled */
123 no_satisfied, /* satisfied */
124 no_signal, /* signal */
125 no_get_fd, /* get_fd */
126 thread_map_access, /* map_access */
127 default_get_sd, /* get_sd */
128 default_set_sd, /* set_sd */
129 no_lookup_name, /* lookup_name */
130 no_open_file, /* open_file */
131 no_close_handle, /* close_handle */
132 destroy_thread /* destroy */
135 static const struct fd_ops thread_fd_ops =
137 NULL, /* get_poll_events */
138 thread_poll_event, /* poll_event */
139 NULL, /* flush */
140 NULL, /* get_fd_type */
141 NULL, /* ioctl */
142 NULL, /* queue_async */
143 NULL, /* reselect_async */
144 NULL /* cancel_async */
147 static struct list thread_list = LIST_INIT(thread_list);
149 /* initialize the structure for a newly allocated thread */
150 static inline void init_thread_structure( struct thread *thread )
152 int i;
154 thread->unix_pid = -1; /* not known yet */
155 thread->unix_tid = -1; /* not known yet */
156 thread->context = NULL;
157 thread->suspend_context = NULL;
158 thread->teb = NULL;
159 thread->debug_ctx = NULL;
160 thread->debug_event = NULL;
161 thread->debug_break = 0;
162 thread->queue = NULL;
163 thread->wait = NULL;
164 thread->error = 0;
165 thread->req_data = NULL;
166 thread->req_toread = 0;
167 thread->reply_data = NULL;
168 thread->reply_towrite = 0;
169 thread->request_fd = NULL;
170 thread->reply_fd = NULL;
171 thread->wait_fd = NULL;
172 thread->state = RUNNING;
173 thread->exit_code = 0;
174 thread->priority = 0;
175 thread->affinity = 1;
176 thread->suspend = 0;
177 thread->desktop_users = 0;
178 thread->token = NULL;
180 thread->creation_time = current_time;
181 thread->exit_time = 0;
183 list_init( &thread->mutex_list );
184 list_init( &thread->system_apc );
185 list_init( &thread->user_apc );
187 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
188 thread->inflight[i].server = thread->inflight[i].client = -1;
191 /* check if address looks valid for a client-side data structure (TEB etc.) */
192 static inline int is_valid_address( void *addr )
194 return addr && !((unsigned long)addr % sizeof(int));
197 /* create a new thread */
198 struct thread *create_thread( int fd, struct process *process )
200 struct thread *thread;
202 if (!(thread = alloc_object( &thread_ops ))) return NULL;
204 init_thread_structure( thread );
206 thread->process = (struct process *)grab_object( process );
207 thread->desktop = process->desktop;
208 if (!current) current = thread;
210 list_add_head( &thread_list, &thread->entry );
212 if (!(thread->id = alloc_ptid( thread )))
214 release_object( thread );
215 return NULL;
217 if (!(thread->request_fd = create_anonymous_fd( &thread_fd_ops, fd, &thread->obj, 0 )))
219 release_object( thread );
220 return NULL;
223 set_fd_events( thread->request_fd, POLLIN ); /* start listening to events */
224 add_process_thread( thread->process, thread );
225 return thread;
228 /* handle a client event */
229 static void thread_poll_event( struct fd *fd, int event )
231 struct thread *thread = get_fd_user( fd );
232 assert( thread->obj.ops == &thread_ops );
234 if (event & (POLLERR | POLLHUP)) kill_thread( thread, 0 );
235 else if (event & POLLIN) read_request( thread );
236 else if (event & POLLOUT) write_reply( thread );
239 /* cleanup everything that is no longer needed by a dead thread */
240 /* used by destroy_thread and kill_thread */
241 static void cleanup_thread( struct thread *thread )
243 int i;
245 clear_apc_queue( &thread->system_apc );
246 clear_apc_queue( &thread->user_apc );
247 free( thread->req_data );
248 free( thread->reply_data );
249 if (thread->request_fd) release_object( thread->request_fd );
250 if (thread->reply_fd) release_object( thread->reply_fd );
251 if (thread->wait_fd) release_object( thread->wait_fd );
252 free( thread->suspend_context );
253 free_msg_queue( thread );
254 cleanup_clipboard_thread(thread);
255 destroy_thread_windows( thread );
256 close_thread_desktop( thread );
257 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
259 if (thread->inflight[i].client != -1)
261 close( thread->inflight[i].server );
262 thread->inflight[i].client = thread->inflight[i].server = -1;
265 thread->req_data = NULL;
266 thread->reply_data = NULL;
267 thread->request_fd = NULL;
268 thread->reply_fd = NULL;
269 thread->wait_fd = NULL;
270 thread->context = NULL;
271 thread->suspend_context = NULL;
272 thread->desktop = 0;
275 /* destroy a thread when its refcount is 0 */
276 static void destroy_thread( struct object *obj )
278 struct thread *thread = (struct thread *)obj;
279 assert( obj->ops == &thread_ops );
281 assert( !thread->debug_ctx ); /* cannot still be debugging something */
282 list_remove( &thread->entry );
283 cleanup_thread( thread );
284 release_object( thread->process );
285 if (thread->id) free_ptid( thread->id );
286 if (thread->token) release_object( thread->token );
289 /* dump a thread on stdout for debugging purposes */
290 static void dump_thread( struct object *obj, int verbose )
292 struct thread *thread = (struct thread *)obj;
293 assert( obj->ops == &thread_ops );
295 fprintf( stderr, "Thread id=%04x unix pid=%d unix tid=%d teb=%p state=%d\n",
296 thread->id, thread->unix_pid, thread->unix_tid, thread->teb, thread->state );
299 static int thread_signaled( struct object *obj, struct thread *thread )
301 struct thread *mythread = (struct thread *)obj;
302 return (mythread->state == TERMINATED);
305 static unsigned int thread_map_access( struct object *obj, unsigned int access )
307 if (access & GENERIC_READ) access |= STANDARD_RIGHTS_READ | SYNCHRONIZE;
308 if (access & GENERIC_WRITE) access |= STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
309 if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
310 if (access & GENERIC_ALL) access |= THREAD_ALL_ACCESS;
311 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
314 static void dump_thread_apc( struct object *obj, int verbose )
316 struct thread_apc *apc = (struct thread_apc *)obj;
317 assert( obj->ops == &thread_apc_ops );
319 fprintf( stderr, "APC owner=%p type=%u\n", apc->owner, apc->call.type );
322 static int thread_apc_signaled( struct object *obj, struct thread *thread )
324 struct thread_apc *apc = (struct thread_apc *)obj;
325 return apc->executed;
328 static void thread_apc_destroy( struct object *obj )
330 struct thread_apc *apc = (struct thread_apc *)obj;
331 if (apc->caller) release_object( apc->caller );
332 if (apc->owner) release_object( apc->owner );
335 /* queue an async procedure call */
336 static struct thread_apc *create_apc( struct object *owner, const apc_call_t *call_data )
338 struct thread_apc *apc;
340 if ((apc = alloc_object( &thread_apc_ops )))
342 apc->call = *call_data;
343 apc->caller = NULL;
344 apc->owner = owner;
345 apc->executed = 0;
346 apc->result.type = APC_NONE;
347 if (owner) grab_object( owner );
349 return apc;
352 /* get a thread pointer from a thread id (and increment the refcount) */
353 struct thread *get_thread_from_id( thread_id_t id )
355 struct object *obj = get_ptid_entry( id );
357 if (obj && obj->ops == &thread_ops) return (struct thread *)grab_object( obj );
358 set_error( STATUS_INVALID_CID );
359 return NULL;
362 /* get a thread from a handle (and increment the refcount) */
363 struct thread *get_thread_from_handle( obj_handle_t handle, unsigned int access )
365 return (struct thread *)get_handle_obj( current->process, handle,
366 access, &thread_ops );
369 /* find a thread from a Unix tid */
370 struct thread *get_thread_from_tid( int tid )
372 struct thread *thread;
374 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
376 if (thread->unix_tid == tid) return thread;
378 return NULL;
381 /* find a thread from a Unix pid */
382 struct thread *get_thread_from_pid( int pid )
384 struct thread *thread;
386 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
388 if (thread->unix_pid == pid) return thread;
390 return NULL;
393 #define THREAD_PRIORITY_REALTIME_HIGHEST 6
394 #define THREAD_PRIORITY_REALTIME_LOWEST -7
396 static void set_thread_priority( int unix_tid, int ntprio )
398 #ifdef HAVE_SCHED_H
399 struct sched_param param;
400 int result, scheduler;
402 assert( unix_tid != -1 );
404 /*fprintf( stderr, "wineserver: set thread priority: %d\n", ntprio);*/
405 if (ntprio == THREAD_PRIORITY_TIME_CRITICAL)
407 param.sched_priority = 1;
408 scheduler = SCHED_FIFO;
410 /* TODO: add other priorities that have any effect (e.g. idle) */
411 else
413 param.sched_priority = 0;
414 scheduler = SCHED_OTHER;
417 result = sched_setscheduler( unix_tid, scheduler, &param );
419 if (result == 0)
421 static int once = 1;
422 if(once && ntprio == THREAD_PRIORITY_TIME_CRITICAL)
424 fprintf( stderr, "wineserver: successfull set thread priority: %d (only printed once)\n", ntprio);
425 once = 0;
427 return;
430 if (result == -EPERM)
432 /* TODO: set to some sane fallback priority (a prior set priority may have succeded) */
433 static int once = 1;
434 if(once)
436 fprintf( stderr, "wineserver: Failed (EPERM) to change the priority of a thread to: %d (only printed once)\n", ntprio );
437 once = 0;
439 return;
441 else
443 fprintf( stderr, "wineserver: Failed (with %d) to change the priority of a thread to: %d\n", result, ntprio);
446 perror( "wineserver: sched_setscheduler" );
447 #endif
450 /* set all information about a thread */
451 static void set_thread_info( struct thread *thread,
452 const struct set_thread_info_request *req )
454 if (req->mask & SET_THREAD_INFO_PRIORITY)
456 int max = THREAD_PRIORITY_HIGHEST;
457 int min = THREAD_PRIORITY_LOWEST;
458 if (thread->process->priority == PROCESS_PRIOCLASS_REALTIME)
460 max = THREAD_PRIORITY_REALTIME_HIGHEST;
461 min = THREAD_PRIORITY_REALTIME_LOWEST;
463 if ((req->priority >= min && req->priority <= max) ||
464 req->priority == THREAD_PRIORITY_IDLE ||
465 req->priority == THREAD_PRIORITY_TIME_CRITICAL)
467 if ((thread->priority != req->priority) && (thread->unix_tid != -1))
468 set_thread_priority( thread->unix_tid, req->priority );
469 thread->priority = req->priority;
471 else
472 set_error( STATUS_INVALID_PARAMETER );
474 if (req->mask & SET_THREAD_INFO_AFFINITY)
476 if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
477 else thread->affinity = req->affinity;
479 if (req->mask & SET_THREAD_INFO_TOKEN)
480 security_set_thread_token( thread, req->token );
483 /* stop a thread (at the Unix level) */
484 void stop_thread( struct thread *thread )
486 if (thread->context) return; /* already inside a debug event, no need for a signal */
487 /* can't stop a thread while initialisation is in progress */
488 if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
491 /* suspend a thread */
492 static int suspend_thread( struct thread *thread )
494 int old_count = thread->suspend;
495 if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
497 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
499 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
500 return old_count;
503 /* resume a thread */
504 static int resume_thread( struct thread *thread )
506 int old_count = thread->suspend;
507 if (thread->suspend > 0)
509 if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
511 return old_count;
514 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
515 int add_queue( struct object *obj, struct wait_queue_entry *entry )
517 grab_object( obj );
518 entry->obj = obj;
519 list_add_tail( &obj->wait_queue, &entry->entry );
520 return 1;
523 /* remove a thread from an object wait queue */
524 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
526 list_remove( &entry->entry );
527 release_object( obj );
530 /* finish waiting */
531 static void end_wait( struct thread *thread )
533 struct thread_wait *wait = thread->wait;
534 struct wait_queue_entry *entry;
535 int i;
537 assert( wait );
538 thread->wait = wait->next;
539 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
540 entry->obj->ops->remove_queue( entry->obj, entry );
541 if (wait->user) remove_timeout_user( wait->user );
542 free( wait );
545 /* build the thread wait structure */
546 static int wait_on( unsigned int count, struct object *objects[], int flags, timeout_t timeout )
548 struct thread_wait *wait;
549 struct wait_queue_entry *entry;
550 unsigned int i;
552 if (!(wait = mem_alloc( FIELD_OFFSET(struct thread_wait, queues[count]) ))) return 0;
553 wait->next = current->wait;
554 wait->thread = current;
555 wait->count = count;
556 wait->flags = flags;
557 wait->user = NULL;
558 wait->timeout = timeout;
559 current->wait = wait;
561 for (i = 0, entry = wait->queues; i < count; i++, entry++)
563 struct object *obj = objects[i];
564 entry->thread = current;
565 if (!obj->ops->add_queue( obj, entry ))
567 wait->count = i;
568 end_wait( current );
569 return 0;
572 return 1;
575 /* check if the thread waiting condition is satisfied */
576 static int check_wait( struct thread *thread )
578 int i, signaled;
579 struct thread_wait *wait = thread->wait;
580 struct wait_queue_entry *entry = wait->queues;
582 assert( wait );
584 if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
585 return STATUS_USER_APC;
587 /* Suspended threads may not acquire locks, but they can run system APCs */
588 if (thread->process->suspend + thread->suspend > 0) return -1;
590 if (wait->flags & SELECT_ALL)
592 int not_ok = 0;
593 /* Note: we must check them all anyway, as some objects may
594 * want to do something when signaled, even if others are not */
595 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
596 not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
597 if (not_ok) goto other_checks;
598 /* Wait satisfied: tell it to all objects */
599 signaled = 0;
600 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
601 if (entry->obj->ops->satisfied( entry->obj, thread ))
602 signaled = STATUS_ABANDONED_WAIT_0;
603 return signaled;
605 else
607 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
609 if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
610 /* Wait satisfied: tell it to the object */
611 signaled = i;
612 if (entry->obj->ops->satisfied( entry->obj, thread ))
613 signaled = i + STATUS_ABANDONED_WAIT_0;
614 return signaled;
618 other_checks:
619 if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
620 if (wait->timeout <= current_time) return STATUS_TIMEOUT;
621 return -1;
624 /* send the wakeup signal to a thread */
625 static int send_thread_wakeup( struct thread *thread, void *cookie, int signaled )
627 struct wake_up_reply reply;
628 int ret;
630 reply.cookie = cookie;
631 reply.signaled = signaled;
632 if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
633 return 0;
634 if (ret >= 0)
635 fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
636 else if (errno == EPIPE)
637 kill_thread( thread, 0 ); /* normal death */
638 else
639 fatal_protocol_perror( thread, "write" );
640 return -1;
643 /* attempt to wake up a thread */
644 /* return >0 if OK, 0 if the wait condition is still not satisfied */
645 int wake_thread( struct thread *thread )
647 int signaled, count;
648 void *cookie;
650 for (count = 0; thread->wait; count++)
652 if ((signaled = check_wait( thread )) == -1) break;
654 cookie = thread->wait->cookie;
655 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
656 thread->id, signaled, cookie );
657 end_wait( thread );
658 if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
659 break;
661 return count;
664 /* thread wait timeout */
665 static void thread_timeout( void *ptr )
667 struct thread_wait *wait = ptr;
668 struct thread *thread = wait->thread;
669 void *cookie = wait->cookie;
671 wait->user = NULL;
672 if (thread->wait != wait) return; /* not the top-level wait, ignore it */
673 if (thread->suspend + thread->process->suspend > 0) return; /* suspended, ignore it */
675 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
676 thread->id, (int)STATUS_TIMEOUT, cookie );
677 end_wait( thread );
678 if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
679 /* check if other objects have become signaled in the meantime */
680 wake_thread( thread );
683 /* try signaling an event flag, a semaphore or a mutex */
684 static int signal_object( obj_handle_t handle )
686 struct object *obj;
687 int ret = 0;
689 obj = get_handle_obj( current->process, handle, 0, NULL );
690 if (obj)
692 ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
693 release_object( obj );
695 return ret;
698 /* select on a list of handles */
699 static timeout_t select_on( unsigned int count, void *cookie, const obj_handle_t *handles,
700 int flags, timeout_t timeout, obj_handle_t signal_obj )
702 int ret;
703 unsigned int i;
704 struct object *objects[MAXIMUM_WAIT_OBJECTS];
706 if (timeout <= 0) timeout = current_time - timeout;
708 if (count > MAXIMUM_WAIT_OBJECTS)
710 set_error( STATUS_INVALID_PARAMETER );
711 return 0;
713 for (i = 0; i < count; i++)
715 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
716 break;
719 if (i < count) goto done;
720 if (!wait_on( count, objects, flags, timeout )) goto done;
722 /* signal the object */
723 if (signal_obj)
725 if (!signal_object( signal_obj ))
727 end_wait( current );
728 goto done;
730 /* check if we woke ourselves up */
731 if (!current->wait) goto done;
734 if ((ret = check_wait( current )) != -1)
736 /* condition is already satisfied */
737 end_wait( current );
738 set_error( ret );
739 goto done;
742 /* now we need to wait */
743 if (current->wait->timeout != TIMEOUT_INFINITE)
745 if (!(current->wait->user = add_timeout_user( current->wait->timeout,
746 thread_timeout, current->wait )))
748 end_wait( current );
749 goto done;
752 current->wait->cookie = cookie;
753 set_error( STATUS_PENDING );
755 done:
756 while (i > 0) release_object( objects[--i] );
757 return timeout;
760 /* attempt to wake threads sleeping on the object wait queue */
761 void wake_up( struct object *obj, int max )
763 struct list *ptr, *next;
765 LIST_FOR_EACH_SAFE( ptr, next, &obj->wait_queue )
767 struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
768 if (wake_thread( entry->thread ))
770 if (max && !--max) break;
775 /* return the apc queue to use for a given apc type */
776 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
778 switch(type)
780 case APC_NONE:
781 case APC_USER:
782 case APC_TIMER:
783 return &thread->user_apc;
784 default:
785 return &thread->system_apc;
789 /* check if thread is currently waiting for a (system) apc */
790 static inline int is_in_apc_wait( struct thread *thread )
792 return (thread->process->suspend || thread->suspend ||
793 (thread->wait && (thread->wait->flags & SELECT_INTERRUPTIBLE)));
796 /* queue an existing APC to a given thread */
797 static int queue_apc( struct process *process, struct thread *thread, struct thread_apc *apc )
799 struct list *queue;
801 if (!thread) /* find a suitable thread inside the process */
803 struct thread *candidate;
805 /* first try to find a waiting thread */
806 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
808 if (candidate->state == TERMINATED) continue;
809 if (is_in_apc_wait( candidate ))
811 thread = candidate;
812 break;
815 if (!thread)
817 /* then use the first one that accepts a signal */
818 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
820 if (send_thread_signal( candidate, SIGUSR1 ))
822 thread = candidate;
823 break;
827 if (!thread) return 0; /* nothing found */
828 queue = get_apc_queue( thread, apc->call.type );
830 else
832 if (thread->state == TERMINATED) return 0;
833 queue = get_apc_queue( thread, apc->call.type );
834 /* send signal for system APCs if needed */
835 if (queue == &thread->system_apc && list_empty( queue ) && !is_in_apc_wait( thread ))
837 if (!send_thread_signal( thread, SIGUSR1 )) return 0;
839 /* cancel a possible previous APC with the same owner */
840 if (apc->owner) thread_cancel_apc( thread, apc->owner, apc->call.type );
843 grab_object( apc );
844 list_add_tail( queue, &apc->entry );
845 if (!list_prev( queue, &apc->entry )) /* first one */
846 wake_thread( thread );
848 return 1;
851 /* queue an async procedure call */
852 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
854 struct thread_apc *apc;
855 int ret = 0;
857 if ((apc = create_apc( owner, call_data )))
859 ret = queue_apc( NULL, thread, apc );
860 release_object( apc );
862 return ret;
865 /* cancel the async procedure call owned by a specific object */
866 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
868 struct thread_apc *apc;
869 struct list *queue = get_apc_queue( thread, type );
871 LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
873 if (apc->owner != owner) continue;
874 list_remove( &apc->entry );
875 apc->executed = 1;
876 wake_up( &apc->obj, 0 );
877 release_object( apc );
878 return;
882 /* remove the head apc from the queue; the returned object must be released by the caller */
883 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
885 struct thread_apc *apc = NULL;
886 struct list *ptr = list_head( &thread->system_apc );
888 if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
889 if (ptr)
891 apc = LIST_ENTRY( ptr, struct thread_apc, entry );
892 list_remove( ptr );
894 return apc;
897 /* clear an APC queue, cancelling all the APCs on it */
898 static void clear_apc_queue( struct list *queue )
900 struct list *ptr;
902 while ((ptr = list_head( queue )))
904 struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
905 list_remove( &apc->entry );
906 apc->executed = 1;
907 wake_up( &apc->obj, 0 );
908 release_object( apc );
912 /* add an fd to the inflight list */
913 /* return list index, or -1 on error */
914 int thread_add_inflight_fd( struct thread *thread, int client, int server )
916 int i;
918 if (server == -1) return -1;
919 if (client == -1)
921 close( server );
922 return -1;
925 /* first check if we already have an entry for this fd */
926 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
927 if (thread->inflight[i].client == client)
929 close( thread->inflight[i].server );
930 thread->inflight[i].server = server;
931 return i;
934 /* now find a free spot to store it */
935 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
936 if (thread->inflight[i].client == -1)
938 thread->inflight[i].client = client;
939 thread->inflight[i].server = server;
940 return i;
942 return -1;
945 /* get an inflight fd and purge it from the list */
946 /* the fd must be closed when no longer used */
947 int thread_get_inflight_fd( struct thread *thread, int client )
949 int i, ret;
951 if (client == -1) return -1;
955 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
957 if (thread->inflight[i].client == client)
959 ret = thread->inflight[i].server;
960 thread->inflight[i].server = thread->inflight[i].client = -1;
961 return ret;
964 } while (!receive_fd( thread->process )); /* in case it is still in the socket buffer */
965 return -1;
968 /* kill a thread on the spot */
969 void kill_thread( struct thread *thread, int violent_death )
971 if (thread->state == TERMINATED) return; /* already killed */
972 thread->state = TERMINATED;
973 thread->exit_time = current_time;
974 if (current == thread) current = NULL;
975 if (debug_level)
976 fprintf( stderr,"%04x: *killed* exit_code=%d\n",
977 thread->id, thread->exit_code );
978 if (thread->wait)
980 while (thread->wait) end_wait( thread );
981 send_thread_wakeup( thread, NULL, STATUS_PENDING );
982 /* if it is waiting on the socket, we don't need to send a SIGTERM */
983 violent_death = 0;
985 kill_console_processes( thread, 0 );
986 debug_exit_thread( thread );
987 abandon_mutexes( thread );
988 wake_up( &thread->obj, 0 );
989 if (violent_death) send_thread_signal( thread, SIGTERM );
990 cleanup_thread( thread );
991 remove_process_thread( thread->process, thread );
992 release_object( thread );
995 /* trigger a breakpoint event in a given thread */
996 void break_thread( struct thread *thread )
998 struct debug_event_exception data;
1000 assert( thread->context );
1002 data.record.ExceptionCode = STATUS_BREAKPOINT;
1003 data.record.ExceptionFlags = EXCEPTION_CONTINUABLE;
1004 data.record.ExceptionRecord = NULL;
1005 data.record.ExceptionAddress = get_context_ip( thread->context );
1006 data.record.NumberParameters = 0;
1007 data.first = 1;
1008 generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
1009 thread->debug_break = 0;
1012 /* take a snapshot of currently running threads */
1013 struct thread_snapshot *thread_snap( int *count )
1015 struct thread_snapshot *snapshot, *ptr;
1016 struct thread *thread;
1017 int total = 0;
1019 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1020 if (thread->state != TERMINATED) total++;
1021 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
1022 ptr = snapshot;
1023 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1025 if (thread->state == TERMINATED) continue;
1026 ptr->thread = thread;
1027 ptr->count = thread->obj.refcount;
1028 ptr->priority = thread->priority;
1029 grab_object( thread );
1030 ptr++;
1032 *count = total;
1033 return snapshot;
1036 /* gets the current impersonation token */
1037 struct token *thread_get_impersonation_token( struct thread *thread )
1039 if (thread->token)
1040 return thread->token;
1041 else
1042 return thread->process->token;
1045 /* create a new thread */
1046 DECL_HANDLER(new_thread)
1048 struct thread *thread;
1049 int request_fd = thread_get_inflight_fd( current, req->request_fd );
1051 if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
1053 if (request_fd != -1) close( request_fd );
1054 set_error( STATUS_INVALID_HANDLE );
1055 return;
1058 if ((thread = create_thread( request_fd, current->process )))
1060 if (req->suspend) thread->suspend++;
1061 reply->tid = get_thread_id( thread );
1062 if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
1064 /* thread object will be released when the thread gets killed */
1065 return;
1067 kill_thread( thread, 1 );
1071 /* initialize a new thread */
1072 DECL_HANDLER(init_thread)
1074 struct process *process = current->process;
1075 int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
1076 int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
1078 if (current->reply_fd) /* already initialised */
1080 set_error( STATUS_INVALID_PARAMETER );
1081 goto error;
1084 if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
1086 current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj, 0 );
1087 reply_fd = -1;
1088 if (!current->reply_fd) goto error;
1090 if (wait_fd == -1)
1092 set_error( STATUS_TOO_MANY_OPENED_FILES ); /* most likely reason */
1093 return;
1095 if (!(current->wait_fd = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj, 0 )))
1096 return;
1098 if (!is_valid_address(req->teb) || !is_valid_address(req->peb) || !is_valid_address(req->ldt_copy))
1100 set_error( STATUS_INVALID_PARAMETER );
1101 return;
1104 current->unix_pid = req->unix_pid;
1105 current->unix_tid = req->unix_tid;
1106 current->teb = req->teb;
1108 if (!process->peb) /* first thread, initialize the process too */
1110 process->unix_pid = current->unix_pid;
1111 process->peb = req->peb;
1112 process->ldt_copy = req->ldt_copy;
1113 reply->info_size = init_process( current );
1115 else
1117 if (process->unix_pid != current->unix_pid)
1118 process->unix_pid = -1; /* can happen with linuxthreads */
1119 if (current->suspend + process->suspend > 0) stop_thread( current );
1120 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
1122 debug_level = max( debug_level, req->debug_level );
1124 /* we may have raced with a SetThreadPriority call */
1125 if (current->priority != THREAD_PRIORITY_NORMAL)
1126 set_thread_priority( current->unix_tid, current->priority );
1128 reply->pid = get_process_id( process );
1129 reply->tid = get_thread_id( current );
1130 reply->version = SERVER_PROTOCOL_VERSION;
1131 reply->server_start = server_start_time;
1132 return;
1134 error:
1135 if (reply_fd != -1) close( reply_fd );
1136 if (wait_fd != -1) close( wait_fd );
1139 /* terminate a thread */
1140 DECL_HANDLER(terminate_thread)
1142 struct thread *thread;
1144 reply->self = 0;
1145 reply->last = 0;
1146 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1148 thread->exit_code = req->exit_code;
1149 if (thread != current) kill_thread( thread, 1 );
1150 else
1152 reply->self = 1;
1153 reply->last = (thread->process->running_threads == 1);
1155 release_object( thread );
1159 /* open a handle to a thread */
1160 DECL_HANDLER(open_thread)
1162 struct thread *thread = get_thread_from_id( req->tid );
1164 reply->handle = 0;
1165 if (thread)
1167 reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1168 release_object( thread );
1172 /* fetch information about a thread */
1173 DECL_HANDLER(get_thread_info)
1175 struct thread *thread;
1176 obj_handle_t handle = req->handle;
1178 if (!handle) thread = get_thread_from_id( req->tid_in );
1179 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1181 if (thread)
1183 reply->pid = get_process_id( thread->process );
1184 reply->tid = get_thread_id( thread );
1185 reply->teb = thread->teb;
1186 reply->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1187 reply->priority = thread->priority;
1188 reply->affinity = thread->affinity;
1189 reply->creation_time = thread->creation_time;
1190 reply->exit_time = thread->exit_time;
1191 reply->last = thread->process->running_threads == 1;
1193 release_object( thread );
1197 /* set information about a thread */
1198 DECL_HANDLER(set_thread_info)
1200 struct thread *thread;
1202 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1204 set_thread_info( thread, req );
1205 release_object( thread );
1209 /* suspend a thread */
1210 DECL_HANDLER(suspend_thread)
1212 struct thread *thread;
1214 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1216 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1217 else reply->count = suspend_thread( thread );
1218 release_object( thread );
1222 /* resume a thread */
1223 DECL_HANDLER(resume_thread)
1225 struct thread *thread;
1227 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1229 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1230 else reply->count = resume_thread( thread );
1231 release_object( thread );
1235 /* select on a handle list */
1236 DECL_HANDLER(select)
1238 struct thread_apc *apc;
1239 unsigned int count;
1240 const apc_result_t *result = get_req_data();
1241 const obj_handle_t *handles = (const obj_handle_t *)(result + 1);
1243 if (get_req_data_size() < sizeof(*result))
1245 set_error( STATUS_INVALID_PARAMETER );
1246 return;
1248 count = (get_req_data_size() - sizeof(*result)) / sizeof(obj_handle_t);
1250 /* first store results of previous apc */
1251 if (req->prev_apc)
1253 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev_apc,
1254 0, &thread_apc_ops ))) return;
1255 apc->result = *result;
1256 apc->executed = 1;
1257 if (apc->result.type == APC_CREATE_THREAD) /* transfer the handle to the caller process */
1259 obj_handle_t handle = duplicate_handle( current->process, apc->result.create_thread.handle,
1260 apc->caller->process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1261 close_handle( current->process, apc->result.create_thread.handle );
1262 apc->result.create_thread.handle = handle;
1263 clear_error(); /* ignore errors from the above calls */
1265 else if (apc->result.type == APC_ASYNC_IO)
1267 if (apc->owner) async_set_result( apc->owner, apc->result.async_io.status );
1269 wake_up( &apc->obj, 0 );
1270 close_handle( current->process, req->prev_apc );
1271 release_object( apc );
1274 reply->timeout = select_on( count, req->cookie, handles, req->flags, req->timeout, req->signal );
1276 if (get_error() == STATUS_USER_APC)
1278 for (;;)
1280 if (!(apc = thread_dequeue_apc( current, !(req->flags & SELECT_ALERTABLE) )))
1281 break;
1282 /* Optimization: ignore APC_NONE calls, they are only used to
1283 * wake up a thread, but since we got here the thread woke up already.
1285 if (apc->call.type != APC_NONE)
1287 if ((reply->apc_handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1288 reply->call = apc->call;
1289 release_object( apc );
1290 break;
1292 apc->executed = 1;
1293 wake_up( &apc->obj, 0 );
1294 release_object( apc );
1299 /* queue an APC for a thread or process */
1300 DECL_HANDLER(queue_apc)
1302 struct thread *thread = NULL;
1303 struct process *process = NULL;
1304 struct thread_apc *apc;
1306 if (!(apc = create_apc( NULL, &req->call ))) return;
1308 switch (apc->call.type)
1310 case APC_NONE:
1311 case APC_USER:
1312 thread = get_thread_from_handle( req->thread, THREAD_SET_CONTEXT );
1313 break;
1314 case APC_VIRTUAL_ALLOC:
1315 case APC_VIRTUAL_FREE:
1316 case APC_VIRTUAL_PROTECT:
1317 case APC_VIRTUAL_FLUSH:
1318 case APC_VIRTUAL_LOCK:
1319 case APC_VIRTUAL_UNLOCK:
1320 case APC_UNMAP_VIEW:
1321 process = get_process_from_handle( req->process, PROCESS_VM_OPERATION );
1322 break;
1323 case APC_VIRTUAL_QUERY:
1324 process = get_process_from_handle( req->process, PROCESS_QUERY_INFORMATION );
1325 break;
1326 case APC_MAP_VIEW:
1327 process = get_process_from_handle( req->process, PROCESS_VM_OPERATION );
1328 if (process && process != current->process)
1330 /* duplicate the handle into the target process */
1331 obj_handle_t handle = duplicate_handle( current->process, apc->call.map_view.handle,
1332 process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1333 if (handle) apc->call.map_view.handle = handle;
1334 else
1336 release_object( process );
1337 process = NULL;
1340 break;
1341 case APC_CREATE_THREAD:
1342 process = get_process_from_handle( req->process, PROCESS_CREATE_THREAD );
1343 break;
1344 default:
1345 set_error( STATUS_INVALID_PARAMETER );
1346 break;
1349 if (thread)
1351 if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1352 release_object( thread );
1354 else if (process)
1356 reply->self = (process == current->process);
1357 if (!reply->self)
1359 obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1360 if (handle)
1362 if (queue_apc( process, NULL, apc ))
1364 apc->caller = (struct thread *)grab_object( current );
1365 reply->handle = handle;
1367 else
1369 close_handle( current->process, handle );
1370 set_error( STATUS_PROCESS_IS_TERMINATING );
1374 release_object( process );
1377 release_object( apc );
1380 /* Get the result of an APC call */
1381 DECL_HANDLER(get_apc_result)
1383 struct thread_apc *apc;
1385 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1386 0, &thread_apc_ops ))) return;
1387 if (!apc->executed) set_error( STATUS_PENDING );
1388 else
1390 reply->result = apc->result;
1391 /* close the handle directly to avoid an extra round-trip */
1392 close_handle( current->process, req->handle );
1394 release_object( apc );
1397 /* retrieve the current context of a thread */
1398 DECL_HANDLER(get_thread_context)
1400 struct thread *thread;
1401 CONTEXT *context;
1403 if (get_reply_max_size() < sizeof(CONTEXT))
1405 set_error( STATUS_INVALID_PARAMETER );
1406 return;
1408 if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1410 if (req->suspend)
1412 if (thread != current || !thread->suspend_context)
1414 /* not suspended, shouldn't happen */
1415 set_error( STATUS_INVALID_PARAMETER );
1417 else
1419 if (thread->context == thread->suspend_context) thread->context = NULL;
1420 set_reply_data_ptr( thread->suspend_context, sizeof(CONTEXT) );
1421 thread->suspend_context = NULL;
1424 else if (thread != current && !thread->context)
1426 /* thread is not suspended, retry (if it's still running) */
1427 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1428 else set_error( STATUS_PENDING );
1430 else if ((context = set_reply_data_size( sizeof(CONTEXT) )))
1432 unsigned int flags = get_context_system_regs( req->flags );
1434 memset( context, 0, sizeof(CONTEXT) );
1435 context->ContextFlags = get_context_cpu_flag();
1436 if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1437 if (flags) get_thread_context( thread, context, flags );
1439 reply->self = (thread == current);
1440 release_object( thread );
1443 /* set the current context of a thread */
1444 DECL_HANDLER(set_thread_context)
1446 struct thread *thread;
1448 if (get_req_data_size() < sizeof(CONTEXT))
1450 set_error( STATUS_INVALID_PARAMETER );
1451 return;
1453 if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1455 if (req->suspend)
1457 if (thread != current || thread->context)
1459 /* nested suspend or exception, shouldn't happen */
1460 set_error( STATUS_INVALID_PARAMETER );
1462 else if ((thread->suspend_context = mem_alloc( sizeof(CONTEXT) )))
1464 memcpy( thread->suspend_context, get_req_data(), sizeof(CONTEXT) );
1465 thread->context = thread->suspend_context;
1466 if (thread->debug_break) break_thread( thread );
1469 else if (thread != current && !thread->context)
1471 /* thread is not suspended, retry (if it's still running) */
1472 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1473 else set_error( STATUS_PENDING );
1475 else
1477 const CONTEXT *context = get_req_data();
1478 unsigned int flags = get_context_system_regs( req->flags );
1480 if (flags) set_thread_context( thread, context, flags );
1481 if (thread->context && !get_error())
1482 copy_context( thread->context, context, req->flags & ~flags );
1484 reply->self = (thread == current);
1485 release_object( thread );
1488 /* fetch a selector entry for a thread */
1489 DECL_HANDLER(get_selector_entry)
1491 struct thread *thread;
1492 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1494 get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1495 release_object( thread );