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