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