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