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