ANSI C fixes.
[wine] / server / thread.c
1 /*
2  * Server-side thread management
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  */
6
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <signal.h>
10 #include <stdio.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <sys/mman.h>
14 #include <sys/types.h>
15 #include <sys/uio.h>
16 #include <unistd.h>
17 #include <stdarg.h>
18
19
20 #include "winbase.h"
21 #include "winerror.h"
22
23 #include "handle.h"
24 #include "process.h"
25 #include "thread.h"
26 #include "request.h"
27
28
29 /* thread queues */
30
31 struct wait_queue_entry
32 {
33     struct wait_queue_entry *next;
34     struct wait_queue_entry *prev;
35     struct object           *obj;
36     struct thread           *thread;
37 };
38
39 struct thread_wait
40 {
41     int                     count;      /* count of objects */
42     int                     flags;
43     struct timeval          timeout;
44     struct timeout_user    *user;
45     struct wait_queue_entry queues[1];
46 };
47
48 /* asynchronous procedure calls */
49
50 struct thread_apc
51 {
52     void                   *func;    /* function to call in client */
53     void                   *param;   /* function param */
54 };
55 #define MAX_THREAD_APC  16  /* Max outstanding APCs for a thread */
56
57
58 /* thread operations */
59
60 static void dump_thread( struct object *obj, int verbose );
61 static int thread_signaled( struct object *obj, struct thread *thread );
62 static void destroy_thread( struct object *obj );
63
64 static const struct object_ops thread_ops =
65 {
66     sizeof(struct thread),
67     dump_thread,
68     add_queue,
69     remove_queue,
70     thread_signaled,
71     no_satisfied,
72     no_read_fd,
73     no_write_fd,
74     no_flush,
75     no_get_file_info,
76     destroy_thread
77 };
78
79 static struct thread *first_thread;
80
81 /* allocate the buffer for the communication with the client */
82 static int alloc_client_buffer( struct thread *thread )
83 {
84     int fd;
85
86     if ((fd = create_anonymous_file()) == -1) return -1;
87     if (ftruncate( fd, MAX_REQUEST_LENGTH ) == -1) goto error;
88     if ((thread->buffer = mmap( 0, MAX_REQUEST_LENGTH, PROT_READ | PROT_WRITE,
89                                 MAP_SHARED, fd, 0 )) == (void*)-1) goto error;
90     return fd;
91
92  error:
93     file_set_error();
94     if (fd != -1) close( fd );
95     return -1;
96 }
97
98 /* create a new thread */
99 static struct thread *create_thread( int fd, struct process *process, int suspend )
100 {
101     struct thread *thread;
102     int buf_fd;
103
104     if (!(thread = alloc_object( &thread_ops ))) return NULL;
105
106     thread->client      = NULL;
107     thread->unix_pid    = 0;  /* not known yet */
108     thread->teb         = NULL;
109     thread->mutex       = NULL;
110     thread->debug_ctx   = NULL;
111     thread->debug_first = NULL;
112     thread->debug_event = NULL;
113     thread->wait        = NULL;
114     thread->apc         = NULL;
115     thread->apc_count   = 0;
116     thread->error       = 0;
117     thread->state       = STARTING;
118     thread->exit_code   = 0x103;  /* STILL_ACTIVE */
119     thread->next        = NULL;
120     thread->prev        = NULL;
121     thread->priority    = THREAD_PRIORITY_NORMAL;
122     thread->affinity    = 1;
123     thread->suspend     = (suspend != 0);
124     thread->buffer      = (void *)-1;
125     thread->last_req    = REQ_GET_THREAD_BUFFER;
126
127     if (!first_thread)  /* creating the first thread */
128     {
129         current = thread;
130         thread->process = process = create_initial_process(); 
131         assert( process );
132     }
133     else thread->process = (struct process *)grab_object( process );
134
135     if ((thread->next = first_thread) != NULL) thread->next->prev = thread;
136     first_thread = thread;
137     add_process_thread( process, thread );
138
139     if ((buf_fd = alloc_client_buffer( thread )) == -1) goto error;
140     if (!(thread->client = add_client( fd, thread )))
141     {
142         close( buf_fd );
143         goto error;
144     }
145     set_reply_fd( thread, buf_fd );  /* send the fd to the client */
146     send_reply( thread );
147     return thread;
148
149  error:
150     remove_process_thread( process, thread );
151     release_object( thread );
152     return NULL;
153 }
154
155 /* create the initial thread and start the main server loop */
156 void create_initial_thread( int fd )
157 {
158     create_thread( fd, NULL, 0 );
159     select_loop();
160 }
161
162 /* destroy a thread when its refcount is 0 */
163 static void destroy_thread( struct object *obj )
164 {
165     struct thread *thread = (struct thread *)obj;
166     assert( obj->ops == &thread_ops );
167
168     assert( !thread->debug_ctx );  /* cannot still be debugging something */
169     release_object( thread->process );
170     if (thread->next) thread->next->prev = thread->prev;
171     if (thread->prev) thread->prev->next = thread->next;
172     else first_thread = thread->next;
173     if (thread->apc) free( thread->apc );
174     if (thread->buffer != (void *)-1) munmap( thread->buffer, MAX_REQUEST_LENGTH );
175 }
176
177 /* dump a thread on stdout for debugging purposes */
178 static void dump_thread( struct object *obj, int verbose )
179 {
180     struct thread *thread = (struct thread *)obj;
181     assert( obj->ops == &thread_ops );
182
183     fprintf( stderr, "Thread pid=%d teb=%p state=%d\n",
184              thread->unix_pid, thread->teb, thread->state );
185 }
186
187 static int thread_signaled( struct object *obj, struct thread *thread )
188 {
189     struct thread *mythread = (struct thread *)obj;
190     return (mythread->state == TERMINATED);
191 }
192
193 /* get a thread pointer from a thread id (and increment the refcount) */
194 struct thread *get_thread_from_id( void *id )
195 {
196     struct thread *t = first_thread;
197     while (t && (t != id)) t = t->next;
198     if (t) grab_object( t );
199     return t;
200 }
201
202 /* get a thread from a handle (and increment the refcount) */
203 struct thread *get_thread_from_handle( int handle, unsigned int access )
204 {
205     return (struct thread *)get_handle_obj( current->process, handle,
206                                             access, &thread_ops );
207 }
208
209 /* set all information about a thread */
210 static void set_thread_info( struct thread *thread,
211                              struct set_thread_info_request *req )
212 {
213     if (req->mask & SET_THREAD_INFO_PRIORITY)
214         thread->priority = req->priority;
215     if (req->mask & SET_THREAD_INFO_AFFINITY)
216     {
217         if (req->affinity != 1) set_error( ERROR_INVALID_PARAMETER );
218         else thread->affinity = req->affinity;
219     }
220 }
221
222 /* suspend a thread */
223 static int suspend_thread( struct thread *thread )
224 {
225     int old_count = thread->suspend;
226     if (thread->suspend < MAXIMUM_SUSPEND_COUNT)
227     {
228         if (!(thread->process->suspend + thread->suspend++))
229         {
230             if (thread->unix_pid) kill( thread->unix_pid, SIGSTOP );
231         }
232     }
233     return old_count;
234 }
235
236 /* resume a thread */
237 static int resume_thread( struct thread *thread )
238 {
239     int old_count = thread->suspend;
240     if (thread->suspend > 0)
241     {
242         if (!(--thread->suspend + thread->process->suspend))
243         {
244             if (thread->unix_pid) kill( thread->unix_pid, SIGCONT );
245         }
246     }
247     return old_count;
248 }
249
250 /* suspend all threads but the current */
251 void suspend_all_threads( void )
252 {
253     struct thread *thread;
254     for ( thread = first_thread; thread; thread = thread->next )
255         if ( thread != current )
256             suspend_thread( thread );
257 }
258
259 /* resume all threads but the current */
260 void resume_all_threads( void )
261 {
262     struct thread *thread;
263     for ( thread = first_thread; thread; thread = thread->next )
264         if ( thread != current )
265             resume_thread( thread );
266 }
267
268 /* add a thread to an object wait queue; return 1 if OK, 0 on error */
269 int add_queue( struct object *obj, struct wait_queue_entry *entry )
270 {
271     grab_object( obj );
272     entry->obj    = obj;
273     entry->prev   = obj->tail;
274     entry->next   = NULL;
275     if (obj->tail) obj->tail->next = entry;
276     else obj->head = entry;
277     obj->tail = entry;
278     return 1;
279 }
280
281 /* remove a thread from an object wait queue */
282 void remove_queue( struct object *obj, struct wait_queue_entry *entry )
283 {
284     if (entry->next) entry->next->prev = entry->prev;
285     else obj->tail = entry->prev;
286     if (entry->prev) entry->prev->next = entry->next;
287     else obj->head = entry->next;
288     release_object( obj );
289 }
290
291 /* finish waiting */
292 static void end_wait( struct thread *thread )
293 {
294     struct thread_wait *wait = thread->wait;
295     struct wait_queue_entry *entry;
296     int i;
297
298     assert( wait );
299     for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
300         entry->obj->ops->remove_queue( entry->obj, entry );
301     if (wait->user) remove_timeout_user( wait->user );
302     free( wait );
303     thread->wait = NULL;
304 }
305
306 /* build the thread wait structure */
307 static int wait_on( struct thread *thread, int count,
308                     int *handles, int flags, int timeout )
309 {
310     struct thread_wait *wait;
311     struct wait_queue_entry *entry;
312     struct object *obj;
313     int i;
314
315     if ((count < 0) || (count > MAXIMUM_WAIT_OBJECTS))
316     {
317         set_error( ERROR_INVALID_PARAMETER );
318         return 0;
319     }
320     if (!(wait = mem_alloc( sizeof(*wait) + (count-1) * sizeof(*entry) ))) return 0;
321     thread->wait  = wait;
322     wait->count   = count;
323     wait->flags   = flags;
324     wait->user    = NULL;
325     if (flags & SELECT_TIMEOUT) make_timeout( &wait->timeout, timeout );
326
327     for (i = 0, entry = wait->queues; i < count; i++, entry++)
328     {
329         if (!(obj = get_handle_obj( thread->process, handles[i],
330                                     SYNCHRONIZE, NULL )))
331         {
332             wait->count = i - 1;
333             end_wait( thread );
334             return 0;
335         }
336         entry->thread = thread;
337         if (!obj->ops->add_queue( obj, entry ))
338         {
339             wait->count = i - 1;
340             end_wait( thread );
341             return 0;
342         }
343         release_object( obj );
344     }
345     return 1;
346 }
347
348 /* check if the thread waiting condition is satisfied */
349 static int check_wait( struct thread *thread, int *signaled )
350 {
351     int i;
352     struct thread_wait *wait = thread->wait;
353     struct wait_queue_entry *entry = wait->queues;
354
355     assert( wait );
356     if (wait->flags & SELECT_ALL)
357     {
358         int not_ok = 0;
359         /* Note: we must check them all anyway, as some objects may
360          * want to do something when signaled, even if others are not */
361         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
362             not_ok |= !entry->obj->ops->signaled( entry->obj, thread );
363         if (not_ok) goto other_checks;
364         /* Wait satisfied: tell it to all objects */
365         *signaled = 0;
366         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
367             if (entry->obj->ops->satisfied( entry->obj, thread ))
368                 *signaled = STATUS_ABANDONED_WAIT_0;
369         return 1;
370     }
371     else
372     {
373         for (i = 0, entry = wait->queues; i < wait->count; i++, entry++)
374         {
375             if (!entry->obj->ops->signaled( entry->obj, thread )) continue;
376             /* Wait satisfied: tell it to the object */
377             *signaled = i;
378             if (entry->obj->ops->satisfied( entry->obj, thread ))
379                 *signaled = i + STATUS_ABANDONED_WAIT_0;
380             return 1;
381         }
382     }
383
384  other_checks:
385     if ((wait->flags & SELECT_ALERTABLE) && thread->apc)
386     {
387         *signaled = STATUS_USER_APC;
388         return 1;
389     }
390     if (wait->flags & SELECT_TIMEOUT)
391     {
392         struct timeval now;
393         gettimeofday( &now, NULL );
394         if ((now.tv_sec > wait->timeout.tv_sec) ||
395             ((now.tv_sec == wait->timeout.tv_sec) &&
396              (now.tv_usec >= wait->timeout.tv_usec)))
397         {
398             *signaled = STATUS_TIMEOUT;
399             return 1;
400         }
401     }
402     return 0;
403 }
404
405 /* attempt to wake up a thread */
406 /* return 1 if OK, 0 if the wait condition is still not satisfied */
407 static int wake_thread( struct thread *thread )
408 {
409     struct select_request *req = get_req_ptr( thread );
410
411     if (!check_wait( thread, &req->signaled )) return 0;
412     end_wait( thread );
413     return 1;
414 }
415
416 /* sleep on a list of objects */
417 static void sleep_on( struct thread *thread, int count, int *handles, int flags, int timeout )
418 {
419     struct select_request *req;
420     assert( !thread->wait );
421     if (!wait_on( thread, count, handles, flags, timeout )) goto error;
422     if (wake_thread( thread )) return;
423     /* now we need to wait */
424     if (flags & SELECT_TIMEOUT)
425     {
426         if (!(thread->wait->user = add_timeout_user( &thread->wait->timeout,
427                                                      call_timeout_handler, thread )))
428             goto error;
429     }
430     thread->state = SLEEPING;
431     return;
432
433  error:
434     req = get_req_ptr( thread );
435     req->signaled = -1;
436 }
437
438 /* timeout for the current thread */
439 void thread_timeout(void)
440 {
441     struct select_request *req = get_req_ptr( current );
442
443     assert( current->wait );
444     current->wait->user = NULL;
445     end_wait( current );
446     req->signaled = STATUS_TIMEOUT;
447     send_reply( current );
448 }
449
450 /* attempt to wake threads sleeping on the object wait queue */
451 void wake_up( struct object *obj, int max )
452 {
453     struct wait_queue_entry *entry = obj->head;
454
455     while (entry)
456     {
457         struct thread *thread = entry->thread;
458         entry = entry->next;
459         if (wake_thread( thread ))
460         {
461             send_reply( thread );
462             if (max && !--max) break;
463         }
464     }
465 }
466
467 /* queue an async procedure call */
468 static int thread_queue_apc( struct thread *thread, void *func, void *param )
469 {
470     struct thread_apc *apc;
471     if (!thread->apc)
472     {
473         if (!(thread->apc = mem_alloc( MAX_THREAD_APC * sizeof(*apc) )))
474             return 0;
475         thread->apc_count = 0;
476     }
477     else if (thread->apc_count >= MAX_THREAD_APC) return 0;
478     thread->apc[thread->apc_count].func  = func;
479     thread->apc[thread->apc_count].param = param;
480     thread->apc_count++;
481     if (thread->wait)
482     {
483         if (wake_thread( thread )) send_reply( thread );
484     }
485     return 1;
486 }
487
488 /* kill a thread on the spot */
489 void kill_thread( struct thread *thread, int exit_code )
490 {
491     if (thread->state == TERMINATED) return;  /* already killed */
492     if (thread->unix_pid) kill( thread->unix_pid, SIGTERM );
493     remove_client( thread->client, exit_code ); /* this will call thread_killed */
494 }
495
496 /* a thread has been killed */
497 void thread_killed( struct thread *thread, int exit_code )
498 {
499     thread->state = TERMINATED;
500     thread->exit_code = exit_code;
501     if (thread->wait) end_wait( thread );
502     debug_exit_thread( thread, exit_code );
503     abandon_mutexes( thread );
504     remove_process_thread( thread->process, thread );
505     wake_up( &thread->obj, 0 );
506     release_object( thread );
507 }
508
509 /* create a new thread */
510 DECL_HANDLER(new_thread)
511 {
512     struct thread *thread;
513     struct process *process;
514
515     if ((process = get_process_from_id( req->pid )))
516     {
517         if ((fd = dup(fd)) != -1)
518         {
519             if ((thread = create_thread( fd, process, req->suspend )))
520             {
521                 req->tid = thread;
522                 if ((req->handle = alloc_handle( current->process, thread,
523                                                  THREAD_ALL_ACCESS, req->inherit )) == -1)
524                     release_object( thread );
525                 /* else will be released when the thread gets killed */
526             }
527             else close( fd );
528         }
529         else file_set_error();
530         release_object( process );
531     }
532 }
533
534 /* retrieve the thread buffer file descriptor */
535 DECL_HANDLER(get_thread_buffer)
536 {
537     fatal_protocol_error( current, "get_thread_buffer: should never get called directly\n" );
538 }
539
540 /* initialize a new thread */
541 DECL_HANDLER(init_thread)
542 {
543     if (current->state != STARTING)
544     {
545         fatal_protocol_error( current, "init_thread: already running\n" );
546         return;
547     }
548     current->state    = RUNNING;
549     current->unix_pid = req->unix_pid;
550     current->teb      = req->teb;
551     if (current->suspend + current->process->suspend > 0)
552         kill( current->unix_pid, SIGSTOP );
553     req->pid = current->process;
554     req->tid = current;
555 }
556
557 /* terminate a thread */
558 DECL_HANDLER(terminate_thread)
559 {
560     struct thread *thread;
561
562     if ((thread = get_thread_from_handle( req->handle, THREAD_TERMINATE )))
563     {
564         kill_thread( thread, req->exit_code );
565         release_object( thread );
566     }
567 }
568
569 /* fetch information about a thread */
570 DECL_HANDLER(get_thread_info)
571 {
572     struct thread *thread;
573
574     if ((thread = get_thread_from_handle( req->handle, THREAD_QUERY_INFORMATION )))
575     {
576         req->tid       = thread;
577         req->exit_code = thread->exit_code;
578         req->priority  = thread->priority;
579         release_object( thread );
580     }
581 }
582
583 /* set information about a thread */
584 DECL_HANDLER(set_thread_info)
585 {
586     struct thread *thread;
587
588     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_INFORMATION )))
589     {
590         set_thread_info( thread, req );
591         release_object( thread );
592     }
593 }
594
595 /* suspend a thread */
596 DECL_HANDLER(suspend_thread)
597 {
598     struct thread *thread;
599
600     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
601     {
602         req->count = suspend_thread( thread );
603         release_object( thread );
604     }
605 }
606
607 /* resume a thread */
608 DECL_HANDLER(resume_thread)
609 {
610     struct thread *thread;
611
612     if ((thread = get_thread_from_handle( req->handle, THREAD_SUSPEND_RESUME )))
613     {
614         req->count = resume_thread( thread );
615         release_object( thread );
616     }
617 }
618
619 /* select on a handle list */
620 DECL_HANDLER(select)
621 {
622     sleep_on( current, req->count, req->handles, req->flags, req->timeout );
623 }
624
625 /* queue an APC for a thread */
626 DECL_HANDLER(queue_apc)
627 {
628     struct thread *thread;
629     if ((thread = get_thread_from_handle( req->handle, THREAD_SET_CONTEXT )))
630     {
631         thread_queue_apc( thread, req->func, req->param );
632         release_object( thread );
633     }
634 }
635
636 /* get list of APC to call */
637 DECL_HANDLER(get_apcs)
638 {
639     if ((req->count = current->apc_count))
640     {
641         memcpy( req->apcs, current->apc, current->apc_count * sizeof(*current->apc) );
642         free( current->apc );
643         current->apc = NULL;
644         current->apc_count = 0;
645     }
646 }