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