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