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