imagehlp: Win64 printf format warning fixes.
[wine] / server / process.c
1 /*
2  * Server-side process management
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <limits.h>
26 #include <signal.h>
27 #include <string.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <sys/time.h>
32 #ifdef HAVE_SYS_SOCKET_H
33 # include <sys/socket.h>
34 #endif
35 #include <unistd.h>
36 #ifdef HAVE_POLL_H
37 #include <poll.h>
38 #endif
39
40 #include "ntstatus.h"
41 #define WIN32_NO_STATUS
42 #include "winternl.h"
43
44 #include "file.h"
45 #include "handle.h"
46 #include "process.h"
47 #include "thread.h"
48 #include "request.h"
49 #include "console.h"
50 #include "user.h"
51 #include "security.h"
52
53 /* process structure */
54
55 static struct list process_list = LIST_INIT(process_list);
56 static int running_processes;
57
58 /* process operations */
59
60 static void process_dump( struct object *obj, int verbose );
61 static int process_signaled( struct object *obj, struct thread *thread );
62 static unsigned int process_map_access( struct object *obj, unsigned int access );
63 static void process_poll_event( struct fd *fd, int event );
64 static void process_destroy( struct object *obj );
65
66 static const struct object_ops process_ops =
67 {
68     sizeof(struct process),      /* size */
69     process_dump,                /* dump */
70     add_queue,                   /* add_queue */
71     remove_queue,                /* remove_queue */
72     process_signaled,            /* signaled */
73     no_satisfied,                /* satisfied */
74     no_signal,                   /* signal */
75     no_get_fd,                   /* get_fd */
76     process_map_access,          /* map_access */
77     no_lookup_name,              /* lookup_name */
78     no_close_handle,             /* close_handle */
79     process_destroy              /* destroy */
80 };
81
82 static const struct fd_ops process_fd_ops =
83 {
84     NULL,                        /* get_poll_events */
85     process_poll_event,          /* poll_event */
86     no_flush,                    /* flush */
87     no_get_file_info,            /* get_file_info */
88     no_queue_async,              /* queue_async */
89     no_cancel_async              /* cancel async */
90 };
91
92 /* process startup info */
93
94 struct startup_info
95 {
96     struct object       obj;          /* object header */
97     obj_handle_t        hstdin;       /* handle for stdin */
98     obj_handle_t        hstdout;      /* handle for stdout */
99     obj_handle_t        hstderr;      /* handle for stderr */
100     struct file        *exe_file;     /* file handle for main exe */
101     struct process     *process;      /* created process */
102     data_size_t         data_size;    /* size of startup data */
103     void               *data;         /* data for startup info */
104 };
105
106 static void startup_info_dump( struct object *obj, int verbose );
107 static int startup_info_signaled( struct object *obj, struct thread *thread );
108 static void startup_info_destroy( struct object *obj );
109
110 static const struct object_ops startup_info_ops =
111 {
112     sizeof(struct startup_info),   /* size */
113     startup_info_dump,             /* dump */
114     add_queue,                     /* add_queue */
115     remove_queue,                  /* remove_queue */
116     startup_info_signaled,         /* signaled */
117     no_satisfied,                  /* satisfied */
118     no_signal,                     /* signal */
119     no_get_fd,                     /* get_fd */
120     no_map_access,                 /* map_access */
121     no_lookup_name,                /* lookup_name */
122     no_close_handle,               /* close_handle */
123     startup_info_destroy           /* destroy */
124 };
125
126
127 struct ptid_entry
128 {
129     void        *ptr;   /* entry ptr */
130     unsigned int next;  /* next free entry */
131 };
132
133 static struct ptid_entry *ptid_entries;     /* array of ptid entries */
134 static unsigned int used_ptid_entries;      /* number of entries in use */
135 static unsigned int alloc_ptid_entries;     /* number of allocated entries */
136 static unsigned int next_free_ptid;         /* next free entry */
137 static unsigned int last_free_ptid;         /* last free entry */
138
139 #define PTID_OFFSET 8  /* offset for first ptid value */
140
141 /* allocate a new process or thread id */
142 unsigned int alloc_ptid( void *ptr )
143 {
144     struct ptid_entry *entry;
145     unsigned int id;
146
147     if (used_ptid_entries < alloc_ptid_entries)
148     {
149         id = used_ptid_entries + PTID_OFFSET;
150         entry = &ptid_entries[used_ptid_entries++];
151     }
152     else if (next_free_ptid)
153     {
154         id = next_free_ptid;
155         entry = &ptid_entries[id - PTID_OFFSET];
156         if (!(next_free_ptid = entry->next)) last_free_ptid = 0;
157     }
158     else  /* need to grow the array */
159     {
160         unsigned int count = alloc_ptid_entries + (alloc_ptid_entries / 2);
161         if (!count) count = 64;
162         if (!(entry = realloc( ptid_entries, count * sizeof(*entry) )))
163         {
164             set_error( STATUS_NO_MEMORY );
165             return 0;
166         }
167         ptid_entries = entry;
168         alloc_ptid_entries = count;
169         id = used_ptid_entries + PTID_OFFSET;
170         entry = &ptid_entries[used_ptid_entries++];
171     }
172
173     entry->ptr = ptr;
174     return id;
175 }
176
177 /* free a process or thread id */
178 void free_ptid( unsigned int id )
179 {
180     struct ptid_entry *entry = &ptid_entries[id - PTID_OFFSET];
181
182     entry->ptr  = NULL;
183     entry->next = 0;
184
185     /* append to end of free list so that we don't reuse it too early */
186     if (last_free_ptid) ptid_entries[last_free_ptid - PTID_OFFSET].next = id;
187     else next_free_ptid = id;
188
189     last_free_ptid = id;
190 }
191
192 /* retrieve the pointer corresponding to a process or thread id */
193 void *get_ptid_entry( unsigned int id )
194 {
195     if (id < PTID_OFFSET) return NULL;
196     if (id - PTID_OFFSET >= used_ptid_entries) return NULL;
197     return ptid_entries[id - PTID_OFFSET].ptr;
198 }
199
200 /* return the main thread of the process */
201 struct thread *get_process_first_thread( struct process *process )
202 {
203     struct list *ptr = list_head( &process->thread_list );
204     if (!ptr) return NULL;
205     return LIST_ENTRY( ptr, struct thread, proc_entry );
206 }
207
208 /* set the state of the process startup info */
209 static void set_process_startup_state( struct process *process, enum startup_state state )
210 {
211     if (process->startup_state == STARTUP_IN_PROGRESS) process->startup_state = state;
212     if (process->startup_info)
213     {
214         wake_up( &process->startup_info->obj, 0 );
215         release_object( process->startup_info );
216         process->startup_info = NULL;
217     }
218 }
219
220 /* final cleanup once we are sure a process is really dead */
221 static void process_died( struct process *process )
222 {
223     if (debug_level) fprintf( stderr, "%04x: *process killed*\n", process->id );
224     release_object( process );
225     if (!--running_processes) close_master_socket();
226 }
227
228 /* callback for process sigkill timeout */
229 static void process_sigkill( void *private )
230 {
231     struct process *process = private;
232
233     process->sigkill_timeout = NULL;
234     kill( process->unix_pid, SIGKILL );
235     process_died( process );
236 }
237
238 /* start the sigkill timer for a process upon exit */
239 static void start_sigkill_timer( struct process *process )
240 {
241     grab_object( process );
242     if (process->unix_pid != -1 && process->msg_fd)
243     {
244         struct timeval when = current_time;
245
246         add_timeout( &when, 1000 );
247         process->sigkill_timeout = add_timeout_user( &when, process_sigkill, process );
248     }
249     else process_died( process );
250 }
251
252 /* create a new process and its main thread */
253 /* if the function fails the fd is closed */
254 struct thread *create_process( int fd, struct thread *parent_thread, int inherit_all )
255 {
256     struct process *process;
257     struct thread *thread = NULL;
258     int request_pipe[2];
259
260     if (!(process = alloc_object( &process_ops )))
261     {
262         close( fd );
263         goto error;
264     }
265     process->parent          = NULL;
266     process->debugger        = NULL;
267     process->handles         = NULL;
268     process->msg_fd          = NULL;
269     process->sigkill_timeout = NULL;
270     process->unix_pid        = -1;
271     process->exit_code       = STILL_ACTIVE;
272     process->running_threads = 0;
273     process->priority        = PROCESS_PRIOCLASS_NORMAL;
274     process->affinity        = 1;
275     process->suspend         = 0;
276     process->create_flags    = 0;
277     process->console         = NULL;
278     process->startup_state   = STARTUP_IN_PROGRESS;
279     process->startup_info    = NULL;
280     process->idle_event      = NULL;
281     process->queue           = NULL;
282     process->peb             = NULL;
283     process->ldt_copy        = NULL;
284     process->winstation      = 0;
285     process->desktop         = 0;
286     process->token           = token_create_admin();
287     list_init( &process->thread_list );
288     list_init( &process->locks );
289     list_init( &process->classes );
290     list_init( &process->dlls );
291
292     process->start_time = current_time;
293     process->end_time.tv_sec = process->end_time.tv_usec = 0;
294     list_add_head( &process_list, &process->entry );
295
296     if (!(process->id = process->group_id = alloc_ptid( process )))
297     {
298         close( fd );
299         goto error;
300     }
301     if (!(process->msg_fd = create_anonymous_fd( &process_fd_ops, fd, &process->obj ))) goto error;
302
303     /* create the handle table */
304     if (!parent_thread) process->handles = alloc_handle_table( process, 0 );
305     else
306     {
307         struct process *parent = parent_thread->process;
308         process->parent = (struct process *)grab_object( parent );
309         process->handles = inherit_all ? copy_handle_table( process, parent )
310                                        : alloc_handle_table( process, 0 );
311     }
312     if (!process->handles) goto error;
313
314     /* create the main thread */
315     if (pipe( request_pipe ) == -1)
316     {
317         file_set_error();
318         goto error;
319     }
320     if (send_client_fd( process, request_pipe[1], 0 ) == -1)
321     {
322         close( request_pipe[0] );
323         close( request_pipe[1] );
324         goto error;
325     }
326     close( request_pipe[1] );
327     if (!(thread = create_thread( request_pipe[0], process ))) goto error;
328
329     set_fd_events( process->msg_fd, POLLIN );  /* start listening to events */
330     release_object( process );
331     return thread;
332
333  error:
334     if (process) release_object( process );
335     /* if we failed to start our first process, close everything down */
336     if (!running_processes) close_master_socket();
337     return NULL;
338 }
339
340 /* initialize the current process and fill in the request */
341 data_size_t init_process( struct thread *thread )
342 {
343     struct process *process = thread->process;
344     struct startup_info *info = process->startup_info;
345
346     if (!info) return 0;
347     return info->data_size;
348 }
349
350 /* destroy a process when its refcount is 0 */
351 static void process_destroy( struct object *obj )
352 {
353     struct process *process = (struct process *)obj;
354     assert( obj->ops == &process_ops );
355
356     /* we can't have a thread remaining */
357     assert( list_empty( &process->thread_list ));
358
359     assert( !process->sigkill_timeout );  /* timeout should hold a reference to the process */
360
361     set_process_startup_state( process, STARTUP_ABORTED );
362     if (process->console) release_object( process->console );
363     if (process->parent) release_object( process->parent );
364     if (process->msg_fd) release_object( process->msg_fd );
365     list_remove( &process->entry );
366     if (process->idle_event) release_object( process->idle_event );
367     if (process->queue) release_object( process->queue );
368     if (process->id) free_ptid( process->id );
369     if (process->token) release_object( process->token );
370 }
371
372 /* dump a process on stdout for debugging purposes */
373 static void process_dump( struct object *obj, int verbose )
374 {
375     struct process *process = (struct process *)obj;
376     assert( obj->ops == &process_ops );
377
378     fprintf( stderr, "Process id=%04x handles=%p\n", process->id, process->handles );
379 }
380
381 static int process_signaled( struct object *obj, struct thread *thread )
382 {
383     struct process *process = (struct process *)obj;
384     return !process->running_threads;
385 }
386
387 static unsigned int process_map_access( struct object *obj, unsigned int access )
388 {
389     if (access & GENERIC_READ)    access |= STANDARD_RIGHTS_READ | SYNCHRONIZE;
390     if (access & GENERIC_WRITE)   access |= STANDARD_RIGHTS_WRITE | SYNCHRONIZE;
391     if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE;
392     if (access & GENERIC_ALL)     access |= PROCESS_ALL_ACCESS;
393     return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
394 }
395
396 static void process_poll_event( struct fd *fd, int event )
397 {
398     struct process *process = get_fd_user( fd );
399     assert( process->obj.ops == &process_ops );
400
401     if (event & (POLLERR | POLLHUP))
402     {
403         release_object( process->msg_fd );
404         process->msg_fd = NULL;
405         if (process->sigkill_timeout)  /* already waiting for it to die */
406         {
407             remove_timeout_user( process->sigkill_timeout );
408             process->sigkill_timeout = NULL;
409             process_died( process );
410         }
411         else kill_process( process, 0 );
412     }
413     else if (event & POLLIN) receive_fd( process );
414 }
415
416 static void startup_info_destroy( struct object *obj )
417 {
418     struct startup_info *info = (struct startup_info *)obj;
419     assert( obj->ops == &startup_info_ops );
420     if (info->data) free( info->data );
421     if (info->exe_file) release_object( info->exe_file );
422     if (info->process) release_object( info->process );
423 }
424
425 static void startup_info_dump( struct object *obj, int verbose )
426 {
427     struct startup_info *info = (struct startup_info *)obj;
428     assert( obj->ops == &startup_info_ops );
429
430     fprintf( stderr, "Startup info in=%p out=%p err=%p\n",
431              info->hstdin, info->hstdout, info->hstderr );
432 }
433
434 static int startup_info_signaled( struct object *obj, struct thread *thread )
435 {
436     struct startup_info *info = (struct startup_info *)obj;
437     return info->process && info->process->startup_state != STARTUP_IN_PROGRESS;
438 }
439
440 /* get a process from an id (and increment the refcount) */
441 struct process *get_process_from_id( process_id_t id )
442 {
443     struct object *obj = get_ptid_entry( id );
444
445     if (obj && obj->ops == &process_ops) return (struct process *)grab_object( obj );
446     set_error( STATUS_INVALID_PARAMETER );
447     return NULL;
448 }
449
450 /* get a process from a handle (and increment the refcount) */
451 struct process *get_process_from_handle( obj_handle_t handle, unsigned int access )
452 {
453     return (struct process *)get_handle_obj( current->process, handle,
454                                              access, &process_ops );
455 }
456
457 /* find a dll from its base address */
458 static inline struct process_dll *find_process_dll( struct process *process, void *base )
459 {
460     struct process_dll *dll;
461
462     LIST_FOR_EACH_ENTRY( dll, &process->dlls, struct process_dll, entry )
463     {
464         if (dll->base == base) return dll;
465     }
466     return NULL;
467 }
468
469 /* add a dll to a process list */
470 static struct process_dll *process_load_dll( struct process *process, struct file *file,
471                                              void *base, const WCHAR *filename, data_size_t name_len )
472 {
473     struct process_dll *dll;
474
475     /* make sure we don't already have one with the same base address */
476     if (find_process_dll( process, base ))
477     {
478         set_error( STATUS_INVALID_PARAMETER );
479         return NULL;
480     }
481
482     if ((dll = mem_alloc( sizeof(*dll) )))
483     {
484         dll->file = NULL;
485         dll->base = base;
486         dll->filename = NULL;
487         dll->namelen  = name_len;
488         if (name_len && !(dll->filename = memdup( filename, name_len )))
489         {
490             free( dll );
491             return NULL;
492         }
493         if (file) dll->file = (struct file *)grab_object( file );
494         list_add_tail( &process->dlls, &dll->entry );
495     }
496     return dll;
497 }
498
499 /* remove a dll from a process list */
500 static void process_unload_dll( struct process *process, void *base )
501 {
502     struct process_dll *dll = find_process_dll( process, base );
503
504     if (dll && (&dll->entry != list_head( &process->dlls )))  /* main exe can't be unloaded */
505     {
506         if (dll->file) release_object( dll->file );
507         if (dll->filename) free( dll->filename );
508         list_remove( &dll->entry );
509         free( dll );
510         generate_debug_event( current, UNLOAD_DLL_DEBUG_EVENT, base );
511     }
512     else set_error( STATUS_INVALID_PARAMETER );
513 }
514
515 /* terminate a process with the given exit code */
516 static void terminate_process( struct process *process, struct thread *skip, int exit_code )
517 {
518     struct list *ptr, *next;
519
520     LIST_FOR_EACH_SAFE( ptr, next, &process->thread_list )
521     {
522         struct thread *thread = LIST_ENTRY( ptr, struct thread, proc_entry );
523
524         if (exit_code) thread->exit_code = exit_code;
525         if (thread != skip) kill_thread( thread, 1 );
526     }
527 }
528
529 /* kill all processes */
530 void kill_all_processes( struct process *skip, int exit_code )
531 {
532     for (;;)
533     {
534         struct process *process;
535
536         LIST_FOR_EACH_ENTRY( process, &process_list, struct process, entry )
537         {
538             if (process == skip) continue;
539             if (process->running_threads) break;
540         }
541         if (&process->entry == &process_list) break;  /* no process found */
542         terminate_process( process, NULL, exit_code );
543     }
544 }
545
546 /* kill all processes being attached to a console renderer */
547 void kill_console_processes( struct thread *renderer, int exit_code )
548 {
549     for (;;)  /* restart from the beginning of the list every time */
550     {
551         struct process *process;
552
553         /* find the first process being attached to 'renderer' and still running */
554         LIST_FOR_EACH_ENTRY( process, &process_list, struct process, entry )
555         {
556             if (process == renderer->process) continue;
557             if (!process->running_threads) continue;
558             if (process->console && process->console->renderer == renderer) break;
559         }
560         if (&process->entry == &process_list) break;  /* no process found */
561         terminate_process( process, NULL, exit_code );
562     }
563 }
564
565 /* a process has been killed (i.e. its last thread died) */
566 static void process_killed( struct process *process )
567 {
568     struct handle_table *handles;
569     struct list *ptr;
570
571     assert( list_empty( &process->thread_list ));
572     process->end_time = current_time;
573     close_process_desktop( process );
574     handles = process->handles;
575     process->handles = NULL;
576     if (handles) release_object( handles );
577
578     /* close the console attached to this process, if any */
579     free_console( process );
580
581     while ((ptr = list_head( &process->dlls )))
582     {
583         struct process_dll *dll = LIST_ENTRY( ptr, struct process_dll, entry );
584         if (dll->file) release_object( dll->file );
585         if (dll->filename) free( dll->filename );
586         list_remove( &dll->entry );
587         free( dll );
588     }
589     destroy_process_classes( process );
590     remove_process_locks( process );
591     set_process_startup_state( process, STARTUP_ABORTED );
592     start_sigkill_timer( process );
593     wake_up( &process->obj, 0 );
594 }
595
596 /* add a thread to a process running threads list */
597 void add_process_thread( struct process *process, struct thread *thread )
598 {
599     list_add_tail( &process->thread_list, &thread->proc_entry );
600     if (!process->running_threads++) running_processes++;
601     grab_object( thread );
602 }
603
604 /* remove a thread from a process running threads list */
605 void remove_process_thread( struct process *process, struct thread *thread )
606 {
607     assert( process->running_threads > 0 );
608     assert( !list_empty( &process->thread_list ));
609
610     list_remove( &thread->proc_entry );
611
612     if (!--process->running_threads)
613     {
614         /* we have removed the last running thread, exit the process */
615         process->exit_code = thread->exit_code;
616         generate_debug_event( thread, EXIT_PROCESS_DEBUG_EVENT, process );
617         process_killed( process );
618     }
619     else generate_debug_event( thread, EXIT_THREAD_DEBUG_EVENT, thread );
620     release_object( thread );
621 }
622
623 /* suspend all the threads of a process */
624 void suspend_process( struct process *process )
625 {
626     if (!process->suspend++)
627     {
628         struct list *ptr, *next;
629
630         LIST_FOR_EACH_SAFE( ptr, next, &process->thread_list )
631         {
632             struct thread *thread = LIST_ENTRY( ptr, struct thread, proc_entry );
633             if (!thread->suspend) stop_thread( thread );
634         }
635     }
636 }
637
638 /* resume all the threads of a process */
639 void resume_process( struct process *process )
640 {
641     assert (process->suspend > 0);
642     if (!--process->suspend)
643     {
644         struct list *ptr, *next;
645
646         LIST_FOR_EACH_SAFE( ptr, next, &process->thread_list )
647         {
648             struct thread *thread = LIST_ENTRY( ptr, struct thread, proc_entry );
649             if (!thread->suspend) wake_thread( thread );
650         }
651     }
652 }
653
654 /* kill a process on the spot */
655 void kill_process( struct process *process, int violent_death )
656 {
657     if (violent_death) terminate_process( process, NULL, 1 );
658     else
659     {
660         struct list *ptr, *next;
661
662         LIST_FOR_EACH_SAFE( ptr, next, &process->thread_list )
663         {
664             struct thread *thread = LIST_ENTRY( ptr, struct thread, proc_entry );
665             kill_thread( thread, 0 );
666         }
667     }
668 }
669
670 /* kill all processes being debugged by a given thread */
671 void kill_debugged_processes( struct thread *debugger, int exit_code )
672 {
673     for (;;)  /* restart from the beginning of the list every time */
674     {
675         struct process *process;
676
677         /* find the first process being debugged by 'debugger' and still running */
678         LIST_FOR_EACH_ENTRY( process, &process_list, struct process, entry )
679         {
680             if (!process->running_threads) continue;
681             if (process->debugger == debugger) break;
682         }
683         if (&process->entry == &process_list) break;  /* no process found */
684         process->debugger = NULL;
685         terminate_process( process, NULL, exit_code );
686     }
687 }
688
689
690 /* trigger a breakpoint event in a given process */
691 void break_process( struct process *process )
692 {
693     struct thread *thread;
694
695     suspend_process( process );
696
697     LIST_FOR_EACH_ENTRY( thread, &process->thread_list, struct thread, proc_entry )
698     {
699         if (thread->context)  /* inside an exception event already */
700         {
701             break_thread( thread );
702             goto done;
703         }
704     }
705     if ((thread = get_process_first_thread( process ))) thread->debug_break = 1;
706     else set_error( STATUS_ACCESS_DENIED );
707 done:
708     resume_process( process );
709 }
710
711
712 /* detach a debugger from all its debuggees */
713 void detach_debugged_processes( struct thread *debugger )
714 {
715     struct process *process;
716
717     LIST_FOR_EACH_ENTRY( process, &process_list, struct process, entry )
718     {
719         if (process->debugger == debugger && process->running_threads)
720         {
721             debugger_detach( process, debugger );
722         }
723     }
724 }
725
726
727 void enum_processes( int (*cb)(struct process*, void*), void *user )
728 {
729     struct list *ptr, *next;
730
731     LIST_FOR_EACH_SAFE( ptr, next, &process_list )
732     {
733         struct process *process = LIST_ENTRY( ptr, struct process, entry );
734         if ((cb)(process, user)) break;
735     }
736 }
737
738 /* set the debugged flag in the process PEB */
739 int set_process_debug_flag( struct process *process, int flag )
740 {
741     char data = (flag != 0);
742
743     /* BeingDebugged flag is the byte at offset 2 in the PEB */
744     return write_process_memory( process, (char *)process->peb + 2, 1, &data );
745 }
746
747 /* take a snapshot of currently running processes */
748 struct process_snapshot *process_snap( int *count )
749 {
750     struct process_snapshot *snapshot, *ptr;
751     struct process *process;
752
753     if (!running_processes) return NULL;
754     if (!(snapshot = mem_alloc( sizeof(*snapshot) * running_processes )))
755         return NULL;
756     ptr = snapshot;
757     LIST_FOR_EACH_ENTRY( process, &process_list, struct process, entry )
758     {
759         if (!process->running_threads) continue;
760         ptr->process  = process;
761         ptr->threads  = process->running_threads;
762         ptr->count    = process->obj.refcount;
763         ptr->priority = process->priority;
764         ptr->handles  = get_handle_table_count(process);
765         grab_object( process );
766         ptr++;
767     }
768
769     if (!(*count = ptr - snapshot))
770     {
771         free( snapshot );
772         snapshot = NULL;
773     }
774     return snapshot;
775 }
776
777 /* take a snapshot of the modules of a process */
778 struct module_snapshot *module_snap( struct process *process, int *count )
779 {
780     struct module_snapshot *snapshot, *ptr;
781     struct process_dll *dll;
782     int total = 0;
783
784     LIST_FOR_EACH_ENTRY( dll, &process->dlls, struct process_dll, entry ) total++;
785     if (!(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
786
787     ptr = snapshot;
788     LIST_FOR_EACH_ENTRY( dll, &process->dlls, struct process_dll, entry )
789     {
790         ptr->base     = dll->base;
791         ptr->size     = dll->size;
792         ptr->namelen  = dll->namelen;
793         ptr->filename = memdup( dll->filename, dll->namelen );
794         ptr++;
795     }
796     *count = total;
797     return snapshot;
798 }
799
800
801 /* create a new process */
802 DECL_HANDLER(new_process)
803 {
804     struct startup_info *info;
805     struct thread *thread;
806     struct process *process;
807     struct process *parent = current->process;
808     int socket_fd = thread_get_inflight_fd( current, req->socket_fd );
809
810     if (socket_fd == -1)
811     {
812         set_error( STATUS_INVALID_PARAMETER );
813         return;
814     }
815     if (fcntl( socket_fd, F_SETFL, O_NONBLOCK ) == -1)
816     {
817         set_error( STATUS_INVALID_HANDLE );
818         close( socket_fd );
819         return;
820     }
821
822     /* build the startup info for a new process */
823     if (!(info = alloc_object( &startup_info_ops ))) return;
824     info->hstdin       = req->hstdin;
825     info->hstdout      = req->hstdout;
826     info->hstderr      = req->hstderr;
827     info->exe_file     = NULL;
828     info->process      = NULL;
829     info->data_size    = get_req_data_size();
830     info->data         = NULL;
831
832     if (req->exe_file &&
833         !(info->exe_file = get_file_obj( current->process, req->exe_file, FILE_READ_DATA )))
834         goto done;
835
836     if (!(info->data = memdup( get_req_data(), info->data_size ))) goto done;
837
838     if (!(thread = create_process( socket_fd, current, req->inherit_all ))) goto done;
839     process = thread->process;
840     process->create_flags = req->create_flags;
841     process->startup_info = (struct startup_info *)grab_object( info );
842
843     /* connect to the window station */
844     connect_process_winstation( process, current );
845
846     /* thread will be actually suspended in init_done */
847     if (req->create_flags & CREATE_SUSPENDED) thread->suspend++;
848
849     /* set the process console */
850     if (!(req->create_flags & (DETACHED_PROCESS | CREATE_NEW_CONSOLE)))
851     {
852         /* FIXME: some better error checking should be done...
853          * like if hConOut and hConIn are console handles, then they should be on the same
854          * physical console
855          */
856         inherit_console( current, process, req->inherit_all ? req->hstdin : 0 );
857     }
858
859     if (!req->inherit_all && !(req->create_flags & CREATE_NEW_CONSOLE))
860     {
861         info->hstdin  = duplicate_handle( parent, req->hstdin, process,
862                                           0, OBJ_INHERIT, DUPLICATE_SAME_ACCESS );
863         info->hstdout = duplicate_handle( parent, req->hstdout, process,
864                                           0, OBJ_INHERIT, DUPLICATE_SAME_ACCESS );
865         info->hstderr = duplicate_handle( parent, req->hstderr, process,
866                                           0, OBJ_INHERIT, DUPLICATE_SAME_ACCESS );
867         /* some handles above may have been invalid; this is not an error */
868         if (get_error() == STATUS_INVALID_HANDLE ||
869             get_error() == STATUS_OBJECT_TYPE_MISMATCH) clear_error();
870     }
871
872     /* attach to the debugger if requested */
873     if (req->create_flags & (DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS))
874         set_process_debugger( process, current );
875     else if (parent->debugger && !(parent->create_flags & DEBUG_ONLY_THIS_PROCESS))
876         set_process_debugger( process, parent->debugger );
877
878     if (!(req->create_flags & CREATE_NEW_PROCESS_GROUP))
879         process->group_id = parent->group_id;
880
881     info->process = (struct process *)grab_object( process );
882     reply->info = alloc_handle( current->process, info, SYNCHRONIZE, 0 );
883     reply->pid = get_process_id( process );
884     reply->tid = get_thread_id( thread );
885     reply->phandle = alloc_handle( parent, process, req->process_access, req->process_attr );
886     reply->thandle = alloc_handle( parent, thread, req->thread_access, req->thread_attr );
887
888  done:
889     release_object( info );
890 }
891
892 /* Retrieve information about a newly started process */
893 DECL_HANDLER(get_new_process_info)
894 {
895     struct startup_info *info;
896
897     if ((info = (struct startup_info *)get_handle_obj( current->process, req->info,
898                                                        0, &startup_info_ops )))
899     {
900         reply->success = is_process_init_done( info->process );
901         reply->exit_code = info->process->exit_code;
902         release_object( info );
903     }
904 }
905
906 /* Retrieve the new process startup info */
907 DECL_HANDLER(get_startup_info)
908 {
909     struct process *process = current->process;
910     struct startup_info *info = process->startup_info;
911     data_size_t size;
912
913     if (!info) return;
914
915     if (info->exe_file &&
916         !(reply->exe_file = alloc_handle( process, info->exe_file, GENERIC_READ, 0 ))) return;
917
918     reply->hstdin  = info->hstdin;
919     reply->hstdout = info->hstdout;
920     reply->hstderr = info->hstderr;
921
922     /* we return the data directly without making a copy so this can only be called once */
923     size = info->data_size;
924     if (size > get_reply_max_size()) size = get_reply_max_size();
925     set_reply_data_ptr( info->data, size );
926     info->data = NULL;
927     info->data_size = 0;
928 }
929
930 /* signal the end of the process initialization */
931 DECL_HANDLER(init_process_done)
932 {
933     struct process_dll *dll;
934     struct process *process = current->process;
935
936     if (is_process_init_done(process))
937     {
938         set_error( STATUS_INVALID_PARAMETER );
939         return;
940     }
941     if (!(dll = find_process_dll( process, req->module )))
942     {
943         set_error( STATUS_DLL_NOT_FOUND );
944         return;
945     }
946
947     /* main exe is the first in the dll list */
948     list_remove( &dll->entry );
949     list_add_head( &process->dlls, &dll->entry );
950
951     generate_startup_debug_events( process, req->entry );
952     set_process_startup_state( process, STARTUP_DONE );
953
954     if (req->gui) process->idle_event = create_event( NULL, NULL, 0, 1, 0 );
955     if (current->suspend + process->suspend > 0) stop_thread( current );
956     if (process->debugger) set_process_debug_flag( process, 1 );
957 }
958
959 /* open a handle to a process */
960 DECL_HANDLER(open_process)
961 {
962     struct process *process = get_process_from_id( req->pid );
963     reply->handle = 0;
964     if (process)
965     {
966         reply->handle = alloc_handle( current->process, process, req->access, req->attributes );
967         release_object( process );
968     }
969 }
970
971 /* terminate a process */
972 DECL_HANDLER(terminate_process)
973 {
974     struct process *process;
975
976     if ((process = get_process_from_handle( req->handle, PROCESS_TERMINATE )))
977     {
978         reply->self = (current->process == process);
979         terminate_process( process, current, req->exit_code );
980         release_object( process );
981     }
982 }
983
984 /* fetch information about a process */
985 DECL_HANDLER(get_process_info)
986 {
987     struct process *process;
988
989     if ((process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION )))
990     {
991         reply->pid              = get_process_id( process );
992         reply->ppid             = process->parent ? get_process_id( process->parent ) : 0;
993         reply->exit_code        = process->exit_code;
994         reply->priority         = process->priority;
995         reply->affinity         = process->affinity;
996         reply->peb              = process->peb;
997         reply->start_time.sec   = process->start_time.tv_sec;
998         reply->start_time.usec  = process->start_time.tv_usec;
999         reply->end_time.sec     = process->end_time.tv_sec;
1000         reply->end_time.usec    = process->end_time.tv_usec;
1001         release_object( process );
1002     }
1003 }
1004
1005 /* set information about a process */
1006 DECL_HANDLER(set_process_info)
1007 {
1008     struct process *process;
1009
1010     if ((process = get_process_from_handle( req->handle, PROCESS_SET_INFORMATION )))
1011     {
1012         if (req->mask & SET_PROCESS_INFO_PRIORITY) process->priority = req->priority;
1013         if (req->mask & SET_PROCESS_INFO_AFFINITY)
1014         {
1015             if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
1016             else process->affinity = req->affinity;
1017         }
1018         release_object( process );
1019     }
1020 }
1021
1022 /* read data from a process address space */
1023 DECL_HANDLER(read_process_memory)
1024 {
1025     struct process *process;
1026     data_size_t len = get_reply_max_size();
1027
1028     if (!(process = get_process_from_handle( req->handle, PROCESS_VM_READ ))) return;
1029
1030     if (len)
1031     {
1032         char *buffer = mem_alloc( len );
1033         if (buffer)
1034         {
1035             if (read_process_memory( process, req->addr, len, buffer ))
1036                 set_reply_data_ptr( buffer, len );
1037             else
1038                 free( buffer );
1039         }
1040     }
1041     release_object( process );
1042 }
1043
1044 /* write data to a process address space */
1045 DECL_HANDLER(write_process_memory)
1046 {
1047     struct process *process;
1048
1049     if ((process = get_process_from_handle( req->handle, PROCESS_VM_WRITE )))
1050     {
1051         data_size_t len = get_req_data_size();
1052         if (len) write_process_memory( process, req->addr, len, get_req_data() );
1053         else set_error( STATUS_INVALID_PARAMETER );
1054         release_object( process );
1055     }
1056 }
1057
1058 /* notify the server that a dll has been loaded */
1059 DECL_HANDLER(load_dll)
1060 {
1061     struct process_dll *dll;
1062     struct file *file = NULL;
1063
1064     if (req->handle && !(file = get_file_obj( current->process, req->handle, FILE_READ_DATA )))
1065         return;
1066
1067     if ((dll = process_load_dll( current->process, file, req->base,
1068                                  get_req_data(), get_req_data_size() )))
1069     {
1070         dll->size       = req->size;
1071         dll->dbg_offset = req->dbg_offset;
1072         dll->dbg_size   = req->dbg_size;
1073         dll->name       = req->name;
1074         /* only generate event if initialization is done */
1075         if (is_process_init_done( current->process ))
1076             generate_debug_event( current, LOAD_DLL_DEBUG_EVENT, dll );
1077     }
1078     if (file) release_object( file );
1079 }
1080
1081 /* notify the server that a dll is being unloaded */
1082 DECL_HANDLER(unload_dll)
1083 {
1084     process_unload_dll( current->process, req->base );
1085 }
1086
1087 /* retrieve information about a module in a process */
1088 DECL_HANDLER(get_dll_info)
1089 {
1090     struct process *process;
1091
1092     if ((process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION )))
1093     {
1094         struct process_dll *dll = find_process_dll( process, req->base_address );
1095
1096         if (dll)
1097         {
1098             reply->size = dll->size;
1099             reply->entry_point = NULL; /* FIXME */
1100             if (dll->filename)
1101             {
1102                 data_size_t len = min( dll->namelen, get_reply_max_size() );
1103                 set_reply_data( dll->filename, len );
1104             }
1105         }
1106         else
1107             set_error( STATUS_DLL_NOT_FOUND );
1108
1109         release_object( process );
1110     }
1111 }
1112
1113 /* retrieve the process idle event */
1114 DECL_HANDLER(get_process_idle_event)
1115 {
1116     struct process *process;
1117
1118     reply->event = 0;
1119     if ((process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION )))
1120     {
1121         if (process->idle_event && process != current->process)
1122             reply->event = alloc_handle( current->process, process->idle_event,
1123                                          EVENT_ALL_ACCESS, 0 );
1124         release_object( process );
1125     }
1126 }