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