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