server: Properly handle kill_thread recursion when killing a process.
[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     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         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;
519
520     if (skip)  /* move it to the end of the list */
521     {
522         assert( skip->state != TERMINATED );
523         list_remove( &skip->proc_entry );
524         list_add_tail( &process->thread_list, &skip->proc_entry );
525     }
526
527     grab_object( process );  /* make sure it doesn't get freed when threads die */
528     while ((ptr = list_head( &process->thread_list )))
529     {
530         struct thread *thread = LIST_ENTRY( ptr, struct thread, proc_entry );
531
532         if (exit_code) thread->exit_code = exit_code;
533         if (thread == skip) break;
534         kill_thread( thread, 1 );
535     }
536     release_object( process );
537 }
538
539 /* kill all processes */
540 void kill_all_processes( struct process *skip, int exit_code )
541 {
542     for (;;)
543     {
544         struct process *process;
545
546         LIST_FOR_EACH_ENTRY( process, &process_list, struct process, entry )
547         {
548             if (process == skip) continue;
549             if (process->running_threads) break;
550         }
551         if (&process->entry == &process_list) break;  /* no process found */
552         terminate_process( process, NULL, exit_code );
553     }
554 }
555
556 /* kill all processes being attached to a console renderer */
557 void kill_console_processes( struct thread *renderer, int exit_code )
558 {
559     for (;;)  /* restart from the beginning of the list every time */
560     {
561         struct process *process;
562
563         /* find the first process being attached to 'renderer' and still running */
564         LIST_FOR_EACH_ENTRY( process, &process_list, struct process, entry )
565         {
566             if (process == renderer->process) continue;
567             if (!process->running_threads) continue;
568             if (process->console && process->console->renderer == renderer) break;
569         }
570         if (&process->entry == &process_list) break;  /* no process found */
571         terminate_process( process, NULL, exit_code );
572     }
573 }
574
575 /* a process has been killed (i.e. its last thread died) */
576 static void process_killed( struct process *process )
577 {
578     struct handle_table *handles;
579     struct list *ptr;
580
581     assert( list_empty( &process->thread_list ));
582     process->end_time = current_time;
583     close_process_desktop( process );
584     handles = process->handles;
585     process->handles = NULL;
586     if (handles) release_object( handles );
587
588     /* close the console attached to this process, if any */
589     free_console( process );
590
591     while ((ptr = list_head( &process->dlls )))
592     {
593         struct process_dll *dll = LIST_ENTRY( ptr, struct process_dll, entry );
594         if (dll->file) release_object( dll->file );
595         free( dll->filename );
596         list_remove( &dll->entry );
597         free( dll );
598     }
599     destroy_process_classes( process );
600     remove_process_locks( process );
601     set_process_startup_state( process, STARTUP_ABORTED );
602     start_sigkill_timer( process );
603     wake_up( &process->obj, 0 );
604 }
605
606 /* add a thread to a process running threads list */
607 void add_process_thread( struct process *process, struct thread *thread )
608 {
609     list_add_tail( &process->thread_list, &thread->proc_entry );
610     if (!process->running_threads++) running_processes++;
611     grab_object( thread );
612 }
613
614 /* remove a thread from a process running threads list */
615 void remove_process_thread( struct process *process, struct thread *thread )
616 {
617     assert( process->running_threads > 0 );
618     assert( !list_empty( &process->thread_list ));
619
620     list_remove( &thread->proc_entry );
621
622     if (!--process->running_threads)
623     {
624         /* we have removed the last running thread, exit the process */
625         process->exit_code = thread->exit_code;
626         generate_debug_event( thread, EXIT_PROCESS_DEBUG_EVENT, process );
627         process_killed( process );
628     }
629     else generate_debug_event( thread, EXIT_THREAD_DEBUG_EVENT, thread );
630     release_object( thread );
631 }
632
633 /* suspend all the threads of a process */
634 void suspend_process( struct process *process )
635 {
636     if (!process->suspend++)
637     {
638         struct list *ptr, *next;
639
640         LIST_FOR_EACH_SAFE( ptr, next, &process->thread_list )
641         {
642             struct thread *thread = LIST_ENTRY( ptr, struct thread, proc_entry );
643             if (!thread->suspend) stop_thread( thread );
644         }
645     }
646 }
647
648 /* resume all the threads of a process */
649 void resume_process( struct process *process )
650 {
651     assert (process->suspend > 0);
652     if (!--process->suspend)
653     {
654         struct list *ptr, *next;
655
656         LIST_FOR_EACH_SAFE( ptr, next, &process->thread_list )
657         {
658             struct thread *thread = LIST_ENTRY( ptr, struct thread, proc_entry );
659             if (!thread->suspend) wake_thread( thread );
660         }
661     }
662 }
663
664 /* kill a process on the spot */
665 void kill_process( struct process *process, int violent_death )
666 {
667     if (violent_death) terminate_process( process, NULL, 1 );
668     else
669     {
670         struct list *ptr;
671
672         grab_object( process );  /* make sure it doesn't get freed when threads die */
673         while ((ptr = list_head( &process->thread_list )))
674         {
675             struct thread *thread = LIST_ENTRY( ptr, struct thread, proc_entry );
676             kill_thread( thread, 0 );
677         }
678         release_object( process );
679     }
680 }
681
682 /* kill all processes being debugged by a given thread */
683 void kill_debugged_processes( struct thread *debugger, int exit_code )
684 {
685     for (;;)  /* restart from the beginning of the list every time */
686     {
687         struct process *process;
688
689         /* find the first process being debugged by 'debugger' and still running */
690         LIST_FOR_EACH_ENTRY( process, &process_list, struct process, entry )
691         {
692             if (!process->running_threads) continue;
693             if (process->debugger == debugger) break;
694         }
695         if (&process->entry == &process_list) break;  /* no process found */
696         process->debugger = NULL;
697         terminate_process( process, NULL, exit_code );
698     }
699 }
700
701
702 /* trigger a breakpoint event in a given process */
703 void break_process( struct process *process )
704 {
705     struct thread *thread;
706
707     suspend_process( process );
708
709     LIST_FOR_EACH_ENTRY( thread, &process->thread_list, struct thread, proc_entry )
710     {
711         if (thread->context)  /* inside an exception event already */
712         {
713             break_thread( thread );
714             goto done;
715         }
716     }
717     if ((thread = get_process_first_thread( process ))) thread->debug_break = 1;
718     else set_error( STATUS_ACCESS_DENIED );
719 done:
720     resume_process( process );
721 }
722
723
724 /* detach a debugger from all its debuggees */
725 void detach_debugged_processes( struct thread *debugger )
726 {
727     struct process *process;
728
729     LIST_FOR_EACH_ENTRY( process, &process_list, struct process, entry )
730     {
731         if (process->debugger == debugger && process->running_threads)
732         {
733             debugger_detach( process, debugger );
734         }
735     }
736 }
737
738
739 void enum_processes( int (*cb)(struct process*, void*), void *user )
740 {
741     struct list *ptr, *next;
742
743     LIST_FOR_EACH_SAFE( ptr, next, &process_list )
744     {
745         struct process *process = LIST_ENTRY( ptr, struct process, entry );
746         if ((cb)(process, user)) break;
747     }
748 }
749
750 /* set the debugged flag in the process PEB */
751 int set_process_debug_flag( struct process *process, int flag )
752 {
753     char data = (flag != 0);
754
755     /* BeingDebugged flag is the byte at offset 2 in the PEB */
756     return write_process_memory( process, (char *)process->peb + 2, 1, &data );
757 }
758
759 /* take a snapshot of currently running processes */
760 struct process_snapshot *process_snap( int *count )
761 {
762     struct process_snapshot *snapshot, *ptr;
763     struct process *process;
764
765     if (!running_processes) return NULL;
766     if (!(snapshot = mem_alloc( sizeof(*snapshot) * running_processes )))
767         return NULL;
768     ptr = snapshot;
769     LIST_FOR_EACH_ENTRY( process, &process_list, struct process, entry )
770     {
771         if (!process->running_threads) continue;
772         ptr->process  = process;
773         ptr->threads  = process->running_threads;
774         ptr->count    = process->obj.refcount;
775         ptr->priority = process->priority;
776         ptr->handles  = get_handle_table_count(process);
777         grab_object( process );
778         ptr++;
779     }
780
781     if (!(*count = ptr - snapshot))
782     {
783         free( snapshot );
784         snapshot = NULL;
785     }
786     return snapshot;
787 }
788
789 /* take a snapshot of the modules of a process */
790 struct module_snapshot *module_snap( struct process *process, int *count )
791 {
792     struct module_snapshot *snapshot, *ptr;
793     struct process_dll *dll;
794     int total = 0;
795
796     LIST_FOR_EACH_ENTRY( dll, &process->dlls, struct process_dll, entry ) total++;
797     if (!(snapshot = mem_alloc( sizeof(*snapshot) * total ))) return NULL;
798
799     ptr = snapshot;
800     LIST_FOR_EACH_ENTRY( dll, &process->dlls, struct process_dll, entry )
801     {
802         ptr->base     = dll->base;
803         ptr->size     = dll->size;
804         ptr->namelen  = dll->namelen;
805         ptr->filename = memdup( dll->filename, dll->namelen );
806         ptr++;
807     }
808     *count = total;
809     return snapshot;
810 }
811
812
813 /* create a new process */
814 DECL_HANDLER(new_process)
815 {
816     struct startup_info *info;
817     struct thread *thread;
818     struct process *process;
819     struct process *parent = current->process;
820     int socket_fd = thread_get_inflight_fd( current, req->socket_fd );
821
822     if (socket_fd == -1)
823     {
824         set_error( STATUS_INVALID_PARAMETER );
825         return;
826     }
827     if (fcntl( socket_fd, F_SETFL, O_NONBLOCK ) == -1)
828     {
829         set_error( STATUS_INVALID_HANDLE );
830         close( socket_fd );
831         return;
832     }
833
834     /* build the startup info for a new process */
835     if (!(info = alloc_object( &startup_info_ops ))) return;
836     info->hstdin       = req->hstdin;
837     info->hstdout      = req->hstdout;
838     info->hstderr      = req->hstderr;
839     info->exe_file     = NULL;
840     info->process      = NULL;
841     info->data_size    = get_req_data_size();
842     info->data         = NULL;
843
844     if (req->exe_file &&
845         !(info->exe_file = get_file_obj( current->process, req->exe_file, FILE_READ_DATA )))
846         goto done;
847
848     if (!(info->data = memdup( get_req_data(), info->data_size ))) goto done;
849
850     if (!(thread = create_process( socket_fd, current, req->inherit_all ))) goto done;
851     process = thread->process;
852     process->create_flags = req->create_flags;
853     process->startup_info = (struct startup_info *)grab_object( info );
854
855     /* connect to the window station */
856     connect_process_winstation( process, current );
857
858     /* thread will be actually suspended in init_done */
859     if (req->create_flags & CREATE_SUSPENDED) thread->suspend++;
860
861     /* set the process console */
862     if (!(req->create_flags & (DETACHED_PROCESS | CREATE_NEW_CONSOLE)))
863     {
864         /* FIXME: some better error checking should be done...
865          * like if hConOut and hConIn are console handles, then they should be on the same
866          * physical console
867          */
868         inherit_console( current, process, req->inherit_all ? req->hstdin : 0 );
869     }
870
871     if (!req->inherit_all && !(req->create_flags & CREATE_NEW_CONSOLE))
872     {
873         info->hstdin  = duplicate_handle( parent, req->hstdin, process,
874                                           0, OBJ_INHERIT, DUPLICATE_SAME_ACCESS );
875         info->hstdout = duplicate_handle( parent, req->hstdout, process,
876                                           0, OBJ_INHERIT, DUPLICATE_SAME_ACCESS );
877         info->hstderr = duplicate_handle( parent, req->hstderr, process,
878                                           0, OBJ_INHERIT, DUPLICATE_SAME_ACCESS );
879         /* some handles above may have been invalid; this is not an error */
880         if (get_error() == STATUS_INVALID_HANDLE ||
881             get_error() == STATUS_OBJECT_TYPE_MISMATCH) clear_error();
882     }
883
884     /* attach to the debugger if requested */
885     if (req->create_flags & (DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS))
886         set_process_debugger( process, current );
887     else if (parent->debugger && !(parent->create_flags & DEBUG_ONLY_THIS_PROCESS))
888         set_process_debugger( process, parent->debugger );
889
890     if (!(req->create_flags & CREATE_NEW_PROCESS_GROUP))
891         process->group_id = parent->group_id;
892
893     info->process = (struct process *)grab_object( process );
894     reply->info = alloc_handle( current->process, info, SYNCHRONIZE, 0 );
895     reply->pid = get_process_id( process );
896     reply->tid = get_thread_id( thread );
897     reply->phandle = alloc_handle( parent, process, req->process_access, req->process_attr );
898     reply->thandle = alloc_handle( parent, thread, req->thread_access, req->thread_attr );
899
900  done:
901     release_object( info );
902 }
903
904 /* Retrieve information about a newly started process */
905 DECL_HANDLER(get_new_process_info)
906 {
907     struct startup_info *info;
908
909     if ((info = (struct startup_info *)get_handle_obj( current->process, req->info,
910                                                        0, &startup_info_ops )))
911     {
912         reply->success = is_process_init_done( info->process );
913         reply->exit_code = info->process->exit_code;
914         release_object( info );
915     }
916 }
917
918 /* Retrieve the new process startup info */
919 DECL_HANDLER(get_startup_info)
920 {
921     struct process *process = current->process;
922     struct startup_info *info = process->startup_info;
923     data_size_t size;
924
925     if (!info) return;
926
927     if (info->exe_file &&
928         !(reply->exe_file = alloc_handle( process, info->exe_file, GENERIC_READ, 0 ))) return;
929
930     reply->hstdin  = info->hstdin;
931     reply->hstdout = info->hstdout;
932     reply->hstderr = info->hstderr;
933
934     /* we return the data directly without making a copy so this can only be called once */
935     size = info->data_size;
936     if (size > get_reply_max_size()) size = get_reply_max_size();
937     set_reply_data_ptr( info->data, size );
938     info->data = NULL;
939     info->data_size = 0;
940 }
941
942 /* signal the end of the process initialization */
943 DECL_HANDLER(init_process_done)
944 {
945     struct process_dll *dll;
946     struct process *process = current->process;
947
948     if (is_process_init_done(process))
949     {
950         set_error( STATUS_INVALID_PARAMETER );
951         return;
952     }
953     if (!(dll = find_process_dll( process, req->module )))
954     {
955         set_error( STATUS_DLL_NOT_FOUND );
956         return;
957     }
958
959     /* main exe is the first in the dll list */
960     list_remove( &dll->entry );
961     list_add_head( &process->dlls, &dll->entry );
962
963     generate_startup_debug_events( process, req->entry );
964     set_process_startup_state( process, STARTUP_DONE );
965
966     if (req->gui) process->idle_event = create_event( NULL, NULL, 0, 1, 0 );
967     if (current->suspend + process->suspend > 0) stop_thread( current );
968     if (process->debugger) set_process_debug_flag( process, 1 );
969 }
970
971 /* open a handle to a process */
972 DECL_HANDLER(open_process)
973 {
974     struct process *process = get_process_from_id( req->pid );
975     reply->handle = 0;
976     if (process)
977     {
978         reply->handle = alloc_handle( current->process, process, req->access, req->attributes );
979         release_object( process );
980     }
981 }
982
983 /* terminate a process */
984 DECL_HANDLER(terminate_process)
985 {
986     struct process *process;
987
988     if ((process = get_process_from_handle( req->handle, PROCESS_TERMINATE )))
989     {
990         reply->self = (current->process == process);
991         terminate_process( process, current, req->exit_code );
992         release_object( process );
993     }
994 }
995
996 /* fetch information about a process */
997 DECL_HANDLER(get_process_info)
998 {
999     struct process *process;
1000
1001     if ((process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION )))
1002     {
1003         reply->pid              = get_process_id( process );
1004         reply->ppid             = process->parent ? get_process_id( process->parent ) : 0;
1005         reply->exit_code        = process->exit_code;
1006         reply->priority         = process->priority;
1007         reply->affinity         = process->affinity;
1008         reply->peb              = process->peb;
1009         reply->start_time.sec   = process->start_time.tv_sec;
1010         reply->start_time.usec  = process->start_time.tv_usec;
1011         reply->end_time.sec     = process->end_time.tv_sec;
1012         reply->end_time.usec    = process->end_time.tv_usec;
1013         release_object( process );
1014     }
1015 }
1016
1017 /* set information about a process */
1018 DECL_HANDLER(set_process_info)
1019 {
1020     struct process *process;
1021
1022     if ((process = get_process_from_handle( req->handle, PROCESS_SET_INFORMATION )))
1023     {
1024         if (req->mask & SET_PROCESS_INFO_PRIORITY) process->priority = req->priority;
1025         if (req->mask & SET_PROCESS_INFO_AFFINITY)
1026         {
1027             if (req->affinity != 1) set_error( STATUS_INVALID_PARAMETER );
1028             else process->affinity = req->affinity;
1029         }
1030         release_object( process );
1031     }
1032 }
1033
1034 /* read data from a process address space */
1035 DECL_HANDLER(read_process_memory)
1036 {
1037     struct process *process;
1038     data_size_t len = get_reply_max_size();
1039
1040     if (!(process = get_process_from_handle( req->handle, PROCESS_VM_READ ))) return;
1041
1042     if (len)
1043     {
1044         char *buffer = mem_alloc( len );
1045         if (buffer)
1046         {
1047             if (read_process_memory( process, req->addr, len, buffer ))
1048                 set_reply_data_ptr( buffer, len );
1049             else
1050                 free( buffer );
1051         }
1052     }
1053     release_object( process );
1054 }
1055
1056 /* write data to a process address space */
1057 DECL_HANDLER(write_process_memory)
1058 {
1059     struct process *process;
1060
1061     if ((process = get_process_from_handle( req->handle, PROCESS_VM_WRITE )))
1062     {
1063         data_size_t len = get_req_data_size();
1064         if (len) write_process_memory( process, req->addr, len, get_req_data() );
1065         else set_error( STATUS_INVALID_PARAMETER );
1066         release_object( process );
1067     }
1068 }
1069
1070 /* notify the server that a dll has been loaded */
1071 DECL_HANDLER(load_dll)
1072 {
1073     struct process_dll *dll;
1074     struct file *file = NULL;
1075
1076     if (req->handle && !(file = get_file_obj( current->process, req->handle, FILE_READ_DATA )))
1077         return;
1078
1079     if ((dll = process_load_dll( current->process, file, req->base,
1080                                  get_req_data(), get_req_data_size() )))
1081     {
1082         dll->size       = req->size;
1083         dll->dbg_offset = req->dbg_offset;
1084         dll->dbg_size   = req->dbg_size;
1085         dll->name       = req->name;
1086         /* only generate event if initialization is done */
1087         if (is_process_init_done( current->process ))
1088             generate_debug_event( current, LOAD_DLL_DEBUG_EVENT, dll );
1089     }
1090     if (file) release_object( file );
1091 }
1092
1093 /* notify the server that a dll is being unloaded */
1094 DECL_HANDLER(unload_dll)
1095 {
1096     process_unload_dll( current->process, req->base );
1097 }
1098
1099 /* retrieve information about a module in a process */
1100 DECL_HANDLER(get_dll_info)
1101 {
1102     struct process *process;
1103
1104     if ((process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION )))
1105     {
1106         struct process_dll *dll = find_process_dll( process, req->base_address );
1107
1108         if (dll)
1109         {
1110             reply->size = dll->size;
1111             reply->entry_point = NULL; /* FIXME */
1112             if (dll->filename)
1113             {
1114                 data_size_t len = min( dll->namelen, get_reply_max_size() );
1115                 set_reply_data( dll->filename, len );
1116             }
1117         }
1118         else
1119             set_error( STATUS_DLL_NOT_FOUND );
1120
1121         release_object( process );
1122     }
1123 }
1124
1125 /* retrieve the process idle event */
1126 DECL_HANDLER(get_process_idle_event)
1127 {
1128     struct process *process;
1129
1130     reply->event = 0;
1131     if ((process = get_process_from_handle( req->handle, PROCESS_QUERY_INFORMATION )))
1132     {
1133         if (process->idle_event && process != current->process)
1134             reply->event = alloc_handle( current->process, process->idle_event,
1135                                          EVENT_ALL_ACCESS, 0 );
1136         release_object( process );
1137     }
1138 }