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