Fixed ANSI C related compile problems.
[wine] / server / process.c
1 /*
2  * Server-side process management
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  */
6
7 #include "config.h"
8
9 #include <assert.h>
10 #include <errno.h>
11 #include <limits.h>
12 #include <signal.h>
13 #include <string.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <sys/time.h>
17 #ifdef HAVE_SYS_SOCKET_H
18 # include <sys/socket.h>
19 #endif
20 #include <unistd.h>
21
22 #include "winbase.h"
23 #include "winnt.h"
24
25 #include "handle.h"
26 #include "process.h"
27 #include "thread.h"
28 #include "request.h"
29
30 /* process structure */
31
32 static struct process *first_process;
33 static int running_processes;
34
35 /* process operations */
36
37 static void process_dump( struct object *obj, int verbose );
38 static int process_signaled( struct object *obj, struct thread *thread );
39 static void process_destroy( struct object *obj );
40
41 static const struct object_ops process_ops =
42 {
43     sizeof(struct process),      /* size */
44     process_dump,                /* dump */
45     add_queue,                   /* add_queue */
46     remove_queue,                /* remove_queue */
47     process_signaled,            /* signaled */
48     no_satisfied,                /* satisfied */
49     NULL,                        /* get_poll_events */
50     NULL,                        /* poll_event */
51     no_read_fd,                  /* get_read_fd */
52     no_write_fd,                 /* get_write_fd */
53     no_flush,                    /* flush */
54     no_get_file_info,            /* get_file_info */
55     process_destroy              /* destroy */
56 };
57
58 /* set the process creation info */
59 static int set_creation_info( struct process *process, struct new_process_request *req,
60                               const char *cmd_line, size_t len )
61 {
62     if (!(process->info = mem_alloc( sizeof(*process->info) + len ))) return 0;
63     if (req)
64     {
65         /* copy the request structure */
66         memcpy( process->info, req, sizeof(*req) );
67     }
68     else  /* no request, use defaults */
69     {
70         req = process->info;
71         req->inherit      = 0;
72         req->inherit_all  = 0;
73         req->create_flags = CREATE_NEW_CONSOLE;
74         req->start_flags  = STARTF_USESTDHANDLES;
75         req->exe_file     = -1;
76         req->hstdin       = -1;
77         req->hstdout      = -1;
78         req->hstderr      = -1;
79         req->event        = -1;
80         req->cmd_show     = 0;
81         req->env_ptr      = NULL;
82     }
83     memcpy( process->info->cmdline, cmd_line, len );
84     process->info->cmdline[len] = 0;
85     process->create_flags = process->info->create_flags;
86     return 1;
87 }
88
89 /* set the console and stdio handles for a newly created process */
90 static int set_process_console( struct process *process, struct process *parent )
91 {
92     struct new_process_request *info = process->info;
93
94     if (process->create_flags & CREATE_NEW_CONSOLE)
95     {
96         if (!alloc_console( process )) return 0;
97     }
98     else if (!(process->create_flags & DETACHED_PROCESS))
99     {
100         if (parent->console_in) process->console_in = grab_object( parent->console_in );
101         if (parent->console_out) process->console_out = grab_object( parent->console_out );
102     }
103     if (parent)
104     {
105         if (!info->inherit_all && !(info->start_flags & STARTF_USESTDHANDLES))
106         {
107             /* duplicate the handle from the parent into this process */
108             info->hstdin  = duplicate_handle( parent, info->hstdin, process,
109                                               0, TRUE, DUPLICATE_SAME_ACCESS );
110             info->hstdout = duplicate_handle( parent, info->hstdout, process,
111                                               0, TRUE, DUPLICATE_SAME_ACCESS );
112             info->hstderr = duplicate_handle( parent, info->hstderr, process,
113                                               0, TRUE, DUPLICATE_SAME_ACCESS );
114         }
115     }
116     else
117     {
118         /* no parent, use handles to the console for stdio */
119         info->hstdin  = alloc_handle( process, process->console_in,
120                                       GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, 1 );
121         info->hstdout = alloc_handle( process, process->console_out,
122                                       GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, 1 );
123         info->hstderr = alloc_handle( process, process->console_out,
124                                       GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, 1 );
125     }
126     return 1;
127 }
128
129 /* create a new process and its main thread */
130 struct thread *create_process( int fd, struct process *parent,
131                                struct new_process_request *req,
132                                const char *cmd_line, size_t len )
133 {
134     struct process *process;
135     struct thread *thread = NULL;
136
137     if (!(process = alloc_object( &process_ops, -1 )))
138     {
139         close( fd );
140         return NULL;
141     }
142     process->next            = NULL;
143     process->prev            = NULL;
144     process->thread_list     = NULL;
145     process->debugger        = NULL;
146     process->handles         = NULL;
147     process->exit_code       = STILL_ACTIVE;
148     process->running_threads = 0;
149     process->priority        = NORMAL_PRIORITY_CLASS;
150     process->affinity        = 1;
151     process->suspend         = 0;
152     process->create_flags    = 0;
153     process->console_in      = NULL;
154     process->console_out     = NULL;
155     process->init_event      = NULL;
156     process->info            = NULL;
157     process->ldt_copy        = NULL;
158     process->ldt_flags       = NULL;
159     process->exe.next        = NULL;
160     process->exe.prev        = NULL;
161     process->exe.file        = NULL;
162     process->exe.dbg_offset  = 0;
163     process->exe.dbg_size    = 0;
164     gettimeofday( &process->start_time, NULL );
165     if ((process->next = first_process) != NULL) process->next->prev = process;
166     first_process = process;
167
168     /* copy the request structure */
169     if (!set_creation_info( process, req, cmd_line, len )) goto error;
170
171     if (process->info->inherit_all)
172         process->handles = copy_handle_table( process, parent );
173     else
174         process->handles = alloc_handle_table( process, 0 );
175     if (!process->handles) goto error;
176
177     /* alloc a handle for the process itself */
178     alloc_handle( process, process, PROCESS_ALL_ACCESS, 0 );
179
180     /* retrieve the main exe file */
181     if (process->info->exe_file != -1)
182     {
183         if (!(process->exe.file = get_file_obj( parent, process->info->exe_file,
184                                                 GENERIC_READ ))) goto error;
185         process->info->exe_file = -1;
186     }
187
188     /* get the init done event */
189     if (process->info->event != -1)
190     {
191         if (!(process->init_event = get_event_obj( parent, process->info->event,
192                                                    EVENT_MODIFY_STATE ))) goto error;
193     }
194
195     /* set the process console */
196     if (!set_process_console( process, parent )) goto error;
197
198     /* create the main thread */
199     if (!(thread = create_thread( fd, process, (process->create_flags & CREATE_SUSPENDED) != 0)))
200         goto error;
201
202     /* attach to the debugger if requested */
203     if (process->create_flags & (DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS))
204         set_process_debugger( process, current );
205     else if (parent && parent->debugger && !(parent->create_flags & DEBUG_ONLY_THIS_PROCESS))
206         set_process_debugger( process, parent->debugger );
207
208     release_object( process );
209     return thread;
210
211  error:
212     close( fd );
213     free_console( process );
214     if (process->handles) release_object( process->handles );
215     release_object( process );
216     return NULL;
217 }
218
219 /* destroy a process when its refcount is 0 */
220 static void process_destroy( struct object *obj )
221 {
222     struct process *process = (struct process *)obj;
223     assert( obj->ops == &process_ops );
224
225     /* we can't have a thread remaining */
226     assert( !process->thread_list );
227     if (process->next) process->next->prev = process->prev;
228     if (process->prev) process->prev->next = process->next;
229     else first_process = process->next;
230     if (process->info) free( process->info );
231     if (process->init_event) release_object( process->init_event );
232     if (process->exe.file) release_object( process->exe.file );
233 }
234
235 /* dump a process on stdout for debugging purposes */
236 static void process_dump( struct object *obj, int verbose )
237 {
238     struct process *process = (struct process *)obj;
239     assert( obj->ops == &process_ops );
240
241     fprintf( stderr, "Process next=%p prev=%p console=%p/%p handles=%p\n",
242              process->next, process->prev, process->console_in, process->console_out,
243              process->handles );
244 }
245
246 static int process_signaled( struct object *obj, struct thread *thread )
247 {
248     struct process *process = (struct process *)obj;
249     return !process->running_threads;
250 }
251
252
253 /* get a process from an id (and increment the refcount) */
254 struct process *get_process_from_id( void *id )
255 {
256     struct process *p = first_process;
257     while (p && (p != id)) p = p->next;
258     if (p) grab_object( p );
259     else set_error( STATUS_INVALID_PARAMETER );
260     return p;
261 }
262
263 /* get a process from a handle (and increment the refcount) */
264 struct process *get_process_from_handle( int handle, unsigned int access )
265 {
266     return (struct process *)get_handle_obj( current->process, handle,
267                                              access, &process_ops );
268 }
269
270 /* add a dll to a process list */
271 static struct process_dll *process_load_dll( struct process *process, struct file *file,
272                                              void *base )
273 {
274     struct process_dll *dll;
275
276     /* make sure we don't already have one with the same base address */
277     for (dll = process->exe.next; dll; dll = dll->next) if (dll->base == base)
278     {
279         set_error( STATUS_INVALID_PARAMETER );
280         return NULL;
281     }
282
283     if ((dll = mem_alloc( sizeof(*dll) )))
284     {
285         dll->prev = &process->exe;
286         dll->file = NULL;
287         dll->base = base;
288         if (file) dll->file = (struct file *)grab_object( file );
289         if ((dll->next = process->exe.next)) dll->next->prev = dll;
290         process->exe.next = dll;
291     }
292     return dll;
293 }
294
295 /* remove a dll from a process list */
296 static void process_unload_dll( struct process *process, void *base )
297 {
298     struct process_dll *dll;
299
300     for (dll = process->exe.next; dll; dll = dll->next)
301     {
302         if (dll->base == base)
303         {
304             if (dll->file) release_object( dll->file );
305             if (dll->next) dll->next->prev = dll->prev;
306             if (dll->prev) dll->prev->next = dll->next;
307             free( dll );
308             generate_debug_event( current, UNLOAD_DLL_DEBUG_EVENT, base );
309             return;
310         }
311     }
312     set_error( STATUS_INVALID_PARAMETER );
313 }
314
315 /* a process has been killed (i.e. its last thread died) */
316 static void process_killed( struct process *process )
317 {
318     assert( !process->thread_list );
319     gettimeofday( &process->end_time, NULL );
320     release_object( process->handles );
321     process->handles = NULL;
322     free_console( process );
323     while (process->exe.next)
324     {
325         struct process_dll *dll = process->exe.next;
326         process->exe.next = dll->next;
327         if (dll->file) release_object( dll->file );
328         free( dll );
329     }
330     if (process->exe.file) release_object( process->exe.file );
331     process->exe.file = NULL;
332     wake_up( &process->obj, 0 );
333     if (!--running_processes)
334     {
335         /* last process died, close global handles */
336         close_global_handles();
337         /* this will cause the select loop to terminate */
338         if (!persistent_server) close_master_socket();
339     }
340 }
341
342 /* add a thread to a process running threads list */
343 void add_process_thread( struct process *process, struct thread *thread )
344 {
345     thread->proc_next = process->thread_list;
346     thread->proc_prev = NULL;
347     if (thread->proc_next) thread->proc_next->proc_prev = thread;
348     process->thread_list = thread;
349     if (!process->running_threads++) running_processes++;
350     grab_object( thread );
351 }
352
353 /* remove a thread from a process running threads list */
354 void remove_process_thread( struct process *process, struct thread *thread )
355 {
356     assert( process->running_threads > 0 );
357     assert( process->thread_list );
358
359     if (thread->proc_next) thread->proc_next->proc_prev = thread->proc_prev;
360     if (thread->proc_prev) thread->proc_prev->proc_next = thread->proc_next;
361     else process->thread_list = thread->proc_next;
362
363     if (!--process->running_threads)
364     {
365         /* we have removed the last running thread, exit the process */
366         process->exit_code = thread->exit_code;
367         generate_debug_event( thread, EXIT_PROCESS_DEBUG_EVENT, process );
368         process_killed( process );
369     }
370     else generate_debug_event( thread, EXIT_THREAD_DEBUG_EVENT, thread );
371     release_object( thread );
372 }
373
374 /* suspend all the threads of a process */
375 void suspend_process( struct process *process )
376 {
377     if (!process->suspend++)
378     {
379         struct thread *thread = process->thread_list;
380         for (; thread; thread = thread->proc_next)
381         {
382             if (!thread->suspend) stop_thread( thread );
383         }
384     }
385 }
386
387 /* resume all the threads of a process */
388 void resume_process( struct process *process )
389 {
390     assert (process->suspend > 0);
391     if (!--process->suspend)
392     {
393         struct thread *thread = process->thread_list;
394         for (; thread; thread = thread->proc_next)
395         {
396             if (!thread->suspend) continue_thread( thread );
397         }
398     }
399 }
400
401 /* kill a process on the spot */
402 static void kill_process( struct process *process, struct thread *skip, int exit_code )
403 {
404     struct thread *thread = process->thread_list;
405     while (thread)
406     {
407         struct thread *next = thread->proc_next;
408         thread->exit_code = exit_code;
409         if (thread != skip) kill_thread( thread, 1 );
410         thread = next;
411     }
412 }
413
414 /* kill all processes being debugged by a given thread */
415 void kill_debugged_processes( struct thread *debugger, int exit_code )
416 {
417     for (;;)  /* restart from the beginning of the list every time */
418     {
419         struct process *process = first_process;
420         /* find the first process being debugged by 'debugger' and still running */
421         while (process && (process->debugger != debugger || !process->running_threads))
422             process = process->next;
423         if (!process) return;
424         process->debugger = NULL;
425         kill_process( process, NULL, exit_code );
426     }
427 }
428
429 /* get all information about a process */
430 static void get_process_info( struct process *process, struct get_process_info_request *req )
431 {
432     req->pid              = process;
433     req->debugged         = (process->debugger != 0);
434     req->exit_code        = process->exit_code;
435     req->priority         = process->priority;
436     req->process_affinity = process->affinity;
437     req->system_affinity  = 1;
438 }
439
440 /* set all information about a process */
441 static void set_process_info( struct process *process,
442                               struct set_process_info_request *req )
443 {
444     if (req->mask & SET_PROCESS_INFO_PRIORITY)
445         process->priority = req->priority;
446     if (req->mask & SET_PROCESS_INFO_AFFINITY)
447     {
448         if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
449         else process->affinity = req->affinity;
450     }
451 }
452
453 /* read data from a process memory space */
454 /* len is the total size (in ints), max is the size we can actually store in the output buffer */
455 /* we read the total size in all cases to check for permissions */
456 static void read_process_memory( struct process *process, const int *addr,
457                                  size_t len, size_t max, int *dest )
458 {
459     struct thread *thread = process->thread_list;
460
461     if ((unsigned int)addr % sizeof(int))  /* address must be aligned */
462     {
463         set_error( STATUS_INVALID_PARAMETER );
464         return;
465     }
466     if (!thread)  /* process is dead */
467     {
468         set_error( STATUS_ACCESS_DENIED );
469         return;
470     }
471     if (suspend_for_ptrace( thread ))
472     {
473         while (len > 0 && max)
474         {
475             if (read_thread_int( thread, addr++, dest++ ) == -1) goto done;
476             max--;
477             len--;
478         }
479         /* check the rest for read permission */
480         if (len > 0)
481         {
482             int dummy, page = get_page_size() / sizeof(int);
483             while (len >= page)
484             {
485                 addr += page;
486                 len -= page;
487                 if (read_thread_int( thread, addr - 1, &dummy ) == -1) goto done;
488             }
489             if (len && (read_thread_int( thread, addr + len - 1, &dummy ) == -1)) goto done;
490         }
491     done:
492         resume_thread( thread );
493     }
494 }
495
496 /* write data to a process memory space */
497 /* len is the total size (in ints), max is the size we can actually read from the input buffer */
498 /* we check the total size for write permissions */
499 static void write_process_memory( struct process *process, int *addr, size_t len,
500                                   size_t max, unsigned int first_mask,
501                                   unsigned int last_mask, const int *src )
502 {
503     struct thread *thread = process->thread_list;
504
505     if (!len || ((unsigned int)addr % sizeof(int)))  /* address must be aligned */
506     {
507         set_error( STATUS_INVALID_PARAMETER );
508         return;
509     }
510     if (!thread)  /* process is dead */
511     {
512         set_error( STATUS_ACCESS_DENIED );
513         return;
514     }
515     if (suspend_for_ptrace( thread ))
516     {
517         /* first word is special */
518         if (len > 1)
519         {
520             if (write_thread_int( thread, addr++, *src++, first_mask ) == -1) goto done;
521             len--;
522             max--;
523         }
524         else last_mask &= first_mask;
525
526         while (len > 1 && max)
527         {
528             if (write_thread_int( thread, addr++, *src++, ~0 ) == -1) goto done;
529             max--;
530             len--;
531         }
532
533         if (max)
534         {
535             /* last word is special too */
536             if (write_thread_int( thread, addr, *src, last_mask ) == -1) goto done;
537         }
538         else
539         {
540             /* check the rest for write permission */
541             int page = get_page_size() / sizeof(int);
542             while (len >= page)
543             {
544                 addr += page;
545                 len -= page;
546                 if (write_thread_int( thread, addr - 1, 0, 0 ) == -1) goto done;
547             }
548             if (len && (write_thread_int( thread, addr + len - 1, 0, 0 ) == -1)) goto done;
549         }
550     done:
551         resume_thread( thread );
552     }
553 }
554
555 /* take a snapshot of currently running processes */
556 struct process_snapshot *process_snap( int *count )
557 {
558     struct process_snapshot *snapshot, *ptr;
559     struct process *process;
560     if (!running_processes) return NULL;
561     if (!(snapshot = mem_alloc( sizeof(*snapshot) * running_processes )))
562         return NULL;
563     ptr = snapshot;
564     for (process = first_process; process; process = process->next)
565     {
566         if (!process->running_threads) continue;
567         ptr->process  = process;
568         ptr->threads  = process->running_threads;
569         ptr->priority = process->priority;
570         grab_object( process );
571         ptr++;
572     }
573     *count = running_processes;
574     return snapshot;
575 }
576
577 /* create a new process */
578 DECL_HANDLER(new_process)
579 {
580     size_t len = get_req_strlen( req->cmdline );
581     struct thread *thread;
582     int sock[2];
583
584     req->phandle = -1;
585     req->thandle = -1;
586     req->pid     = NULL;
587     req->tid     = NULL;
588
589     if (socketpair( AF_UNIX, SOCK_STREAM, 0, sock ) == -1)
590     {
591         file_set_error();
592         return;
593     }
594
595     if ((thread = create_process( sock[0], current->process, req, req->cmdline, len )))
596     {
597         int phandle = alloc_handle( current->process, thread->process,
598                                     PROCESS_ALL_ACCESS, req->inherit );
599         if ((req->phandle = phandle) != -1)
600         {
601             if ((req->thandle = alloc_handle( current->process, thread,
602                                               THREAD_ALL_ACCESS, req->inherit )) != -1)
603             {
604                 /* thread object will be released when the thread gets killed */
605                 set_reply_fd( current, sock[1] );
606                 req->pid = thread->process;
607                 req->tid = thread;
608                 return;
609             }
610             close_handle( current->process, phandle );
611         }
612         release_object( thread );
613     }
614     close( sock[1] );
615 }
616
617 /* initialize a new process */
618 DECL_HANDLER(init_process)
619 {
620     struct new_process_request *info;
621
622     if (!current->unix_pid)
623     {
624         fatal_protocol_error( current, "init_process: init_thread not called yet\n" );
625         return;
626     }
627     if (!(info = current->process->info))
628     {
629         fatal_protocol_error( current, "init_process: called twice\n" );
630         return;
631     }
632     current->process->ldt_copy  = req->ldt_copy;
633     current->process->ldt_flags = req->ldt_flags;
634     current->process->info = NULL;
635     req->exe_file    = -1;
636     req->start_flags = info->start_flags;
637     req->hstdin      = info->hstdin;
638     req->hstdout     = info->hstdout;
639     req->hstderr     = info->hstderr;
640     req->cmd_show    = info->cmd_show;
641     req->env_ptr     = info->env_ptr;
642     strcpy( req->cmdline, info->cmdline );
643     if (current->process->exe.file)
644         req->exe_file = alloc_handle( current->process, current->process->exe.file,
645                                       GENERIC_READ, 0 );
646     free( info );
647 }
648
649 /* signal the end of the process initialization */
650 DECL_HANDLER(init_process_done)
651 {
652     struct process *process = current->process;
653     if (!process->init_event)
654     {
655         fatal_protocol_error( current, "init_process_done: no event\n" );
656         return;
657     }
658     current->entry    = req->entry;
659     process->exe.base = req->module;
660     generate_startup_debug_events( current->process );
661     set_event( process->init_event );
662     release_object( process->init_event );
663     process->init_event = NULL;
664     if (current->suspend + current->process->suspend > 0) stop_thread( current );
665     req->debugged = (current->process->debugger != 0);
666 }
667
668 /* open a handle to a process */
669 DECL_HANDLER(open_process)
670 {
671     struct process *process = get_process_from_id( req->pid );
672     req->handle = -1;
673     if (process)
674     {
675         req->handle = alloc_handle( current->process, process, req->access, req->inherit );
676         release_object( process );
677     }
678 }
679
680 /* terminate a process */
681 DECL_HANDLER(terminate_process)
682 {
683     struct process *process;
684
685     if ((process = get_process_from_handle( req->handle, PROCESS_TERMINATE )))
686     {
687         req->self = (current->process == process);
688         kill_process( process, current, req->exit_code );
689         release_object( process );
690     }
691 }
692
693 /* fetch information about a process */
694 DECL_HANDLER(get_process_info)
695 {
696     struct process *process;
697
698     if ((process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION )))
699     {
700         get_process_info( process, req );
701         release_object( process );
702     }
703 }
704
705 /* set information about a process */
706 DECL_HANDLER(set_process_info)
707 {
708     struct process *process;
709
710     if ((process = get_process_from_handle( req->handle, PROCESS_SET_INFORMATION )))
711     {
712         set_process_info( process, req );
713         release_object( process );
714     }
715 }
716
717 /* read data from a process address space */
718 DECL_HANDLER(read_process_memory)
719 {
720     struct process *process;
721
722     if ((process = get_process_from_handle( req->handle, PROCESS_VM_READ )))
723     {
724         read_process_memory( process, req->addr, req->len,
725                              get_req_size( req->data, sizeof(int) ), req->data );
726         release_object( process );
727     }
728 }
729
730 /* write data to a process address space */
731 DECL_HANDLER(write_process_memory)
732 {
733     struct process *process;
734
735     if ((process = get_process_from_handle( req->handle, PROCESS_VM_WRITE )))
736     {
737         write_process_memory( process, req->addr, req->len, get_req_size( req->data, sizeof(int) ),
738                               req->first_mask, req->last_mask, req->data );
739         release_object( process );
740     }
741 }
742
743 /* notify the server that a dll has been loaded */
744 DECL_HANDLER(load_dll)
745 {
746     struct process_dll *dll;
747     struct file *file = NULL;
748
749     if ((req->handle != -1) &&
750         !(file = get_file_obj( current->process, req->handle, GENERIC_READ ))) return;
751     
752     if ((dll = process_load_dll( current->process, file, req->base )))
753     {
754         dll->dbg_offset = req->dbg_offset;
755         dll->dbg_size   = req->dbg_size;
756         dll->name       = req->name;
757         /* only generate event if initialization is done */
758         if (!current->process->init_event)
759             generate_debug_event( current, LOAD_DLL_DEBUG_EVENT, dll );
760     }
761     if (file) release_object( file );
762 }
763
764 /* notify the server that a dll is being unloaded */
765 DECL_HANDLER(unload_dll)
766 {
767     process_unload_dll( current->process, req->base );
768 }