push 7a18a4ae7c2bf2ba4d68ac56f1ac427d00926089
[wine/hacks.git] / server / thread.c
blob5216a7fb199ebbef39faa61ec52b307d004b3ddd
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 static void set_thread_priority( int unix_tid, int ntprio )
391 #ifdef HAVE_SCHED_H
392 struct sched_param param;
393 int result, scheduler;
395 assert( unix_tid != -1 );
397 /*fprintf( stderr, "wineserver: set thread priority: %d\n", ntprio);*/
398 if (ntprio == THREAD_PRIORITY_TIME_CRITICAL)
400 param.sched_priority = 1;
401 scheduler = SCHED_FIFO;
403 /* TODO: add other priorities that have any effect (e.g. idle) */
404 else
406 param.sched_priority = 0;
407 scheduler = SCHED_OTHER;
410 result = sched_setscheduler( unix_tid, scheduler, &param );
412 if (result == 0)
414 static int once = 1;
415 if(once && ntprio == THREAD_PRIORITY_TIME_CRITICAL)
417 fprintf( stderr, "wineserver: successfull set thread priority: %d (only printed once)\n", ntprio);
418 once = 0;
420 return;
423 if (result == -EPERM)
425 /* TODO: set to some sane fallback priority (a prior set priority may have succeded) */
426 static int once = 1;
427 if(once)
429 fprintf( stderr, "wineserver: Failed (EPERM) to change the priority of a thread to: %d (only printed once)\n", ntprio );
430 once = 0;
432 return;
434 else
436 fprintf( stderr, "wineserver: Failed (with %d) to change the priority of a thread to: %d\n", result, ntprio);
439 perror( "wineserver: sched_setscheduler" );
440 #endif
443 /* set all information about a thread */
444 static void set_thread_info( struct thread *thread,
445 const struct set_thread_info_request *req )
447 if (req->mask & SET_THREAD_INFO_PRIORITY)
449 if ((thread->priority != req->priority) && (thread->unix_tid != -1))
450 set_thread_priority( thread->unix_tid, req->priority );
451 thread->priority = req->priority;
454 if (req->mask & SET_THREAD_INFO_AFFINITY)
456 if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
457 else thread->affinity = req->affinity;
459 if (req->mask & SET_THREAD_INFO_TOKEN)
460 security_set_thread_token( thread, req->token );
463 /* stop a thread (at the Unix level) */
464 void stop_thread( struct thread *thread )
466 if (thread->context) return; /* already inside a debug event, no need for a signal */
467 /* can't stop a thread while initialisation is in progress */
468 if (is_process_init_done(thread->process)) send_thread_signal( thread, SIGUSR1 );
471 /* suspend a thread */
472 static int suspend_thread( struct thread *thread )
474 int old_count = thread->suspend;
475 if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
477 if (!(thread->process->suspend + thread->suspend++)) stop_thread( thread );
479 else set_error( STATUS_SUSPEND_COUNT_EXCEEDED );
480 return old_count;
483 /* resume a thread */
484 static int resume_thread( struct thread *thread )
486 int old_count = thread->suspend;
487 if (thread->suspend > 0)
489 if (!(--thread->suspend + thread->process->suspend)) wake_thread( thread );
491 return old_count;
494 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
495 int add_queue( struct object *obj, struct wait_queue_entry *entry )
497 grab_object( obj );
498 entry->obj = obj;
499 list_add_tail( &obj->wait_queue, &entry->entry );
500 return 1;
503 /* remove a thread from an object wait queue */
504 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
506 list_remove( &entry->entry );
507 release_object( obj );
510 /* finish waiting */
511 static void end_wait( struct thread *thread )
513 struct thread_wait *wait = thread->wait;
514 struct wait_queue_entry *entry;
515 int i;
517 assert( wait );
518 thread->wait = wait->next;
519 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
520 entry->obj->ops->remove_queue( entry->obj, entry );
521 if (wait->user) remove_timeout_user( wait->user );
522 free( wait );
525 /* build the thread wait structure */
526 static int wait_on( unsigned int count, struct object *objects[], int flags, timeout_t timeout )
528 struct thread_wait *wait;
529 struct wait_queue_entry *entry;
530 unsigned int i;
532 if (!(wait = mem_alloc( FIELD_OFFSET(struct thread_wait, queues[count]) ))) return 0;
533 wait->next = current->wait;
534 wait->thread = current;
535 wait->count = count;
536 wait->flags = flags;
537 wait->user = NULL;
538 wait->timeout = timeout;
539 current->wait = wait;
541 for (i = 0, entry = wait->queues; i < count; i++, entry++)
543 struct object *obj = objects[i];
544 entry->thread = current;
545 if (!obj->ops->add_queue( obj, entry ))
547 wait->count = i;
548 end_wait( current );
549 return 0;
552 return 1;
555 /* check if the thread waiting condition is satisfied */
556 static int check_wait( struct thread *thread )
558 int i, signaled;
559 struct thread_wait *wait = thread->wait;
560 struct wait_queue_entry *entry = wait->queues;
562 assert( wait );
564 if ((wait->flags & SELECT_INTERRUPTIBLE) && !list_empty( &thread->system_apc ))
565 return STATUS_USER_APC;
567 /* Suspended threads may not acquire locks, but they can run system APCs */
568 if (thread->process->suspend + thread->suspend > 0) return -1;
570 if (wait->flags & SELECT_ALL)
572 int not_ok = 0;
573 /* Note: we must check them all anyway, as some objects may
574 * want to do something when signaled, even if others are not */
575 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
576 not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
577 if (not_ok) goto other_checks;
578 /* Wait satisfied: tell it to all objects */
579 signaled = 0;
580 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
581 if (entry->obj->ops->satisfied( entry->obj, thread ))
582 signaled = STATUS_ABANDONED_WAIT_0;
583 return signaled;
585 else
587 for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
589 if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
590 /* Wait satisfied: tell it to the object */
591 signaled = i;
592 if (entry->obj->ops->satisfied( entry->obj, thread ))
593 signaled = i + STATUS_ABANDONED_WAIT_0;
594 return signaled;
598 other_checks:
599 if ((wait->flags & SELECT_ALERTABLE) && !list_empty(&thread->user_apc)) return STATUS_USER_APC;
600 if (wait->timeout <= current_time) return STATUS_TIMEOUT;
601 return -1;
604 /* send the wakeup signal to a thread */
605 static int send_thread_wakeup( struct thread *thread, void *cookie, int signaled )
607 struct wake_up_reply reply;
608 int ret;
610 reply.cookie = cookie;
611 reply.signaled = signaled;
612 if ((ret = write( get_unix_fd( thread->wait_fd ), &reply, sizeof(reply) )) == sizeof(reply))
613 return 0;
614 if (ret >= 0)
615 fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
616 else if (errno == EPIPE)
617 kill_thread( thread, 0 ); /* normal death */
618 else
619 fatal_protocol_perror( thread, "write" );
620 return -1;
623 /* attempt to wake up a thread */
624 /* return >0 if OK, 0 if the wait condition is still not satisfied */
625 int wake_thread( struct thread *thread )
627 int signaled, count;
628 void *cookie;
630 for (count = 0; thread->wait; count++)
632 if ((signaled = check_wait( thread )) == -1) break;
634 cookie = thread->wait->cookie;
635 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
636 thread->id, signaled, cookie );
637 end_wait( thread );
638 if (send_thread_wakeup( thread, cookie, signaled ) == -1) /* error */
639 break;
641 return count;
644 /* thread wait timeout */
645 static void thread_timeout( void *ptr )
647 struct thread_wait *wait = ptr;
648 struct thread *thread = wait->thread;
649 void *cookie = wait->cookie;
651 wait->user = NULL;
652 if (thread->wait != wait) return; /* not the top-level wait, ignore it */
653 if (thread->suspend + thread->process->suspend > 0) return; /* suspended, ignore it */
655 if (debug_level) fprintf( stderr, "%04x: *wakeup* signaled=%d cookie=%p\n",
656 thread->id, (int)STATUS_TIMEOUT, cookie );
657 end_wait( thread );
658 if (send_thread_wakeup( thread, cookie, STATUS_TIMEOUT ) == -1) return;
659 /* check if other objects have become signaled in the meantime */
660 wake_thread( thread );
663 /* try signaling an event flag, a semaphore or a mutex */
664 static int signal_object( obj_handle_t handle )
666 struct object *obj;
667 int ret = 0;
669 obj = get_handle_obj( current->process, handle, 0, NULL );
670 if (obj)
672 ret = obj->ops->signal( obj, get_handle_access( current->process, handle ));
673 release_object( obj );
675 return ret;
678 /* select on a list of handles */
679 static timeout_t select_on( unsigned int count, void *cookie, const obj_handle_t *handles,
680 int flags, timeout_t timeout, obj_handle_t signal_obj )
682 int ret;
683 unsigned int i;
684 struct object *objects[MAXIMUM_WAIT_OBJECTS];
686 if (timeout <= 0) timeout = current_time - timeout;
688 if (count > MAXIMUM_WAIT_OBJECTS)
690 set_error( STATUS_INVALID_PARAMETER );
691 return 0;
693 for (i = 0; i < count; i++)
695 if (!(objects[i] = get_handle_obj( current->process, handles[i], SYNCHRONIZE, NULL )))
696 break;
699 if (i < count) goto done;
700 if (!wait_on( count, objects, flags, timeout )) goto done;
702 /* signal the object */
703 if (signal_obj)
705 if (!signal_object( signal_obj ))
707 end_wait( current );
708 goto done;
710 /* check if we woke ourselves up */
711 if (!current->wait) goto done;
714 if ((ret = check_wait( current )) != -1)
716 /* condition is already satisfied */
717 end_wait( current );
718 set_error( ret );
719 goto done;
722 /* now we need to wait */
723 if (current->wait->timeout != TIMEOUT_INFINITE)
725 if (!(current->wait->user = add_timeout_user( current->wait->timeout,
726 thread_timeout, current->wait )))
728 end_wait( current );
729 goto done;
732 current->wait->cookie = cookie;
733 set_error( STATUS_PENDING );
735 done:
736 while (i > 0) release_object( objects[--i] );
737 return timeout;
740 /* attempt to wake threads sleeping on the object wait queue */
741 void wake_up( struct object *obj, int max )
743 struct list *ptr, *next;
745 LIST_FOR_EACH_SAFE( ptr, next, &obj->wait_queue )
747 struct wait_queue_entry *entry = LIST_ENTRY( ptr, struct wait_queue_entry, entry );
748 if (wake_thread( entry->thread ))
750 if (max && !--max) break;
755 /* return the apc queue to use for a given apc type */
756 static inline struct list *get_apc_queue( struct thread *thread, enum apc_type type )
758 switch(type)
760 case APC_NONE:
761 case APC_USER:
762 case APC_TIMER:
763 return &thread->user_apc;
764 default:
765 return &thread->system_apc;
769 /* check if thread is currently waiting for a (system) apc */
770 static inline int is_in_apc_wait( struct thread *thread )
772 return (thread->process->suspend || thread->suspend ||
773 (thread->wait && (thread->wait->flags & SELECT_INTERRUPTIBLE)));
776 /* queue an existing APC to a given thread */
777 static int queue_apc( struct process *process, struct thread *thread, struct thread_apc *apc )
779 struct list *queue;
781 if (!thread) /* find a suitable thread inside the process */
783 struct thread *candidate;
785 /* first try to find a waiting thread */
786 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
788 if (candidate->state == TERMINATED) continue;
789 if (is_in_apc_wait( candidate ))
791 thread = candidate;
792 break;
795 if (!thread)
797 /* then use the first one that accepts a signal */
798 LIST_FOR_EACH_ENTRY( candidate, &process->thread_list, struct thread, proc_entry )
800 if (send_thread_signal( candidate, SIGUSR1 ))
802 thread = candidate;
803 break;
807 if (!thread) return 0; /* nothing found */
808 queue = get_apc_queue( thread, apc->call.type );
810 else
812 if (thread->state == TERMINATED) return 0;
813 queue = get_apc_queue( thread, apc->call.type );
814 /* send signal for system APCs if needed */
815 if (queue == &thread->system_apc && list_empty( queue ) && !is_in_apc_wait( thread ))
817 if (!send_thread_signal( thread, SIGUSR1 )) return 0;
819 /* cancel a possible previous APC with the same owner */
820 if (apc->owner) thread_cancel_apc( thread, apc->owner, apc->call.type );
823 grab_object( apc );
824 list_add_tail( queue, &apc->entry );
825 if (!list_prev( queue, &apc->entry )) /* first one */
826 wake_thread( thread );
828 return 1;
831 /* queue an async procedure call */
832 int thread_queue_apc( struct thread *thread, struct object *owner, const apc_call_t *call_data )
834 struct thread_apc *apc;
835 int ret = 0;
837 if ((apc = create_apc( owner, call_data )))
839 ret = queue_apc( NULL, thread, apc );
840 release_object( apc );
842 return ret;
845 /* cancel the async procedure call owned by a specific object */
846 void thread_cancel_apc( struct thread *thread, struct object *owner, enum apc_type type )
848 struct thread_apc *apc;
849 struct list *queue = get_apc_queue( thread, type );
851 LIST_FOR_EACH_ENTRY( apc, queue, struct thread_apc, entry )
853 if (apc->owner != owner) continue;
854 list_remove( &apc->entry );
855 apc->executed = 1;
856 wake_up( &apc->obj, 0 );
857 release_object( apc );
858 return;
862 /* remove the head apc from the queue; the returned object must be released by the caller */
863 static struct thread_apc *thread_dequeue_apc( struct thread *thread, int system_only )
865 struct thread_apc *apc = NULL;
866 struct list *ptr = list_head( &thread->system_apc );
868 if (!ptr && !system_only) ptr = list_head( &thread->user_apc );
869 if (ptr)
871 apc = LIST_ENTRY( ptr, struct thread_apc, entry );
872 list_remove( ptr );
874 return apc;
877 /* clear an APC queue, cancelling all the APCs on it */
878 static void clear_apc_queue( struct list *queue )
880 struct list *ptr;
882 while ((ptr = list_head( queue )))
884 struct thread_apc *apc = LIST_ENTRY( ptr, struct thread_apc, entry );
885 list_remove( &apc->entry );
886 apc->executed = 1;
887 wake_up( &apc->obj, 0 );
888 release_object( apc );
892 /* add an fd to the inflight list */
893 /* return list index, or -1 on error */
894 int thread_add_inflight_fd( struct thread *thread, int client, int server )
896 int i;
898 if (server == -1) return -1;
899 if (client == -1)
901 close( server );
902 return -1;
905 /* first check if we already have an entry for this fd */
906 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
907 if (thread->inflight[i].client == client)
909 close( thread->inflight[i].server );
910 thread->inflight[i].server = server;
911 return i;
914 /* now find a free spot to store it */
915 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
916 if (thread->inflight[i].client == -1)
918 thread->inflight[i].client = client;
919 thread->inflight[i].server = server;
920 return i;
922 return -1;
925 /* get an inflight fd and purge it from the list */
926 /* the fd must be closed when no longer used */
927 int thread_get_inflight_fd( struct thread *thread, int client )
929 int i, ret;
931 if (client == -1) return -1;
935 for (i = 0; i < MAX_INFLIGHT_FDS; i++)
937 if (thread->inflight[i].client == client)
939 ret = thread->inflight[i].server;
940 thread->inflight[i].server = thread->inflight[i].client = -1;
941 return ret;
944 } while (!receive_fd( thread->process )); /* in case it is still in the socket buffer */
945 return -1;
948 /* kill a thread on the spot */
949 void kill_thread( struct thread *thread, int violent_death )
951 if (thread->state == TERMINATED) return; /* already killed */
952 thread->state = TERMINATED;
953 thread->exit_time = current_time;
954 if (current == thread) current = NULL;
955 if (debug_level)
956 fprintf( stderr,"%04x: *killed* exit_code=%d\n",
957 thread->id, thread->exit_code );
958 if (thread->wait)
960 while (thread->wait) end_wait( thread );
961 send_thread_wakeup( thread, NULL, STATUS_PENDING );
962 /* if it is waiting on the socket, we don't need to send a SIGTERM */
963 violent_death = 0;
965 kill_console_processes( thread, 0 );
966 debug_exit_thread( thread );
967 abandon_mutexes( thread );
968 wake_up( &thread->obj, 0 );
969 if (violent_death) send_thread_signal( thread, SIGTERM );
970 cleanup_thread( thread );
971 remove_process_thread( thread->process, thread );
972 release_object( thread );
975 /* trigger a breakpoint event in a given thread */
976 void break_thread( struct thread *thread )
978 struct debug_event_exception data;
980 assert( thread->context );
982 data.record.ExceptionCode = STATUS_BREAKPOINT;
983 data.record.ExceptionFlags = EXCEPTION_CONTINUABLE;
984 data.record.ExceptionRecord = NULL;
985 data.record.ExceptionAddress = get_context_ip( thread->context );
986 data.record.NumberParameters = 0;
987 data.first = 1;
988 generate_debug_event( thread, EXCEPTION_DEBUG_EVENT, &data );
989 thread->debug_break = 0;
992 /* take a snapshot of currently running threads */
993 struct thread_snapshot *thread_snap( int *count )
995 struct thread_snapshot *snapshot, *ptr;
996 struct thread *thread;
997 int total = 0;
999 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1000 if (thread->state != TERMINATED) total++;
1001 if (!total || !(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
1002 ptr = snapshot;
1003 LIST_FOR_EACH_ENTRY( thread, &thread_list, struct thread, entry )
1005 if (thread->state == TERMINATED) continue;
1006 ptr->thread = thread;
1007 ptr->count = thread->obj.refcount;
1008 ptr->priority = thread->priority;
1009 grab_object( thread );
1010 ptr++;
1012 *count = total;
1013 return snapshot;
1016 /* gets the current impersonation token */
1017 struct token *thread_get_impersonation_token( struct thread *thread )
1019 if (thread->token)
1020 return thread->token;
1021 else
1022 return thread->process->token;
1025 /* create a new thread */
1026 DECL_HANDLER(new_thread)
1028 struct thread *thread;
1029 int request_fd = thread_get_inflight_fd( current, req->request_fd );
1031 if (request_fd == -1 || fcntl( request_fd, F_SETFL, O_NONBLOCK ) == -1)
1033 if (request_fd != -1) close( request_fd );
1034 set_error( STATUS_INVALID_HANDLE );
1035 return;
1038 if ((thread = create_thread( request_fd, current->process )))
1040 if (req->suspend) thread->suspend++;
1041 reply->tid = get_thread_id( thread );
1042 if ((reply->handle = alloc_handle( current->process, thread, req->access, req->attributes )))
1044 /* thread object will be released when the thread gets killed */
1045 return;
1047 kill_thread( thread, 1 );
1051 /* initialize a new thread */
1052 DECL_HANDLER(init_thread)
1054 struct process *process = current->process;
1055 int reply_fd = thread_get_inflight_fd( current, req->reply_fd );
1056 int wait_fd = thread_get_inflight_fd( current, req->wait_fd );
1058 if (current->reply_fd) /* already initialised */
1060 set_error( STATUS_INVALID_PARAMETER );
1061 goto error;
1064 if (reply_fd == -1 || fcntl( reply_fd, F_SETFL, O_NONBLOCK ) == -1) goto error;
1066 current->reply_fd = create_anonymous_fd( &thread_fd_ops, reply_fd, &current->obj, 0 );
1067 reply_fd = -1;
1068 if (!current->reply_fd) goto error;
1070 if (wait_fd == -1)
1072 set_error( STATUS_TOO_MANY_OPENED_FILES ); /* most likely reason */
1073 return;
1075 if (!(current->wait_fd = create_anonymous_fd( &thread_fd_ops, wait_fd, &current->obj, 0 )))
1076 return;
1078 if (!is_valid_address(req->teb) || !is_valid_address(req->peb) || !is_valid_address(req->ldt_copy))
1080 set_error( STATUS_INVALID_PARAMETER );
1081 return;
1084 current->unix_pid = req->unix_pid;
1085 current->unix_tid = req->unix_tid;
1086 current->teb = req->teb;
1088 if (!process->peb) /* first thread, initialize the process too */
1090 process->unix_pid = current->unix_pid;
1091 process->peb = req->peb;
1092 process->ldt_copy = req->ldt_copy;
1093 reply->info_size = init_process( current );
1095 else
1097 if (process->unix_pid != current->unix_pid)
1098 process->unix_pid = -1; /* can happen with linuxthreads */
1099 if (current->suspend + process->suspend > 0) stop_thread( current );
1100 generate_debug_event( current, CREATE_THREAD_DEBUG_EVENT, req->entry );
1102 debug_level = max( debug_level, req->debug_level );
1104 /* we may have raced with a SetThreadPriority call */
1105 if (current->priority != THREAD_PRIORITY_NORMAL)
1106 set_thread_priority( current->unix_tid, current->priority );
1108 reply->pid = get_process_id( process );
1109 reply->tid = get_thread_id( current );
1110 reply->version = SERVER_PROTOCOL_VERSION;
1111 reply->server_start = server_start_time;
1112 return;
1114 error:
1115 if (reply_fd != -1) close( reply_fd );
1116 if (wait_fd != -1) close( wait_fd );
1119 /* terminate a thread */
1120 DECL_HANDLER(terminate_thread)
1122 struct thread *thread;
1124 reply->self = 0;
1125 reply->last = 0;
1126 if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
1128 thread->exit_code = req->exit_code;
1129 if (thread != current) kill_thread( thread, 1 );
1130 else
1132 reply->self = 1;
1133 reply->last = (thread->process->running_threads == 1);
1135 release_object( thread );
1139 /* open a handle to a thread */
1140 DECL_HANDLER(open_thread)
1142 struct thread *thread = get_thread_from_id( req->tid );
1144 reply->handle = 0;
1145 if (thread)
1147 reply->handle = alloc_handle( current->process, thread, req->access, req->attributes );
1148 release_object( thread );
1152 /* fetch information about a thread */
1153 DECL_HANDLER(get_thread_info)
1155 struct thread *thread;
1156 obj_handle_t handle = req->handle;
1158 if (!handle) thread = get_thread_from_id( req->tid_in );
1159 else thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION );
1161 if (thread)
1163 reply->pid = get_process_id( thread->process );
1164 reply->tid = get_thread_id( thread );
1165 reply->teb = thread->teb;
1166 reply->exit_code = (thread->state == TERMINATED) ? thread->exit_code : STATUS_PENDING;
1167 reply->priority = thread->priority;
1168 reply->affinity = thread->affinity;
1169 reply->creation_time = thread->creation_time;
1170 reply->exit_time = thread->exit_time;
1171 reply->last = thread->process->running_threads == 1;
1173 release_object( thread );
1177 /* set information about a thread */
1178 DECL_HANDLER(set_thread_info)
1180 struct thread *thread;
1182 if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
1184 set_thread_info( thread, req );
1185 release_object( thread );
1189 /* suspend a thread */
1190 DECL_HANDLER(suspend_thread)
1192 struct thread *thread;
1194 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1196 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1197 else reply->count = suspend_thread( thread );
1198 release_object( thread );
1202 /* resume a thread */
1203 DECL_HANDLER(resume_thread)
1205 struct thread *thread;
1207 if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
1209 if (thread->state == TERMINATED) set_error( STATUS_ACCESS_DENIED );
1210 else reply->count = resume_thread( thread );
1211 release_object( thread );
1215 /* select on a handle list */
1216 DECL_HANDLER(select)
1218 unsigned int count = get_req_data_size() / sizeof(obj_handle_t);
1219 reply->timeout = select_on( count, req->cookie, get_req_data(), req->flags, req->timeout, req->signal );
1222 /* queue an APC for a thread or process */
1223 DECL_HANDLER(queue_apc)
1225 struct thread *thread = NULL;
1226 struct process *process = NULL;
1227 struct thread_apc *apc;
1229 if (!(apc = create_apc( NULL, &req->call ))) return;
1231 switch (apc->call.type)
1233 case APC_NONE:
1234 case APC_USER:
1235 thread = get_thread_from_handle( req->thread, THREAD_SET_CONTEXT );
1236 break;
1237 case APC_VIRTUAL_ALLOC:
1238 case APC_VIRTUAL_FREE:
1239 case APC_VIRTUAL_PROTECT:
1240 case APC_VIRTUAL_FLUSH:
1241 case APC_VIRTUAL_LOCK:
1242 case APC_VIRTUAL_UNLOCK:
1243 case APC_UNMAP_VIEW:
1244 process = get_process_from_handle( req->process, PROCESS_VM_OPERATION );
1245 break;
1246 case APC_VIRTUAL_QUERY:
1247 process = get_process_from_handle( req->process, PROCESS_QUERY_INFORMATION );
1248 break;
1249 case APC_MAP_VIEW:
1250 process = get_process_from_handle( req->process, PROCESS_VM_OPERATION );
1251 if (process && process != current->process)
1253 /* duplicate the handle into the target process */
1254 obj_handle_t handle = duplicate_handle( current->process, apc->call.map_view.handle,
1255 process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1256 if (handle) apc->call.map_view.handle = handle;
1257 else
1259 release_object( process );
1260 process = NULL;
1263 break;
1264 case APC_CREATE_THREAD:
1265 process = get_process_from_handle( req->process, PROCESS_CREATE_THREAD );
1266 break;
1267 default:
1268 set_error( STATUS_INVALID_PARAMETER );
1269 break;
1272 if (thread)
1274 if (!queue_apc( NULL, thread, apc )) set_error( STATUS_THREAD_IS_TERMINATING );
1275 release_object( thread );
1277 else if (process)
1279 reply->self = (process == current->process);
1280 if (!reply->self)
1282 obj_handle_t handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 );
1283 if (handle)
1285 if (queue_apc( process, NULL, apc ))
1287 apc->caller = (struct thread *)grab_object( current );
1288 reply->handle = handle;
1290 else
1292 close_handle( current->process, handle );
1293 set_error( STATUS_PROCESS_IS_TERMINATING );
1297 release_object( process );
1300 release_object( apc );
1303 /* get next APC to call */
1304 DECL_HANDLER(get_apc)
1306 struct thread_apc *apc;
1307 int system_only = !req->alertable;
1309 if (req->prev)
1311 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->prev,
1312 0, &thread_apc_ops ))) return;
1313 apc->result = req->result;
1314 apc->executed = 1;
1315 if (apc->result.type == APC_CREATE_THREAD) /* transfer the handle to the caller process */
1317 obj_handle_t handle = duplicate_handle( current->process, apc->result.create_thread.handle,
1318 apc->caller->process, 0, 0, DUP_HANDLE_SAME_ACCESS );
1319 close_handle( current->process, apc->result.create_thread.handle );
1320 apc->result.create_thread.handle = handle;
1321 clear_error(); /* ignore errors from the above calls */
1323 else if (apc->result.type == APC_ASYNC_IO)
1325 if (apc->owner) async_set_result( apc->owner, apc->result.async_io.status );
1327 wake_up( &apc->obj, 0 );
1328 close_handle( current->process, req->prev );
1329 release_object( apc );
1332 if (current->suspend + current->process->suspend > 0) system_only = 1;
1334 for (;;)
1336 if (!(apc = thread_dequeue_apc( current, system_only )))
1338 /* no more APCs */
1339 set_error( STATUS_PENDING );
1340 return;
1342 /* Optimization: ignore APC_NONE calls, they are only used to
1343 * wake up a thread, but since we got here the thread woke up already.
1345 if (apc->call.type != APC_NONE) break;
1346 apc->executed = 1;
1347 wake_up( &apc->obj, 0 );
1348 release_object( apc );
1351 if ((reply->handle = alloc_handle( current->process, apc, SYNCHRONIZE, 0 )))
1352 reply->call = apc->call;
1353 release_object( apc );
1356 /* Get the result of an APC call */
1357 DECL_HANDLER(get_apc_result)
1359 struct thread_apc *apc;
1361 if (!(apc = (struct thread_apc *)get_handle_obj( current->process, req->handle,
1362 0, &thread_apc_ops ))) return;
1363 if (!apc->executed) set_error( STATUS_PENDING );
1364 else
1366 reply->result = apc->result;
1367 /* close the handle directly to avoid an extra round-trip */
1368 close_handle( current->process, req->handle );
1370 release_object( apc );
1373 /* retrieve the current context of a thread */
1374 DECL_HANDLER(get_thread_context)
1376 struct thread *thread;
1377 CONTEXT *context;
1379 if (get_reply_max_size() < sizeof(CONTEXT))
1381 set_error( STATUS_INVALID_PARAMETER );
1382 return;
1384 if (!(thread = get_thread_from_handle( req->handle, THREAD_GET_CONTEXT ))) return;
1386 if (req->suspend)
1388 if (thread != current || !thread->suspend_context)
1390 /* not suspended, shouldn't happen */
1391 set_error( STATUS_INVALID_PARAMETER );
1393 else
1395 if (thread->context == thread->suspend_context) thread->context = NULL;
1396 set_reply_data_ptr( thread->suspend_context, sizeof(CONTEXT) );
1397 thread->suspend_context = NULL;
1400 else if (thread != current && !thread->context)
1402 /* thread is not suspended, retry (if it's still running) */
1403 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1404 else set_error( STATUS_PENDING );
1406 else if ((context = set_reply_data_size( sizeof(CONTEXT) )))
1408 unsigned int flags = get_context_system_regs( req->flags );
1410 memset( context, 0, sizeof(CONTEXT) );
1411 context->ContextFlags = get_context_cpu_flag();
1412 if (thread->context) copy_context( context, thread->context, req->flags & ~flags );
1413 if (flags) get_thread_context( thread, context, flags );
1415 reply->self = (thread == current);
1416 release_object( thread );
1419 /* set the current context of a thread */
1420 DECL_HANDLER(set_thread_context)
1422 struct thread *thread;
1424 if (get_req_data_size() < sizeof(CONTEXT))
1426 set_error( STATUS_INVALID_PARAMETER );
1427 return;
1429 if (!(thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT ))) return;
1431 if (req->suspend)
1433 if (thread != current || thread->context)
1435 /* nested suspend or exception, shouldn't happen */
1436 set_error( STATUS_INVALID_PARAMETER );
1438 else if ((thread->suspend_context = mem_alloc( sizeof(CONTEXT) )))
1440 memcpy( thread->suspend_context, get_req_data(), sizeof(CONTEXT) );
1441 thread->context = thread->suspend_context;
1442 if (thread->debug_break) break_thread( thread );
1445 else if (thread != current && !thread->context)
1447 /* thread is not suspended, retry (if it's still running) */
1448 if (thread->state != RUNNING) set_error( STATUS_ACCESS_DENIED );
1449 else set_error( STATUS_PENDING );
1451 else
1453 const CONTEXT *context = get_req_data();
1454 unsigned int flags = get_context_system_regs( req->flags );
1456 if (flags) set_thread_context( thread, context, flags );
1457 if (thread->context && !get_error())
1458 copy_context( thread->context, context, req->flags & ~flags );
1460 reply->self = (thread == current);
1461 release_object( thread );
1464 /* fetch a selector entry for a thread */
1465 DECL_HANDLER(get_selector_entry)
1467 struct thread *thread;
1468 if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
1470 get_selector_entry( thread, req->entry, &reply->base, &reply->limit, &reply->flags );
1471 release_object( thread );