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