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