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