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