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