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