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