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