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