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