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