Merge pull request #1081 from rneatherway/bug17537
[mono.git] / mono / io-layer / processes.c
1 /*
2  * processes.c:  Process handles
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * (C) 2002-2011 Novell, Inc.
8  * Copyright 2011 Xamarin Inc
9  */
10
11 #include <config.h>
12 #include <glib.h>
13 #include <stdio.h>
14 #include <string.h>
15 #include <pthread.h>
16 #include <sched.h>
17 #include <sys/time.h>
18 #include <errno.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <unistd.h>
22 #include <signal.h>
23 #include <sys/wait.h>
24 #include <sys/time.h>
25 #include <sys/resource.h>
26 #include <fcntl.h>
27 #ifdef HAVE_SYS_PARAM_H
28 #include <sys/param.h>
29 #endif
30 #include <ctype.h>
31
32 #ifdef HAVE_SYS_MKDEV_H
33 #include <sys/mkdev.h>
34 #endif
35
36 /* sys/resource.h (for rusage) is required when using osx 10.3 (but not 10.4) */
37 #ifdef __APPLE__
38 #include <TargetConditionals.h>
39 #include <sys/resource.h>
40 #ifdef HAVE_LIBPROC_H
41 /* proc_name */
42 #include <libproc.h>
43 #endif
44 #endif
45
46 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
47 #include <sys/proc.h>
48 #include <sys/sysctl.h>
49 #  if !defined(__OpenBSD__)
50 #    include <sys/utsname.h>
51 #  endif
52 #endif
53
54 #ifdef PLATFORM_SOLARIS
55 /* procfs.h cannot be included if this define is set, but it seems to work fine if it is undefined */
56 #if _FILE_OFFSET_BITS == 64
57 #undef _FILE_OFFSET_BITS
58 #include <procfs.h>
59 #define _FILE_OFFSET_BITS 64
60 #else
61 #include <procfs.h>
62 #endif
63 #endif
64
65 #ifdef __HAIKU__
66 #include <KernelKit.h>
67 #endif
68
69 #include <mono/io-layer/wapi.h>
70 #include <mono/io-layer/wapi-private.h>
71 #include <mono/io-layer/handles-private.h>
72 #include <mono/io-layer/misc-private.h>
73 #include <mono/io-layer/process-private.h>
74 #include <mono/io-layer/threads.h>
75 #include <mono/utils/strenc.h>
76 #include <mono/utils/mono-path.h>
77 #include <mono/io-layer/timefuncs-private.h>
78 #include <mono/utils/mono-time.h>
79 #include <mono/utils/mono-membar.h>
80 #include <mono/utils/mono-mutex.h>
81 #include <mono/utils/mono-signal-handler.h>
82
83 /* The process' environment strings */
84 #if defined(__APPLE__) && !defined (__arm__)
85 /* Apple defines this in crt_externs.h but doesn't provide that header for 
86  * arm-apple-darwin9.  We'll manually define the symbol on Apple as it does
87  * in fact exist on all implementations (so far) 
88  */
89 char ***_NSGetEnviron(void);
90 #define environ (*_NSGetEnviron())
91 #else
92 extern char **environ;
93 #endif
94
95 #if 0
96 #define DEBUG(...) g_message(__VA_ARGS__)
97 #define DEBUG_ENABLED 1
98 #else
99 #define DEBUG(...)
100 #endif
101
102 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable);
103 static void process_close (gpointer handle, gpointer data);
104 static gboolean is_pid_valid (pid_t pid);
105
106 #if !defined(__OpenBSD__)
107 static FILE *
108 open_process_map (int pid, const char *mode);
109 #endif
110
111 struct _WapiHandleOps _wapi_process_ops = {
112         process_close,          /* close_shared */
113         NULL,                           /* signal */
114         NULL,                           /* own */
115         NULL,                           /* is_owned */
116         process_wait,                   /* special_wait */
117         NULL                            /* prewait */   
118 };
119
120 #if HAVE_SIGACTION
121 static struct sigaction previous_chld_sa;
122 #endif
123 static mono_once_t process_sig_chld_once = MONO_ONCE_INIT;
124 static void process_add_sigchld_handler (void);
125
126 /* The signal-safe logic to use mono_processes goes like this:
127  * - The list must be safe to traverse for the signal handler at all times.
128  *   It's safe to: prepend an entry (which is a single store to 'mono_processes'),
129  *   unlink an entry (assuming the unlinked entry isn't freed and doesn't 
130  *   change its 'next' pointer so that it can still be traversed).
131  * When cleaning up we first unlink an entry, then we verify that
132  * the read lock isn't locked. Then we can free the entry, since
133  * we know that nobody is using the old version of the list (including
134  * the unlinked entry).
135  * We also need to lock when adding and cleaning up so that those two
136  * operations don't mess with eachother. (This lock is not used in the
137  * signal handler)
138  */
139 static struct MonoProcess *mono_processes = NULL;
140 static volatile gint32 mono_processes_read_lock = 0;
141 static volatile gint32 mono_processes_cleaning_up = 0;
142 static mono_mutex_t mono_processes_mutex;
143 static void mono_processes_cleanup (void);
144
145 static gpointer current_process;
146 static char *cli_launcher;
147
148 static WapiHandle_process *
149 lookup_process_handle (gpointer handle)
150 {
151         WapiHandle_process *process_data;
152         gboolean ret;
153
154         ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
155                                                            (gpointer *)&process_data);
156         if (!ret)
157                 return NULL;
158         return process_data;
159 }
160
161 /* Check if a pid is valid - i.e. if a process exists with this pid. */
162 static gboolean
163 is_pid_valid (pid_t pid)
164 {
165         gboolean result = FALSE;
166
167 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__)
168         if (((kill(pid, 0) == 0) || (errno == EPERM)) && pid != 0)
169                 result = TRUE;
170 #elif defined(__HAIKU__)
171         team_info teamInfo;
172         if (get_team_info ((team_id)pid, &teamInfo) == B_OK)
173                 result = TRUE;
174 #else
175         char *dir = g_strdup_printf ("/proc/%d", pid);
176         if (!access (dir, F_OK))
177                 result = TRUE;
178         g_free (dir);
179 #endif
180         
181         return result;
182 }
183
184 static void
185 process_set_defaults (WapiHandle_process *process_handle)
186 {
187         /* These seem to be the defaults on w2k */
188         process_handle->min_working_set = 204800;
189         process_handle->max_working_set = 1413120;
190         
191         _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
192 }
193
194 static int
195 len16 (const gunichar2 *str)
196 {
197         int len = 0;
198         
199         while (*str++ != 0)
200                 len++;
201
202         return len;
203 }
204
205 static gunichar2 *
206 utf16_concat (const gunichar2 *first, ...)
207 {
208         va_list args;
209         int total = 0, i;
210         const gunichar2 *s;
211         gunichar2 *ret;
212
213         va_start (args, first);
214         total += len16 (first);
215         for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
216                 total += len16 (s);
217         }
218         va_end (args);
219
220         ret = g_new (gunichar2, total + 1);
221         if (ret == NULL)
222                 return NULL;
223
224         ret [total] = 0;
225         i = 0;
226         for (s = first; *s != 0; s++)
227                 ret [i++] = *s;
228         va_start (args, first);
229         for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
230                 const gunichar2 *p;
231                 
232                 for (p = s; *p != 0; p++)
233                         ret [i++] = *p;
234         }
235         va_end (args);
236         
237         return ret;
238 }
239
240 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
241 static const gunichar2 *utf16_space = utf16_space_bytes; 
242 static const gunichar2 utf16_quote_bytes [2] = { 0x22, 0 };
243 static const gunichar2 *utf16_quote = utf16_quote_bytes;
244
245 #ifdef DEBUG_ENABLED
246 /* Useful in gdb */
247 void
248 print_utf16 (gunichar2 *str)
249 {
250         char *res;
251
252         res = g_utf16_to_utf8 (str, -1, NULL, NULL, NULL);
253         g_print ("%s\n", res);
254         g_free (res);
255 }
256 #endif
257
258 /* Implemented as just a wrapper around CreateProcess () */
259 gboolean
260 ShellExecuteEx (WapiShellExecuteInfo *sei)
261 {
262         gboolean ret;
263         WapiProcessInformation process_info;
264         gunichar2 *args;
265         
266         if (sei == NULL) {
267                 /* w2k just segfaults here, but we can do better than
268                  * that
269                  */
270                 SetLastError (ERROR_INVALID_PARAMETER);
271                 return FALSE;
272         }
273
274         if (sei->lpFile == NULL)
275                 /* w2k returns TRUE for this, for some reason. */
276                 return TRUE;
277         
278         /* Put both executable and parameters into the second argument
279          * to CreateProcess (), so it searches $PATH.  The conversion
280          * into and back out of utf8 is because there is no
281          * g_strdup_printf () equivalent for gunichar2 :-(
282          */
283         args = utf16_concat (utf16_quote, sei->lpFile, utf16_quote, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
284         if (args == NULL) {
285                 SetLastError (ERROR_INVALID_DATA);
286                 return FALSE;
287         }
288         ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
289                              CREATE_UNICODE_ENVIRONMENT, NULL,
290                              sei->lpDirectory, NULL, &process_info);
291         g_free (args);
292
293         if (!ret && GetLastError () == ERROR_OUTOFMEMORY)
294                 return ret;
295         
296         if (!ret) {
297                 static char *handler;
298                 static gunichar2 *handler_utf16;
299                 
300                 if (handler_utf16 == (gunichar2 *)-1)
301                         return FALSE;
302
303 #ifdef PLATFORM_MACOSX
304                 handler = g_strdup ("/usr/bin/open");
305 #else
306                 /*
307                  * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
308                  * if that fails, try to use gnome-open, then kfmclient
309                  */
310                 handler = g_find_program_in_path ("xdg-open");
311                 if (handler == NULL){
312                         handler = g_find_program_in_path ("gnome-open");
313                         if (handler == NULL){
314                                 handler = g_find_program_in_path ("kfmclient");
315                                 if (handler == NULL){
316                                         handler_utf16 = (gunichar2 *) -1;
317                                         return FALSE;
318                                 } else {
319                                         /* kfmclient needs exec argument */
320                                         char *old = handler;
321                                         handler = g_strconcat (old, " exec",
322                                                                NULL);
323                                         g_free (old);
324                                 }
325                         }
326                 }
327 #endif
328                 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
329                 g_free (handler);
330
331                 /* Put quotes around the filename, in case it's a url
332                  * that contains #'s (CreateProcess() calls
333                  * g_shell_parse_argv(), which deliberately throws
334                  * away anything after an unquoted #).  Fixes bug
335                  * 371567.
336                  */
337                 args = utf16_concat (handler_utf16, utf16_space, utf16_quote,
338                                      sei->lpFile, utf16_quote,
339                                      sei->lpParameters == NULL ? NULL : utf16_space,
340                                      sei->lpParameters, NULL);
341                 if (args == NULL) {
342                         SetLastError (ERROR_INVALID_DATA);
343                         return FALSE;
344                 }
345                 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
346                                      CREATE_UNICODE_ENVIRONMENT, NULL,
347                                      sei->lpDirectory, NULL, &process_info);
348                 g_free (args);
349                 if (!ret) {
350                         if (GetLastError () != ERROR_OUTOFMEMORY)
351                                 SetLastError (ERROR_INVALID_DATA);
352                         return FALSE;
353                 }
354                 /* Shell exec should not return a process handle when it spawned a GUI thing, like a browser. */
355                 CloseHandle (process_info.hProcess);
356                 process_info.hProcess = NULL;
357         }
358         
359         if (sei->fMask & SEE_MASK_NOCLOSEPROCESS)
360                 sei->hProcess = process_info.hProcess;
361         else
362                 CloseHandle (process_info.hProcess);
363         
364         return ret;
365 }
366
367 static gboolean
368 is_managed_binary (const char *filename)
369 {
370         int original_errno = errno;
371 #if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
372         int file = open (filename, O_RDONLY | O_LARGEFILE);
373 #else
374         int file = open (filename, O_RDONLY);
375 #endif
376         off_t new_offset;
377         unsigned char buffer[8];
378         off_t file_size, optional_header_offset;
379         off_t pe_header_offset;
380         gboolean managed = FALSE;
381         int num_read;
382         guint32 first_word, second_word;
383         
384         /* If we are unable to open the file, then we definitely
385          * can't say that it is managed. The child mono process
386          * probably wouldn't be able to open it anyway.
387          */
388         if (file < 0) {
389                 errno = original_errno;
390                 return FALSE;
391         }
392
393         /* Retrieve the length of the file for future sanity checks. */
394         file_size = lseek (file, 0, SEEK_END);
395         lseek (file, 0, SEEK_SET);
396
397         /* We know we need to read a header field at offset 60. */
398         if (file_size < 64)
399                 goto leave;
400
401         num_read = read (file, buffer, 2);
402
403         if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
404                 goto leave;
405
406         new_offset = lseek (file, 60, SEEK_SET);
407
408         if (new_offset != 60)
409                 goto leave;
410         
411         num_read = read (file, buffer, 4);
412
413         if (num_read != 4)
414                 goto leave;
415         pe_header_offset =  buffer[0]
416                 | (buffer[1] <<  8)
417                 | (buffer[2] << 16)
418                 | (buffer[3] << 24);
419         
420         if (pe_header_offset + 24 > file_size)
421                 goto leave;
422
423         new_offset = lseek (file, pe_header_offset, SEEK_SET);
424
425         if (new_offset != pe_header_offset)
426                 goto leave;
427
428         num_read = read (file, buffer, 4);
429
430         if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
431                 goto leave;
432
433         /*
434          * Verify that the header we want in the optional header data
435          * is present in this binary.
436          */
437         new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
438
439         if (new_offset != pe_header_offset + 20)
440                 goto leave;
441
442         num_read = read (file, buffer, 2);
443
444         if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
445                 goto leave;
446
447         /* Read the CLR header address and size fields. These will be
448          * zero if the binary is not managed.
449          */
450         optional_header_offset = pe_header_offset + 24;
451         new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
452
453         if (new_offset != optional_header_offset + 208)
454                 goto leave;
455
456         num_read = read (file, buffer, 8);
457         
458         /* We are not concerned with endianness, only with
459          * whether it is zero or not.
460          */
461         first_word = *(guint32 *)&buffer[0];
462         second_word = *(guint32 *)&buffer[4];
463         
464         if ((num_read != 8) || (first_word == 0) || (second_word == 0))
465                 goto leave;
466         
467         managed = TRUE;
468
469 leave:
470         close (file);
471         errno = original_errno;
472         return managed;
473 }
474
475 gboolean
476 CreateProcessWithLogonW (const gunichar2 *username,
477                                                  const gunichar2 *domain,
478                                                  const gunichar2 *password,
479                                                  const guint32 logonFlags,
480                                                  const gunichar2 *appname,
481                                                  const gunichar2 *cmdline,
482                                                  guint32 create_flags,
483                                                  gpointer env,
484                                                  const gunichar2 *cwd,
485                                                  WapiStartupInfo *startup,
486                                                  WapiProcessInformation *process_info)
487 {
488         /* FIXME: use user information */
489         return CreateProcess (appname, cmdline, NULL, NULL, FALSE, create_flags, env, cwd, startup, process_info);
490 }
491
492 static gboolean
493 is_readable (const char *prog)
494 {
495         struct stat buf;
496         if (access (prog, R_OK) != 0)
497                 return FALSE;
498         if (stat (prog, &buf))
499                 return FALSE;
500         if (S_ISREG (buf.st_mode))
501                 return TRUE;
502         return FALSE;
503 }
504
505 static gboolean
506 is_executable (const char *prog)
507 {
508         struct stat buf;
509         if (access (prog, X_OK) != 0)
510                 return FALSE;
511         if (stat (prog, &buf))
512                 return FALSE;
513         if (S_ISREG (buf.st_mode))
514                 return TRUE;
515         return FALSE;
516 }
517
518 static void
519 switch_dir_separators (char *path)
520 {
521         size_t i, pathLength = strlen(path);
522         
523         /* Turn all the slashes round the right way, except for \' */
524         /* There are probably other characters that need to be excluded as well. */
525         for (i = 0; i < pathLength; i++) {
526                 if (path[i] == '\\' && i < pathLength - 1 && path[i+1] != '\'' )
527                         path[i] = '/';
528         }
529 }
530
531 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
532                         WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
533                         WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
534                         gboolean inherit_handles, guint32 create_flags,
535                         gpointer new_environ, const gunichar2 *cwd,
536                         WapiStartupInfo *startup,
537                         WapiProcessInformation *process_info)
538 {
539         char *cmd = NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL;
540         char *dir = NULL, **env_strings = NULL, **argv = NULL;
541         guint32 i, env_count = 0;
542         gboolean ret = FALSE;
543         gpointer handle;
544         WapiHandle_process process_handle = {0}, *process_handle_data;
545         GError *gerr = NULL;
546         int in_fd, out_fd, err_fd;
547         pid_t pid;
548         int thr_ret;
549         int startup_pipe [2] = {-1, -1};
550         int dummy;
551         struct MonoProcess *mono_process;
552         gboolean fork_failed = FALSE;
553
554         mono_once (&process_sig_chld_once, process_add_sigchld_handler);
555
556         /* appname and cmdline specify the executable and its args:
557          *
558          * If appname is not NULL, it is the name of the executable.
559          * Otherwise the executable is the first token in cmdline.
560          *
561          * Executable searching:
562          *
563          * If appname is not NULL, it can specify the full path and
564          * file name, or else a partial name and the current directory
565          * will be used.  There is no additional searching.
566          *
567          * If appname is NULL, the first whitespace-delimited token in
568          * cmdline is used.  If the name does not contain a full
569          * directory path, the search sequence is:
570          *
571          * 1) The directory containing the current process
572          * 2) The current working directory
573          * 3) The windows system directory  (Ignored)
574          * 4) The windows directory (Ignored)
575          * 5) $PATH
576          *
577          * Just to make things more interesting, tokens can contain
578          * white space if they are surrounded by quotation marks.  I'm
579          * beginning to understand just why windows apps are generally
580          * so crap, with an API like this :-(
581          */
582         if (appname != NULL) {
583                 cmd = mono_unicode_to_external (appname);
584                 if (cmd == NULL) {
585                         DEBUG ("%s: unicode conversion returned NULL",
586                                    __func__);
587
588                         SetLastError (ERROR_PATH_NOT_FOUND);
589                         goto free_strings;
590                 }
591
592                 switch_dir_separators(cmd);
593         }
594         
595         if (cmdline != NULL) {
596                 args = mono_unicode_to_external (cmdline);
597                 if (args == NULL) {
598                         DEBUG ("%s: unicode conversion returned NULL", __func__);
599
600                         SetLastError (ERROR_PATH_NOT_FOUND);
601                         goto free_strings;
602                 }
603         }
604
605         if (cwd != NULL) {
606                 dir = mono_unicode_to_external (cwd);
607                 if (dir == NULL) {
608                         DEBUG ("%s: unicode conversion returned NULL", __func__);
609
610                         SetLastError (ERROR_PATH_NOT_FOUND);
611                         goto free_strings;
612                 }
613
614                 /* Turn all the slashes round the right way */
615                 switch_dir_separators(dir);
616         }
617         
618
619         /* We can't put off locating the executable any longer :-( */
620         if (cmd != NULL) {
621                 char *unquoted;
622                 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
623                         /* Strip off the drive letter.  I can't
624                          * believe that CP/M holdover is still
625                          * visible...
626                          */
627                         g_memmove (cmd, cmd+2, strlen (cmd)-2);
628                         cmd[strlen (cmd)-2] = '\0';
629                 }
630
631                 unquoted = g_shell_unquote (cmd, NULL);
632                 if (unquoted[0] == '/') {
633                         /* Assume full path given */
634                         prog = g_strdup (unquoted);
635
636                         /* Executable existing ? */
637                         if (!is_readable (prog)) {
638                                 DEBUG ("%s: Couldn't find executable %s",
639                                            __func__, prog);
640                                 g_free (unquoted);
641                                 SetLastError (ERROR_FILE_NOT_FOUND);
642                                 goto free_strings;
643                         }
644                 } else {
645                         /* Search for file named by cmd in the current
646                          * directory
647                          */
648                         char *curdir = g_get_current_dir ();
649
650                         prog = g_strdup_printf ("%s/%s", curdir, unquoted);
651                         g_free (curdir);
652
653                         /* And make sure it's readable */
654                         if (!is_readable (prog)) {
655                                 DEBUG ("%s: Couldn't find executable %s",
656                                            __func__, prog);
657                                 g_free (unquoted);
658                                 SetLastError (ERROR_FILE_NOT_FOUND);
659                                 goto free_strings;
660                         }
661                 }
662                 g_free (unquoted);
663
664                 args_after_prog = args;
665         } else {
666                 char *token = NULL;
667                 char quote;
668                 
669                 /* Dig out the first token from args, taking quotation
670                  * marks into account
671                  */
672
673                 /* First, strip off all leading whitespace */
674                 args = g_strchug (args);
675                 
676                 /* args_after_prog points to the contents of args
677                  * after token has been set (otherwise argv[0] is
678                  * duplicated)
679                  */
680                 args_after_prog = args;
681
682                 /* Assume the opening quote will always be the first
683                  * character
684                  */
685                 if (args[0] == '\"' || args [0] == '\'') {
686                         quote = args [0];
687                         for (i = 1; args[i] != '\0' && args[i] != quote; i++);
688                         if (args [i + 1] == '\0' || g_ascii_isspace (args[i+1])) {
689                                 /* We found the first token */
690                                 token = g_strndup (args+1, i-1);
691                                 args_after_prog = g_strchug (args + i + 1);
692                         } else {
693                                 /* Quotation mark appeared in the
694                                  * middle of the token.  Just give the
695                                  * whole first token, quotes and all,
696                                  * to exec.
697                                  */
698                         }
699                 }
700                 
701                 if (token == NULL) {
702                         /* No quote mark, or malformed */
703                         for (i = 0; args[i] != '\0'; i++) {
704                                 if (g_ascii_isspace (args[i])) {
705                                         token = g_strndup (args, i);
706                                         args_after_prog = args + i + 1;
707                                         break;
708                                 }
709                         }
710                 }
711
712                 if (token == NULL && args[0] != '\0') {
713                         /* Must be just one token in the string */
714                         token = g_strdup (args);
715                         args_after_prog = NULL;
716                 }
717                 
718                 if (token == NULL) {
719                         /* Give up */
720                         DEBUG ("%s: Couldn't find what to exec", __func__);
721
722                         SetLastError (ERROR_PATH_NOT_FOUND);
723                         goto free_strings;
724                 }
725                 
726                 /* Turn all the slashes round the right way. Only for
727                  * the prg. name
728                  */
729                 switch_dir_separators(token);
730
731                 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
732                         /* Strip off the drive letter.  I can't
733                          * believe that CP/M holdover is still
734                          * visible...
735                          */
736                         g_memmove (token, token+2, strlen (token)-2);
737                         token[strlen (token)-2] = '\0';
738                 }
739
740                 if (token[0] == '/') {
741                         /* Assume full path given */
742                         prog = g_strdup (token);
743                         
744                         /* Executable existing ? */
745                         if (!is_readable (prog)) {
746                                 DEBUG ("%s: Couldn't find executable %s",
747                                            __func__, token);
748                                 g_free (token);
749                                 SetLastError (ERROR_FILE_NOT_FOUND);
750                                 goto free_strings;
751                         }
752                 } else {
753                         char *curdir = g_get_current_dir ();
754
755                         /* FIXME: Need to record the directory
756                          * containing the current process, and check
757                          * that for the new executable as the first
758                          * place to look
759                          */
760
761                         prog = g_strdup_printf ("%s/%s", curdir, token);
762                         g_free (curdir);
763
764                         /* I assume X_OK is the criterion to use,
765                          * rather than F_OK
766                          *
767                          * X_OK is too strict *if* the target is a CLR binary
768                          */
769                         if (!is_readable (prog)) {
770                                 g_free (prog);
771                                 prog = g_find_program_in_path (token);
772                                 if (prog == NULL) {
773                                         DEBUG ("%s: Couldn't find executable %s", __func__, token);
774
775                                         g_free (token);
776                                         SetLastError (ERROR_FILE_NOT_FOUND);
777                                         goto free_strings;
778                                 }
779                         }
780                 }
781
782                 g_free (token);
783         }
784
785         DEBUG ("%s: Exec prog [%s] args [%s]", __func__, prog,
786                    args_after_prog);
787         
788         /* Check for CLR binaries; if found, we will try to invoke
789          * them using the same mono binary that started us.
790          */
791         if (is_managed_binary (prog)) {
792                 gunichar2 *newapp = NULL, *newcmd;
793                 gsize bytes_ignored;
794
795                 if (cli_launcher)
796                         newapp = mono_unicode_from_external (cli_launcher, &bytes_ignored);
797                 else
798                         newapp = mono_unicode_from_external ("mono", &bytes_ignored);
799
800                 if (newapp != NULL) {
801                         if (appname != NULL) {
802                                 newcmd = utf16_concat (newapp, utf16_space,
803                                                        appname, utf16_space,
804                                                        cmdline, NULL);
805                         } else {
806                                 newcmd = utf16_concat (newapp, utf16_space,
807                                                        cmdline, NULL);
808                         }
809                         
810                         g_free ((gunichar2 *)newapp);
811                         
812                         if (newcmd != NULL) {
813                                 ret = CreateProcess (NULL, newcmd,
814                                                      process_attrs,
815                                                      thread_attrs,
816                                                      inherit_handles,
817                                                      create_flags, new_environ,
818                                                      cwd, startup,
819                                                      process_info);
820                                 
821                                 g_free ((gunichar2 *)newcmd);
822                                 
823                                 goto free_strings;
824                         }
825                 }
826         } else {
827                 if (!is_executable (prog)) {
828                         DEBUG ("%s: Executable permisson not set on %s", __func__, prog);
829                         g_free (prog);
830                         SetLastError (ERROR_ACCESS_DENIED);
831                         goto free_strings;
832                 }
833         }
834
835         if (args_after_prog != NULL && *args_after_prog) {
836                 char *qprog;
837
838                 qprog = g_shell_quote (prog);
839                 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
840                 g_free (qprog);
841         } else {
842                 full_prog = g_shell_quote (prog);
843         }
844
845         ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
846         if (ret == FALSE) {
847                 g_message ("CreateProcess: %s\n", gerr->message);
848                 g_error_free (gerr);
849                 gerr = NULL;
850                 goto free_strings;
851         }
852
853         if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
854                 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
855                 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
856                 err_fd = GPOINTER_TO_UINT (startup->hStdError);
857         } else {
858                 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
859                 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
860                 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
861         }
862         
863         process_handle.proc_name = g_strdup (prog);
864
865         process_set_defaults (&process_handle);
866         
867         handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
868         if (handle == _WAPI_HANDLE_INVALID) {
869                 g_warning ("%s: error creating process handle", __func__);
870
871                 ret = FALSE;
872                 SetLastError (ERROR_OUTOFMEMORY);
873                 goto free_strings;
874         }
875
876         /* new_environ is a block of NULL-terminated strings, which
877          * is itself NULL-terminated. Of course, passing an array of
878          * string pointers would have made things too easy :-(
879          *
880          * If new_environ is not NULL it specifies the entire set of
881          * environment variables in the new process.  Otherwise the
882          * new process inherits the same environment.
883          */
884         if (new_environ) {
885                 gunichar2 *new_environp;
886
887                 /* Count the number of strings */
888                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
889                      new_environp++) {
890                         env_count++;
891                         while (*new_environp) {
892                                 new_environp++;
893                         }
894                 }
895
896                 /* +2: one for the process handle value, and the last
897                  * one is NULL
898                  */
899                 env_strings = g_new0 (char *, env_count + 2);
900                 
901                 /* Copy each environ string into 'strings' turning it
902                  * into utf8 (or the requested encoding) at the same
903                  * time
904                  */
905                 env_count = 0;
906                 for (new_environp = (gunichar2 *)new_environ; *new_environp;
907                      new_environp++) {
908                         env_strings[env_count] = mono_unicode_to_external (new_environp);
909                         env_count++;
910                         while (*new_environp) {
911                                 new_environp++;
912                         }
913                 }
914         } else {
915                 for (i = 0; environ[i] != NULL; i++)
916                         env_count++;
917
918                 /* +2: one for the process handle value, and the last
919                  * one is NULL
920                  */
921                 env_strings = g_new0 (char *, env_count + 2);
922                 
923                 /* Copy each environ string into 'strings' turning it
924                  * into utf8 (or the requested encoding) at the same
925                  * time
926                  */
927                 env_count = 0;
928                 for (i = 0; environ[i] != NULL; i++) {
929                         env_strings[env_count] = g_strdup (environ[i]);
930                         env_count++;
931                 }
932         }
933
934         /* Create a pipe to make sure the child doesn't exit before 
935          * we can add the process to the linked list of mono_processes */
936         if (pipe (startup_pipe) == -1) {
937                 /* Could not create the pipe to synchroniz process startup. We'll just not synchronize.
938                  * This is just for a very hard to hit race condition in the first place */
939                 startup_pipe [0] = startup_pipe [1] = -1;
940                 DEBUG ("%s: new process startup not synchronized. We may not notice if the newly created process exits immediately.", __func__);
941         }
942
943         thr_ret = _wapi_handle_lock_shared_handles ();
944         g_assert (thr_ret == 0);
945         
946         pid = fork ();
947         if (pid == -1) {
948                 /* Error */
949                 SetLastError (ERROR_OUTOFMEMORY);
950                 ret = FALSE;
951                 fork_failed = TRUE;
952                 goto cleanup;
953         } else if (pid == 0) {
954                 /* Child */
955                 
956                 if (startup_pipe [0] != -1) {
957                         /* Wait until the parent has updated it's internal data */
958                         ssize_t _i G_GNUC_UNUSED = read (startup_pipe [0], &dummy, 1);
959                         DEBUG ("%s: child: parent has completed its setup", __func__);
960                         close (startup_pipe [0]);
961                         close (startup_pipe [1]);
962                 }
963                 
964                 /* should we detach from the process group? */
965
966                 /* Connect stdin, stdout and stderr */
967                 dup2 (in_fd, 0);
968                 dup2 (out_fd, 1);
969                 dup2 (err_fd, 2);
970
971                 if (inherit_handles != TRUE) {
972                         /* FIXME: do something here */
973                 }
974                 
975                 /* Close all file descriptors */
976                 for (i = wapi_getdtablesize () - 1; i > 2; i--)
977                         close (i);
978
979 #ifdef DEBUG_ENABLED
980                 DEBUG ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
981                            dir == NULL?".":dir);
982                 for (i = 0; argv[i] != NULL; i++)
983                         g_message ("arg %d: [%s]", i, argv[i]);
984                 
985                 for (i = 0; env_strings[i] != NULL; i++)
986                         g_message ("env %d: [%s]", i, env_strings[i]);
987 #endif
988
989                 /* set cwd */
990                 if (dir != NULL && chdir (dir) == -1) {
991                         /* set error */
992                         _exit (-1);
993                 }
994                 
995                 /* exec */
996                 execve (argv[0], argv, env_strings);
997                 
998                 /* set error */
999                 _exit (-1);
1000         }
1001         /* parent */
1002         
1003         process_handle_data = lookup_process_handle (handle);
1004         if (!process_handle_data) {
1005                 g_warning ("%s: error looking up process handle %p", __func__,
1006                            handle);
1007                 _wapi_handle_unref (handle);
1008                 goto cleanup;
1009         }
1010         
1011         process_handle_data->id = pid;
1012
1013         /* Add our mono_process into the linked list of mono_processes */
1014         mono_process = (struct MonoProcess *) g_malloc0 (sizeof (struct MonoProcess));
1015         mono_process->pid = pid;
1016         mono_process->handle_count = 1;
1017         if (MONO_SEM_INIT (&mono_process->exit_sem, 0) != 0) {
1018                 /* If we can't create the exit semaphore, we just don't add anything
1019                  * to our list of mono processes. Waiting on the process will return 
1020                  * immediately. */
1021                 g_warning ("%s: could not create exit semaphore for process.", strerror (errno));
1022                 g_free (mono_process);
1023         } else {
1024                 /* Keep the process handle artificially alive until the process
1025                  * exits so that the information in the handle isn't lost. */
1026                 _wapi_handle_ref (handle);
1027                 mono_process->handle = handle;
1028
1029                 process_handle_data->mono_process = mono_process;
1030
1031                 mono_mutex_lock (&mono_processes_mutex);
1032                 mono_process->next = mono_processes;
1033                 mono_processes = mono_process;
1034                 mono_mutex_unlock (&mono_processes_mutex);
1035         }
1036         
1037         if (process_info != NULL) {
1038                 process_info->hProcess = handle;
1039                 process_info->dwProcessId = pid;
1040
1041                 /* FIXME: we might need to handle the thread info some
1042                  * day
1043                  */
1044                 process_info->hThread = INVALID_HANDLE_VALUE;
1045                 process_info->dwThreadId = 0;
1046         }
1047
1048 cleanup:
1049         _wapi_handle_unlock_shared_handles ();
1050
1051         if (fork_failed)
1052                 _wapi_handle_unref (handle);
1053
1054         if (startup_pipe [1] != -1) {
1055                 /* Write 1 byte, doesn't matter what */
1056                 ssize_t _i G_GNUC_UNUSED = write (startup_pipe [1], startup_pipe, 1);
1057                 close (startup_pipe [0]);
1058                 close (startup_pipe [1]);
1059         }
1060
1061 free_strings:
1062         if (cmd)
1063                 g_free (cmd);
1064         if (full_prog)
1065                 g_free (full_prog);
1066         if (prog)
1067                 g_free (prog);
1068         if (args)
1069                 g_free (args);
1070         if (dir)
1071                 g_free (dir);
1072         if (env_strings)
1073                 g_strfreev (env_strings);
1074         if (argv)
1075                 g_strfreev (argv);
1076         
1077         DEBUG ("%s: returning handle %p for pid %d", __func__, handle,
1078                    pid);
1079
1080         /* Check if something needs to be cleaned up. */
1081         mono_processes_cleanup ();
1082         
1083         return ret;
1084 }
1085                 
1086 static void
1087 process_set_name (WapiHandle_process *process_handle)
1088 {
1089         char *progname, *utf8_progname, *slash;
1090         
1091         progname = g_get_prgname ();
1092         utf8_progname = mono_utf8_from_external (progname);
1093
1094         DEBUG ("%s: using [%s] as prog name", __func__, progname);
1095
1096         if (utf8_progname) {
1097                 slash = strrchr (utf8_progname, '/');
1098                 if (slash)
1099                         process_handle->proc_name = g_strdup (slash+1);
1100                 else
1101                         process_handle->proc_name = g_strdup (utf8_progname);
1102                 g_free (utf8_progname);
1103         }
1104 }
1105
1106 void
1107 wapi_processes_init (void)
1108 {
1109         pid_t pid = _wapi_getpid ();
1110         WapiHandle_process process_handle = {0};
1111
1112         _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
1113                                             WAPI_HANDLE_CAP_WAIT |
1114                                             WAPI_HANDLE_CAP_SPECIAL_WAIT);
1115         
1116         process_handle.id = pid;
1117
1118         process_set_defaults (&process_handle);
1119         process_set_name (&process_handle);
1120
1121         current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1122                                             &process_handle);
1123         g_assert (current_process);
1124 }
1125
1126 gpointer
1127 _wapi_process_duplicate (void)
1128 {
1129         _wapi_handle_ref (current_process);
1130         
1131         return current_process;
1132 }
1133
1134 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1135 gpointer
1136 GetCurrentProcess (void)
1137 {
1138         return _WAPI_PROCESS_CURRENT;
1139 }
1140
1141 guint32
1142 GetProcessId (gpointer handle)
1143 {
1144         WapiHandle_process *process_handle;
1145
1146         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1147                 /* This is a pseudo handle */
1148                 return WAPI_HANDLE_TO_PID (handle);
1149         
1150         process_handle = lookup_process_handle (handle);
1151         if (!process_handle) {
1152                 SetLastError (ERROR_INVALID_HANDLE);
1153                 return 0;
1154         }
1155         
1156         return process_handle->id;
1157 }
1158
1159 static gboolean
1160 process_open_compare (gpointer handle, gpointer user_data)
1161 {
1162         pid_t wanted_pid;
1163         WapiHandle_process *process_handle;
1164         pid_t checking_pid;
1165
1166         g_assert (!WAPI_IS_PSEUDO_PROCESS_HANDLE (handle));
1167         
1168         process_handle = lookup_process_handle (handle);
1169         g_assert (process_handle);
1170         
1171         DEBUG ("%s: looking at process %d", __func__, process_handle->id);
1172
1173         checking_pid = process_handle->id;
1174
1175         if (checking_pid == 0)
1176                 return FALSE;
1177         
1178         wanted_pid = GPOINTER_TO_UINT (user_data);
1179
1180         /* It's possible to have more than one process handle with the
1181          * same pid, but only the one running process can be
1182          * unsignalled
1183          */
1184         if (checking_pid == wanted_pid &&
1185             !_wapi_handle_issignalled (handle)) {
1186                 /* If the handle is blown away in the window between
1187                  * returning TRUE here and _wapi_search_handle pinging
1188                  * the timestamp, the search will continue
1189                  */
1190                 return TRUE;
1191         } else {
1192                 return FALSE;
1193         }
1194 }
1195
1196 gboolean
1197 CloseProcess (gpointer handle)
1198 {
1199         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (handle))
1200                 return TRUE;
1201         return CloseHandle (handle);
1202 }
1203
1204 /*
1205  * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1206  */
1207 gpointer
1208 OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1209 {
1210         /* Find the process handle that corresponds to pid */
1211         gpointer handle = NULL;
1212         
1213         DEBUG ("%s: looking for process %d", __func__, pid);
1214
1215         handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1216                                       process_open_compare,
1217                                       GUINT_TO_POINTER (pid), NULL, TRUE);
1218         if (handle == 0) {
1219                 if (is_pid_valid (pid)) {
1220                         /* Return a pseudo handle for processes we
1221                          * don't have handles for
1222                          */
1223                         return WAPI_PID_TO_HANDLE (pid);
1224                 } else {
1225                         DEBUG ("%s: Can't find pid %d", __func__, pid);
1226
1227                         SetLastError (ERROR_PROC_NOT_FOUND);
1228         
1229                         return NULL;
1230                 }
1231         }
1232
1233         /* _wapi_search_handle () already added a ref */
1234         return handle;
1235 }
1236
1237 gboolean
1238 GetExitCodeProcess (gpointer process, guint32 *code)
1239 {
1240         WapiHandle_process *process_handle;
1241         guint32 pid = -1;
1242         
1243         if (!code)
1244                 return FALSE;
1245         
1246         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1247                 pid = WAPI_HANDLE_TO_PID (process);
1248                 /* This is a pseudo handle, so we don't know what the
1249                  * exit code was, but we can check whether it's alive or not
1250                  */
1251                 if (is_pid_valid (pid)) {
1252                         *code = STILL_ACTIVE;
1253                         return TRUE;
1254                 } else {
1255                         return FALSE;
1256                 }
1257         }
1258
1259         process_handle = lookup_process_handle (process);
1260         if (!process_handle) {
1261                 DEBUG ("%s: Can't find process %p", __func__, process);
1262                 
1263                 return FALSE;
1264         }
1265         
1266         /* A process handle is only signalled if the process has exited
1267          * and has been waited for */
1268
1269         /* Make sure any process exit has been noticed, before
1270          * checking if the process is signalled.  Fixes bug 325463.
1271          */
1272         process_wait (process, 0, TRUE);
1273         
1274         if (_wapi_handle_issignalled (process))
1275                 *code = process_handle->exitstatus;
1276         else
1277                 *code = STILL_ACTIVE;
1278         
1279         return TRUE;
1280 }
1281
1282 gboolean
1283 GetProcessTimes (gpointer process, WapiFileTime *create_time,
1284                                  WapiFileTime *exit_time, WapiFileTime *kernel_time,
1285                                  WapiFileTime *user_time)
1286 {
1287         WapiHandle_process *process_handle;
1288         gboolean ku_times_set = FALSE;
1289         
1290         if (create_time == NULL || exit_time == NULL || kernel_time == NULL ||
1291                 user_time == NULL)
1292                 /* Not sure if w32 allows NULLs here or not */
1293                 return FALSE;
1294         
1295         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
1296                 /* This is a pseudo handle, so just fail for now
1297                  */
1298                 return FALSE;
1299         
1300         process_handle = lookup_process_handle (process);
1301         if (!process_handle) {
1302                 DEBUG ("%s: Can't find process %p", __func__, process);
1303                 
1304                 return FALSE;
1305         }
1306         
1307         *create_time = process_handle->create_time;
1308
1309         /* A process handle is only signalled if the process has
1310          * exited.  Otherwise exit_time isn't set
1311          */
1312         if (_wapi_handle_issignalled (process))
1313                 *exit_time = process_handle->exit_time;
1314
1315 #ifdef HAVE_GETRUSAGE
1316         if (process_handle->id == getpid ()) {
1317                 struct rusage time_data;
1318                 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1319                         guint64 tick_val;
1320                         ku_times_set = TRUE;
1321                         tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1322                         _wapi_guint64_to_filetime (tick_val, user_time);
1323                         tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1324                         _wapi_guint64_to_filetime (tick_val, kernel_time);
1325                 }
1326         }
1327 #endif
1328         if (!ku_times_set) {
1329                 memset (kernel_time, 0, sizeof (WapiFileTime));
1330                 memset (user_time, 0, sizeof (WapiFileTime));
1331         }
1332
1333         return TRUE;
1334 }
1335
1336 typedef struct
1337 {
1338         gpointer address_start;
1339         gpointer address_end;
1340         char *perms;
1341         gpointer address_offset;
1342         dev_t device;
1343         ino_t inode;
1344         char *filename;
1345 } WapiProcModule;
1346
1347 static void free_procmodule (WapiProcModule *mod)
1348 {
1349         if (mod->perms != NULL) {
1350                 g_free (mod->perms);
1351         }
1352         if (mod->filename != NULL) {
1353                 g_free (mod->filename);
1354         }
1355         g_free (mod);
1356 }
1357
1358 static gint find_procmodule (gconstpointer a, gconstpointer b)
1359 {
1360         WapiProcModule *want = (WapiProcModule *)a;
1361         WapiProcModule *compare = (WapiProcModule *)b;
1362         
1363         if ((want->device == compare->device) &&
1364             (want->inode == compare->inode)) {
1365                 return(0);
1366         } else {
1367                 return(1);
1368         }
1369 }
1370
1371 #ifdef PLATFORM_MACOSX
1372 #include <mach-o/dyld.h>
1373 #include <mach-o/getsect.h>
1374
1375 static GSList *load_modules (void)
1376 {
1377         GSList *ret = NULL;
1378         WapiProcModule *mod;
1379         uint32_t count = _dyld_image_count ();
1380         int i = 0;
1381
1382         for (i = 0; i < count; i++) {
1383 #if SIZEOF_VOID_P == 8
1384                 const struct mach_header_64 *hdr;
1385                 const struct section_64 *sec;
1386 #else
1387                 const struct mach_header *hdr;
1388                 const struct section *sec;
1389 #endif
1390                 const char *name;
1391
1392                 name = _dyld_get_image_name (i);
1393 #if SIZEOF_VOID_P == 8
1394                 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1395                 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1396 #else
1397                 hdr = _dyld_get_image_header (i);
1398                 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1399 #endif
1400
1401                 /* Some dynlibs do not have data sections on osx (#533893) */
1402                 if (sec == 0) {
1403                         continue;
1404                 }
1405                         
1406                 mod = g_new0 (WapiProcModule, 1);
1407                 mod->address_start = GINT_TO_POINTER (sec->addr);
1408                 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1409                 mod->perms = g_strdup ("r--p");
1410                 mod->address_offset = 0;
1411                 mod->device = makedev (0, 0);
1412                 mod->inode = (ino_t) i;
1413                 mod->filename = g_strdup (name); 
1414                 
1415                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1416                         ret = g_slist_prepend (ret, mod);
1417                 } else {
1418                         free_procmodule (mod);
1419                 }
1420         }
1421
1422         ret = g_slist_reverse (ret);
1423         
1424         return(ret);
1425 }
1426 #elif defined(__OpenBSD__)
1427 #include <link.h>
1428 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1429 {
1430         if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1431             + sizeof (info->dlpi_phnum))
1432                 return (-1);
1433
1434         struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1435         if (!cpy)
1436                 return (-1);
1437
1438         memcpy(cpy, info, sizeof(*info));
1439
1440         g_ptr_array_add ((GPtrArray *)ptr, cpy);
1441
1442         return (0);
1443 }
1444
1445 static GSList *load_modules (void)
1446 {
1447         GSList *ret = NULL;
1448         WapiProcModule *mod;
1449         GPtrArray *dlarray = g_ptr_array_new();
1450         int i;
1451
1452         if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1453                 return (ret);
1454
1455         for (i = 0; i < dlarray->len; i++) {
1456                 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1457
1458                 mod = g_new0 (WapiProcModule, 1);
1459                 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1460                 mod->address_end = (gpointer)(info->dlpi_addr +
1461                                        info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1462                 mod->perms = g_strdup ("r--p");
1463                 mod->address_offset = 0;
1464                 mod->inode = (ino_t) i;
1465                 mod->filename = g_strdup (info->dlpi_name); 
1466
1467                 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1468                                    mod->inode, mod->filename, mod->address_start, mod->address_end);
1469
1470                 free(info);
1471
1472                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1473                         ret = g_slist_prepend (ret, mod);
1474                 } else {
1475                         free_procmodule (mod);
1476                 }
1477         }
1478
1479         g_ptr_array_free (dlarray, TRUE);
1480
1481         ret = g_slist_reverse (ret);
1482
1483         return(ret);
1484 }
1485 #elif defined(__HAIKU__)
1486
1487 static GSList *load_modules (void)
1488 {
1489         GSList *ret = NULL;
1490         WapiProcModule *mod;
1491         int32 cookie = 0;
1492         image_info imageInfo;
1493
1494         while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1495                 mod = g_new0 (WapiProcModule, 1);
1496                 mod->device = imageInfo.device;
1497                 mod->inode = imageInfo.node;
1498                 mod->filename = g_strdup (imageInfo.name);
1499                 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1500                 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1501                         (uint8_t*)imageInfo.data + imageInfo.data_size);
1502                 mod->perms = g_strdup ("r--p");
1503                 mod->address_offset = 0;
1504
1505                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1506                         ret = g_slist_prepend (ret, mod);
1507                 } else {
1508                         free_procmodule (mod);
1509                 }
1510         }
1511
1512         ret = g_slist_reverse (ret);
1513
1514         return ret;
1515 }
1516 #else
1517 static GSList *load_modules (FILE *fp)
1518 {
1519         GSList *ret = NULL;
1520         WapiProcModule *mod;
1521         char buf[MAXPATHLEN + 1], *p, *endp;
1522         char *start_start, *end_start, *prot_start, *offset_start;
1523         char *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1524         gpointer address_start, address_end, address_offset;
1525         guint32 maj_dev, min_dev;
1526         ino_t inode;
1527         dev_t device;
1528         
1529         while (fgets (buf, sizeof(buf), fp)) {
1530                 p = buf;
1531                 while (g_ascii_isspace (*p)) ++p;
1532                 start_start = p;
1533                 if (!g_ascii_isxdigit (*start_start)) {
1534                         continue;
1535                 }
1536                 address_start = (gpointer)strtoul (start_start, &endp, 16);
1537                 p = endp;
1538                 if (*p != '-') {
1539                         continue;
1540                 }
1541                 
1542                 ++p;
1543                 end_start = p;
1544                 if (!g_ascii_isxdigit (*end_start)) {
1545                         continue;
1546                 }
1547                 address_end = (gpointer)strtoul (end_start, &endp, 16);
1548                 p = endp;
1549                 if (!g_ascii_isspace (*p)) {
1550                         continue;
1551                 }
1552                 
1553                 while (g_ascii_isspace (*p)) ++p;
1554                 prot_start = p;
1555                 if (*prot_start != 'r' && *prot_start != '-') {
1556                         continue;
1557                 }
1558                 memcpy (prot_buf, prot_start, 4);
1559                 prot_buf[4] = '\0';
1560                 while (!g_ascii_isspace (*p)) ++p;
1561                 
1562                 while (g_ascii_isspace (*p)) ++p;
1563                 offset_start = p;
1564                 if (!g_ascii_isxdigit (*offset_start)) {
1565                         continue;
1566                 }
1567                 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1568                 p = endp;
1569                 if (!g_ascii_isspace (*p)) {
1570                         continue;
1571                 }
1572                 
1573                 while(g_ascii_isspace (*p)) ++p;
1574                 maj_dev_start = p;
1575                 if (!g_ascii_isxdigit (*maj_dev_start)) {
1576                         continue;
1577                 }
1578                 maj_dev = strtoul (maj_dev_start, &endp, 16);
1579                 p = endp;
1580                 if (*p != ':') {
1581                         continue;
1582                 }
1583                 
1584                 ++p;
1585                 min_dev_start = p;
1586                 if (!g_ascii_isxdigit (*min_dev_start)) {
1587                         continue;
1588                 }
1589                 min_dev = strtoul (min_dev_start, &endp, 16);
1590                 p = endp;
1591                 if (!g_ascii_isspace (*p)) {
1592                         continue;
1593                 }
1594                 
1595                 while (g_ascii_isspace (*p)) ++p;
1596                 inode_start = p;
1597                 if (!g_ascii_isxdigit (*inode_start)) {
1598                         continue;
1599                 }
1600                 inode = (ino_t)strtol (inode_start, &endp, 10);
1601                 p = endp;
1602                 if (!g_ascii_isspace (*p)) {
1603                         continue;
1604                 }
1605
1606                 device = makedev ((int)maj_dev, (int)min_dev);
1607                 if ((device == 0) &&
1608                     (inode == 0)) {
1609                         continue;
1610                 }
1611                 
1612                 while(g_ascii_isspace (*p)) ++p;
1613                 /* p now points to the filename */
1614
1615                 mod = g_new0 (WapiProcModule, 1);
1616                 mod->address_start = address_start;
1617                 mod->address_end = address_end;
1618                 mod->perms = g_strdup (prot_buf);
1619                 mod->address_offset = address_offset;
1620                 mod->device = device;
1621                 mod->inode = inode;
1622                 mod->filename = g_strdup (g_strstrip (p));
1623                 
1624                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1625                         ret = g_slist_prepend (ret, mod);
1626                 } else {
1627                         free_procmodule (mod);
1628                 }
1629         }
1630
1631         ret = g_slist_reverse (ret);
1632         
1633         return(ret);
1634 }
1635 #endif
1636
1637 static gboolean match_procname_to_modulename (char *procname, char *modulename)
1638 {
1639         char* lastsep = NULL;
1640         char* lastsep2 = NULL;
1641         char* pname = NULL;
1642         char* mname = NULL;
1643         gboolean result = FALSE;
1644
1645         if (procname == NULL || modulename == NULL)
1646                 return (FALSE);
1647
1648         pname = mono_path_resolve_symlinks (procname);
1649         mname = mono_path_resolve_symlinks (modulename);
1650
1651         if (!strcmp (pname, mname))
1652                 result = TRUE;
1653
1654         if (!result) {
1655                 lastsep = strrchr (mname, '/');
1656                 if (lastsep)
1657                         if (!strcmp (lastsep+1, pname))
1658                                 result = TRUE;
1659                 if (!result) {
1660                         lastsep2 = strrchr (pname, '/');
1661                         if (lastsep2){
1662                                 if (lastsep) {
1663                                         if (!strcmp (lastsep+1, lastsep2+1))
1664                                                 result = TRUE;
1665                                 } else {
1666                                         if (!strcmp (mname, lastsep2+1))
1667                                                 result = TRUE;
1668                                 }
1669                         }
1670                 }
1671         }
1672
1673         g_free (pname);
1674         g_free (mname);
1675
1676         return result;
1677 }
1678
1679 #if !defined(__OpenBSD__)
1680 static FILE *
1681 open_process_map (int pid, const char *mode)
1682 {
1683         FILE *fp = NULL;
1684         const char *proc_path[] = {
1685                 "/proc/%d/maps",        /* GNU/Linux */
1686                 "/proc/%d/map",         /* FreeBSD */
1687                 NULL
1688         };
1689         int i;
1690         char *filename;
1691
1692         for (i = 0; fp == NULL && proc_path [i]; i++) {
1693                 filename = g_strdup_printf (proc_path[i], pid);
1694                 fp = fopen (filename, mode);
1695                 g_free (filename);
1696         }
1697
1698         return fp;
1699 }
1700 #endif
1701
1702 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1703                              guint32 size, guint32 *needed)
1704 {
1705         WapiHandle_process *process_handle;
1706 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
1707         FILE *fp;
1708 #endif
1709         GSList *mods = NULL;
1710         WapiProcModule *module;
1711         guint32 count, avail = size / sizeof(gpointer);
1712         int i;
1713         pid_t pid;
1714         char *proc_name = NULL;
1715         
1716         /* Store modules in an array of pointers (main module as
1717          * modules[0]), using the load address for each module as a
1718          * token.  (Use 'NULL' as an alternative for the main module
1719          * so that the simple implementation can just return one item
1720          * for now.)  Get the info from /proc/<pid>/maps on linux,
1721          * /proc/<pid>/map on FreeBSD, other systems will have to
1722          * implement /dev/kmem reading or whatever other horrid
1723          * technique is needed.
1724          */
1725         if (size < sizeof(gpointer))
1726                 return FALSE;
1727
1728         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
1729                 pid = WAPI_HANDLE_TO_PID (process);
1730         } else {
1731                 process_handle = lookup_process_handle (process);
1732                 if (!process_handle) {
1733                         DEBUG ("%s: Can't find process %p", __func__, process);
1734                 
1735                         return FALSE;
1736                 }
1737                 pid = process_handle->id;
1738                 proc_name = process_handle->proc_name;
1739         }
1740         
1741 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
1742         mods = load_modules ();
1743         if (!proc_name) {
1744                 modules[0] = NULL;
1745                 *needed = sizeof(gpointer);
1746                 return TRUE;
1747         }
1748 #else
1749         fp = open_process_map (pid, "r");
1750         if (!fp) {
1751                 /* No /proc/<pid>/maps so just return the main module
1752                  * shortcut for now
1753                  */
1754                 modules[0] = NULL;
1755                 *needed = sizeof(gpointer);
1756                 return TRUE;
1757         }
1758         mods = load_modules (fp);
1759         fclose (fp);
1760 #endif
1761         count = g_slist_length (mods);
1762                 
1763         /* count + 1 to leave slot 0 for the main module */
1764         *needed = sizeof(gpointer) * (count + 1);
1765
1766         /*
1767          * Use the NULL shortcut, as the first line in
1768          * /proc/<pid>/maps isn't the executable, and we need
1769          * that first in the returned list. Check the module name 
1770          * to see if it ends with the proc name and substitute 
1771          * the first entry with it.  FIXME if this turns out to 
1772          * be a problem.
1773          */
1774         modules[0] = NULL;
1775         for (i = 0; i < (avail - 1) && i < count; i++) {
1776                 module = (WapiProcModule *)g_slist_nth_data (mods, i);
1777                 if (modules[0] != NULL)
1778                         modules[i] = module->address_start;
1779                 else if (match_procname_to_modulename (proc_name, module->filename))
1780                         modules[0] = module->address_start;
1781                 else
1782                         modules[i + 1] = module->address_start;
1783         }
1784                 
1785         for (i = 0; i < count; i++) {
1786                 free_procmodule (g_slist_nth_data (mods, i));
1787         }
1788         g_slist_free (mods);
1789
1790         return TRUE;
1791 }
1792
1793 static char *
1794 get_process_name_from_proc (pid_t pid)
1795 {
1796 #if defined(__OpenBSD__)
1797         int mib [6];
1798         size_t size;
1799         struct kinfo_proc *pi;
1800 #elif defined(PLATFORM_MACOSX)
1801 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
1802         size_t size;
1803         struct kinfo_proc *pi;
1804         int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
1805 #endif
1806 #else
1807         FILE *fp;
1808         char *filename = NULL;
1809 #endif
1810         char buf[256];
1811         char *ret = NULL;
1812
1813 #if defined(PLATFORM_SOLARIS)
1814         filename = g_strdup_printf ("/proc/%d/psinfo", pid);
1815         if ((fp = fopen (filename, "r")) != NULL) {
1816                 struct psinfo info;
1817                 int nread;
1818
1819                 nread = fread (&info, sizeof (info), 1, fp);
1820                 if (nread == 1) {
1821                         ret = g_strdup (info.pr_fname);
1822                 }
1823
1824                 fclose (fp);
1825         }
1826         g_free (filename);
1827 #elif defined(PLATFORM_MACOSX)
1828 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
1829         /* No proc name on OSX < 10.5 nor ppc nor iOS */
1830         memset (buf, '\0', sizeof(buf));
1831         proc_name (pid, buf, sizeof(buf));
1832         if (strlen (buf) > 0)
1833                 ret = g_strdup (buf);
1834 #else
1835         if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
1836                 return(ret);
1837
1838         if ((pi = malloc(size)) == NULL)
1839                 return(ret);
1840
1841         if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
1842                 if (errno == ENOMEM) {
1843                         free(pi);
1844                         DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
1845                 }
1846                 return(ret);
1847         }
1848
1849         if (strlen (pi->kp_proc.p_comm) > 0)
1850                 ret = g_strdup (pi->kp_proc.p_comm);
1851
1852         free(pi);
1853 #endif
1854 #elif defined(__OpenBSD__)
1855         mib [0] = CTL_KERN;
1856         mib [1] = KERN_PROC;
1857         mib [2] = KERN_PROC_PID;
1858         mib [3] = pid;
1859         mib [4] = sizeof(struct kinfo_proc);
1860         mib [5] = 0;
1861
1862 retry:
1863         if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
1864                 return(ret);
1865
1866         if ((pi = malloc(size)) == NULL)
1867                 return(ret);
1868
1869         mib[5] = (int)(size / sizeof(struct kinfo_proc));
1870
1871         if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
1872                 (size != sizeof (struct kinfo_proc))) {
1873                 if (errno == ENOMEM) {
1874                         free(pi);
1875                         goto retry;
1876                 }
1877                 return(ret);
1878         }
1879
1880         if (strlen (pi->p_comm) > 0)
1881                 ret = g_strdup (pi->p_comm);
1882
1883         free(pi);
1884 #elif defined(__HAIKU__)
1885         image_info imageInfo;
1886         int32 cookie = 0;
1887
1888         if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
1889                 ret = g_strdup (imageInfo.name);
1890         }
1891 #else
1892         memset (buf, '\0', sizeof(buf));
1893         filename = g_strdup_printf ("/proc/%d/exe", pid);
1894         if (readlink (filename, buf, 255) > 0) {
1895                 ret = g_strdup (buf);
1896         }
1897         g_free (filename);
1898
1899         if (ret != NULL) {
1900                 return(ret);
1901         }
1902
1903         filename = g_strdup_printf ("/proc/%d/cmdline", pid);
1904         if ((fp = fopen (filename, "r")) != NULL) {
1905                 if (fgets (buf, 256, fp) != NULL) {
1906                         ret = g_strdup (buf);
1907                 }
1908                 
1909                 fclose (fp);
1910         }
1911         g_free (filename);
1912
1913         if (ret != NULL) {
1914                 return(ret);
1915         }
1916         
1917         filename = g_strdup_printf ("/proc/%d/stat", pid);
1918         if ((fp = fopen (filename, "r")) != NULL) {
1919                 if (fgets (buf, 256, fp) != NULL) {
1920                         char *start, *end;
1921                         
1922                         start = strchr (buf, '(');
1923                         if (start != NULL) {
1924                                 end = strchr (start + 1, ')');
1925                                 
1926                                 if (end != NULL) {
1927                                         ret = g_strndup (start + 1,
1928                                                          end - start - 1);
1929                                 }
1930                         }
1931                 }
1932                 
1933                 fclose (fp);
1934         }
1935         g_free (filename);
1936 #endif
1937
1938         return ret;
1939 }
1940
1941 /*
1942  * wapi_process_get_path:
1943  *
1944  *   Return the full path of the executable of the process PID, or NULL if it cannot be determined.
1945  * Returns malloc-ed memory.
1946  */
1947 char*
1948 wapi_process_get_path (pid_t pid)
1949 {
1950 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
1951         char buf [PROC_PIDPATHINFO_MAXSIZE];
1952         int res;
1953
1954         res = proc_pidpath (pid, buf, sizeof (buf));
1955         if (res <= 0)
1956                 return NULL;
1957         if (buf [0] == '\0')
1958                 return NULL;
1959         return g_strdup (buf);
1960 #else
1961         return get_process_name_from_proc (pid);
1962 #endif
1963 }
1964
1965 /*
1966  * wapi_process_set_cli_launcher:
1967  *
1968  *   Set the full path of the runtime executable used to launch managed exe's.
1969  */
1970 void
1971 wapi_process_set_cli_launcher (char *path)
1972 {
1973         g_free (cli_launcher);
1974         cli_launcher = path ? g_strdup (path) : NULL;
1975 }
1976
1977 static guint32
1978 get_module_name (gpointer process, gpointer module,
1979                                  gunichar2 *basename, guint32 size,
1980                                  gboolean base)
1981 {
1982         WapiHandle_process *process_handle;
1983         pid_t pid;
1984         gunichar2 *procname;
1985         char *procname_ext = NULL;
1986         glong len;
1987         gsize bytes;
1988 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
1989         FILE *fp;
1990 #endif
1991         GSList *mods = NULL;
1992         WapiProcModule *found_module;
1993         guint32 count;
1994         int i;
1995         char *proc_name = NULL;
1996         
1997         DEBUG ("%s: Getting module base name, process handle %p module %p",
1998                    __func__, process, module);
1999
2000         size = size * sizeof (gunichar2); /* adjust for unicode characters */
2001
2002         if (basename == NULL || size == 0)
2003                 return 0;
2004         
2005         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2006                 /* This is a pseudo handle */
2007                 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2008                 proc_name = get_process_name_from_proc (pid);
2009         } else {
2010                 process_handle = lookup_process_handle (process);
2011                 if (!process_handle) {
2012                         DEBUG ("%s: Can't find process %p", __func__,
2013                                    process);
2014                         
2015                         return 0;
2016                 }
2017                 pid = process_handle->id;
2018                 proc_name = g_strdup (process_handle->proc_name);
2019         }
2020
2021         /* Look up the address in /proc/<pid>/maps */
2022 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2023         mods = load_modules ();
2024 #else
2025         fp = open_process_map (pid, "r");
2026         if (fp == NULL) {
2027                 if (errno == EACCES && module == NULL && base == TRUE) {
2028                         procname_ext = get_process_name_from_proc (pid);
2029                 } else {
2030                         /* No /proc/<pid>/maps, so just return failure
2031                          * for now
2032                          */
2033                         g_free (proc_name);
2034                         return 0;
2035                 }
2036         } else {
2037                 mods = load_modules (fp);
2038                 fclose (fp);
2039         }
2040 #endif
2041         count = g_slist_length (mods);
2042
2043         /* If module != NULL compare the address.
2044          * If module == NULL we are looking for the main module.
2045          * The best we can do for now check it the module name end with the process name.
2046          */
2047         for (i = 0; i < count; i++) {
2048                 found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2049                 if (procname_ext == NULL &&
2050                         ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2051                          (module != NULL && found_module->address_start == module))) {
2052                         if (base)
2053                                 procname_ext = g_path_get_basename (found_module->filename);
2054                         else
2055                                 procname_ext = g_strdup (found_module->filename);
2056                 }
2057
2058                 free_procmodule (found_module);
2059         }
2060
2061         if (procname_ext == NULL) {
2062                 /* If it's *still* null, we might have hit the
2063                  * case where reading /proc/$pid/maps gives an
2064                  * empty file for this user.
2065                  */
2066                 procname_ext = get_process_name_from_proc (pid);
2067         }
2068
2069         g_slist_free (mods);
2070         g_free (proc_name);
2071
2072         if (procname_ext) {
2073                 DEBUG ("%s: Process name is [%s]", __func__,
2074                            procname_ext);
2075
2076                 procname = mono_unicode_from_external (procname_ext, &bytes);
2077                 if (procname == NULL) {
2078                         /* bugger */
2079                         g_free (procname_ext);
2080                         return 0;
2081                 }
2082                 
2083                 len = (bytes / 2);
2084                 
2085                 /* Add the terminator */
2086                 bytes += 2;
2087                 
2088                 if (size < bytes) {
2089                         DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2090
2091                         memcpy (basename, procname, size);
2092                 } else {
2093                         DEBUG ("%s: Size %d larger than needed (%ld)",
2094                                    __func__, size, bytes);
2095
2096                         memcpy (basename, procname, bytes);
2097                 }
2098                 
2099                 g_free (procname);
2100                 g_free (procname_ext);
2101                 
2102                 return len;
2103         }
2104         
2105         return 0;
2106 }
2107
2108 guint32
2109 GetModuleBaseName (gpointer process, gpointer module,
2110                                    gunichar2 *basename, guint32 size)
2111 {
2112         return get_module_name (process, module, basename, size, TRUE);
2113 }
2114
2115 guint32
2116 GetModuleFileNameEx (gpointer process, gpointer module,
2117                                          gunichar2 *filename, guint32 size)
2118 {
2119         return get_module_name (process, module, filename, size, FALSE);
2120 }
2121
2122 gboolean
2123 GetModuleInformation (gpointer process, gpointer module,
2124                                           WapiModuleInfo *modinfo, guint32 size)
2125 {
2126         WapiHandle_process *process_handle;
2127         pid_t pid;
2128 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2129         FILE *fp;
2130 #endif
2131         GSList *mods = NULL;
2132         WapiProcModule *found_module;
2133         guint32 count;
2134         int i;
2135         gboolean ret = FALSE;
2136         char *proc_name = NULL;
2137         
2138         DEBUG ("%s: Getting module info, process handle %p module %p",
2139                    __func__, process, module);
2140
2141         if (modinfo == NULL || size < sizeof (WapiModuleInfo))
2142                 return FALSE;
2143         
2144         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2145                 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2146                 proc_name = get_process_name_from_proc (pid);
2147         } else {
2148                 process_handle = lookup_process_handle (process);
2149                 if (!process_handle) {
2150                         DEBUG ("%s: Can't find process %p", __func__,
2151                                    process);
2152                         
2153                         return FALSE;
2154                 }
2155                 pid = process_handle->id;
2156                 proc_name = g_strdup (process_handle->proc_name);
2157         }
2158
2159 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2160         mods = load_modules ();
2161 #else
2162         /* Look up the address in /proc/<pid>/maps */
2163         if ((fp = open_process_map (pid, "r")) == NULL) {
2164                 /* No /proc/<pid>/maps, so just return failure
2165                  * for now
2166                  */
2167                 g_free (proc_name);
2168                 return FALSE;
2169         }
2170         mods = load_modules (fp);
2171         fclose (fp);
2172 #endif
2173         count = g_slist_length (mods);
2174
2175         /* If module != NULL compare the address.
2176          * If module == NULL we are looking for the main module.
2177          * The best we can do for now check it the module name end with the process name.
2178          */
2179         for (i = 0; i < count; i++) {
2180                         found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2181                         if (ret == FALSE &&
2182                                 ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2183                                  (module != NULL && found_module->address_start == module))) {
2184                                 modinfo->lpBaseOfDll = found_module->address_start;
2185                                 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2186                                 modinfo->EntryPoint = found_module->address_offset;
2187                                 ret = TRUE;
2188                         }
2189
2190                         free_procmodule (found_module);
2191         }
2192
2193         g_slist_free (mods);
2194         g_free (proc_name);
2195
2196         return ret;
2197 }
2198
2199 gboolean
2200 GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2201 {
2202         WapiHandle_process *process_handle;
2203         
2204         if (min == NULL || max == NULL)
2205                 /* Not sure if w32 allows NULLs here or not */
2206                 return FALSE;
2207         
2208         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2209                 /* This is a pseudo handle, so just fail for now */
2210                 return FALSE;
2211         
2212         process_handle = lookup_process_handle (process);
2213         if (!process_handle) {
2214                 DEBUG ("%s: Can't find process %p", __func__, process);
2215                 
2216                 return FALSE;
2217         }
2218
2219         *min = process_handle->min_working_set;
2220         *max = process_handle->max_working_set;
2221         
2222         return TRUE;
2223 }
2224
2225 gboolean
2226 SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2227 {
2228         WapiHandle_process *process_handle;
2229
2230         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process))
2231                 /* This is a pseudo handle, so just fail for now
2232                  */
2233                 return FALSE;
2234
2235         process_handle = lookup_process_handle (process);
2236         if (!process_handle) {
2237                 DEBUG ("%s: Can't find process %p", __func__, process);
2238                 
2239                 return FALSE;
2240         }
2241
2242         process_handle->min_working_set = min;
2243         process_handle->max_working_set = max;
2244         
2245         return TRUE;
2246 }
2247
2248
2249 gboolean
2250 TerminateProcess (gpointer process, gint32 exitCode)
2251 {
2252         WapiHandle_process *process_handle;
2253         int signo;
2254         int ret;
2255         pid_t pid;
2256         
2257         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2258                 /* This is a pseudo handle */
2259                 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2260         } else {
2261                 process_handle = lookup_process_handle (process);
2262                 if (!process_handle) {
2263                         DEBUG ("%s: Can't find process %p", __func__, process);
2264                         SetLastError (ERROR_INVALID_HANDLE);
2265                         return FALSE;
2266                 }
2267                 pid = process_handle->id;
2268         }
2269
2270         signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2271         ret = kill (pid, signo);
2272         if (ret == -1) {
2273                 switch (errno) {
2274                 case EINVAL:
2275                         SetLastError (ERROR_INVALID_PARAMETER);
2276                         break;
2277                 case EPERM:
2278                         SetLastError (ERROR_ACCESS_DENIED);
2279                         break;
2280                 case ESRCH:
2281                         SetLastError (ERROR_PROC_NOT_FOUND);
2282                         break;
2283                 default:
2284                         SetLastError (ERROR_GEN_FAILURE);
2285                 }
2286         }
2287         
2288         return (ret == 0);
2289 }
2290
2291 guint32
2292 GetPriorityClass (gpointer process)
2293 {
2294 #ifdef HAVE_GETPRIORITY
2295         WapiHandle_process *process_handle;
2296         int ret;
2297         pid_t pid;
2298         
2299         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2300                 /* This is a pseudo handle */
2301                 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2302         } else {
2303                 process_handle = lookup_process_handle (process);
2304                 if (!process_handle) {
2305                         SetLastError (ERROR_INVALID_HANDLE);
2306                         return FALSE;
2307                 }
2308                 pid = process_handle->id;
2309         }
2310
2311         errno = 0;
2312         ret = getpriority (PRIO_PROCESS, pid);
2313         if (ret == -1 && errno != 0) {
2314                 switch (errno) {
2315                 case EPERM:
2316                 case EACCES:
2317                         SetLastError (ERROR_ACCESS_DENIED);
2318                         break;
2319                 case ESRCH:
2320                         SetLastError (ERROR_PROC_NOT_FOUND);
2321                         break;
2322                 default:
2323                         SetLastError (ERROR_GEN_FAILURE);
2324                 }
2325                 return FALSE;
2326         }
2327
2328         if (ret == 0)
2329                 return NORMAL_PRIORITY_CLASS;
2330         else if (ret < -15)
2331                 return REALTIME_PRIORITY_CLASS;
2332         else if (ret < -10)
2333                 return HIGH_PRIORITY_CLASS;
2334         else if (ret < 0)
2335                 return ABOVE_NORMAL_PRIORITY_CLASS;
2336         else if (ret > 10)
2337                 return IDLE_PRIORITY_CLASS;
2338         else if (ret > 0)
2339                 return BELOW_NORMAL_PRIORITY_CLASS;
2340
2341         return NORMAL_PRIORITY_CLASS;
2342 #else
2343         SetLastError (ERROR_NOT_SUPPORTED);
2344         return 0;
2345 #endif
2346 }
2347
2348 gboolean
2349 SetPriorityClass (gpointer process, guint32  priority_class)
2350 {
2351 #ifdef HAVE_SETPRIORITY
2352         WapiHandle_process *process_handle;
2353         int ret;
2354         int prio;
2355         pid_t pid;
2356         
2357         if (WAPI_IS_PSEUDO_PROCESS_HANDLE (process)) {
2358                 /* This is a pseudo handle */
2359                 pid = (pid_t)WAPI_HANDLE_TO_PID (process);
2360         } else {
2361                 process_handle = lookup_process_handle (process);
2362                 if (!process_handle) {
2363                         SetLastError (ERROR_INVALID_HANDLE);
2364                         return FALSE;
2365                 }
2366                 pid = process_handle->id;
2367         }
2368
2369         switch (priority_class) {
2370         case IDLE_PRIORITY_CLASS:
2371                 prio = 19;
2372                 break;
2373         case BELOW_NORMAL_PRIORITY_CLASS:
2374                 prio = 10;
2375                 break;
2376         case NORMAL_PRIORITY_CLASS:
2377                 prio = 0;
2378                 break;
2379         case ABOVE_NORMAL_PRIORITY_CLASS:
2380                 prio = -5;
2381                 break;
2382         case HIGH_PRIORITY_CLASS:
2383                 prio = -11;
2384                 break;
2385         case REALTIME_PRIORITY_CLASS:
2386                 prio = -20;
2387                 break;
2388         default:
2389                 SetLastError (ERROR_INVALID_PARAMETER);
2390                 return FALSE;
2391         }
2392
2393         ret = setpriority (PRIO_PROCESS, pid, prio);
2394         if (ret == -1) {
2395                 switch (errno) {
2396                 case EPERM:
2397                 case EACCES:
2398                         SetLastError (ERROR_ACCESS_DENIED);
2399                         break;
2400                 case ESRCH:
2401                         SetLastError (ERROR_PROC_NOT_FOUND);
2402                         break;
2403                 default:
2404                         SetLastError (ERROR_GEN_FAILURE);
2405                 }
2406         }
2407
2408         return ret == 0;
2409 #else
2410         SetLastError (ERROR_NOT_SUPPORTED);
2411         return FALSE;
2412 #endif
2413 }
2414
2415 static void
2416 mono_processes_cleanup (void)
2417 {
2418         struct MonoProcess *mp;
2419         struct MonoProcess *prev = NULL;
2420         struct MonoProcess *candidate = NULL;
2421         gpointer unref_handle;
2422         int spin;
2423
2424         DEBUG ("%s", __func__);
2425
2426         /* Ensure we're not in here in multiple threads at once, nor recursive. */
2427         if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2428                 return;
2429
2430         mp = mono_processes;
2431         while (mp != NULL) {
2432                 if (mp->pid == 0 && mp->handle != NULL) {
2433                         /* This process has exited and we need to remove the artifical ref
2434                          * on the handle */
2435                         mono_mutex_lock (&mono_processes_mutex);
2436                         unref_handle = mp->handle;
2437                         mp->handle = NULL;
2438                         mono_mutex_unlock (&mono_processes_mutex);
2439                         if (unref_handle)
2440                                 _wapi_handle_unref (unref_handle);
2441                         continue;
2442                 }
2443                 mp = mp->next;
2444         }
2445
2446         /*
2447          * Remove processes which exited from the mono_processes list.
2448          * We need to synchronize with the sigchld handler here, which runs
2449          * asynchronously. The handler requires that the mono_processes list
2450          * remain valid.
2451          */
2452         mp = mono_processes;
2453         spin = 0;
2454         while (mp != NULL) {
2455                 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2456                         if (spin > 0) {
2457                                 _wapi_handle_spin (spin);
2458                                 spin <<= 1;
2459                         }
2460
2461                         /* We've found a candidate */
2462                         mono_mutex_lock (&mono_processes_mutex);
2463                         /*
2464                          * This code can run parallel with the sigchld handler, but the
2465                          * modifications it makes are safe.
2466                          */
2467                         if (candidate == NULL) {
2468                                 /* unlink it */
2469                                 if (mp == mono_processes) {
2470                                         mono_processes = mp->next;
2471                                 } else {
2472                                         prev->next = mp->next;
2473                                 }
2474                                 candidate = mp;
2475                         }
2476
2477                         /* It's still safe to traverse the structure.*/
2478                         mono_memory_barrier ();
2479
2480                         if (mono_processes_read_lock != 0) {
2481                                 /* The sigchld handler is watching us. Spin a bit and try again */
2482                                 if (spin == 0) {
2483                                         spin = 1;
2484                                 } else if (spin >= 8) {
2485                                         /* Just give up for now */
2486                                         mono_mutex_unlock (&mono_processes_mutex);
2487                                         break;
2488                                 }
2489                         } else {
2490                                 /* We've modified the list of processes, and we know the sigchld handler
2491                                  * isn't executing, so even if it executes at any moment, it'll see the
2492                                  * new version of the list. So now we can free the candidate. */
2493                                 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2494                                 mp = candidate->next;
2495                                 MONO_SEM_DESTROY (&candidate->exit_sem);
2496                                 g_free (candidate);
2497                                 candidate = NULL;
2498                         }
2499
2500                         mono_mutex_unlock (&mono_processes_mutex);
2501
2502                         continue;
2503                 }
2504                 spin = 0;
2505                 prev = mp;
2506                 mp = mp->next;
2507         }
2508
2509         DEBUG ("%s done", __func__);
2510
2511         InterlockedDecrement (&mono_processes_cleaning_up);
2512 }
2513
2514 static void
2515 process_close (gpointer handle, gpointer data)
2516 {
2517         WapiHandle_process *process_handle;
2518
2519         DEBUG ("%s", __func__);
2520
2521         process_handle = (WapiHandle_process *) data;
2522         g_free (process_handle->proc_name);
2523         process_handle->proc_name = NULL;
2524         if (process_handle->mono_process)
2525                 InterlockedDecrement (&process_handle->mono_process->handle_count);
2526         mono_processes_cleanup ();
2527 }
2528
2529 #if HAVE_SIGACTION
2530 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2531 {
2532         int status;
2533         int pid;
2534         struct MonoProcess *p;
2535
2536         DEBUG ("SIG CHILD handler for pid: %i\n", info->si_pid);
2537
2538         InterlockedIncrement (&mono_processes_read_lock);
2539
2540         do {
2541                 do {
2542                         pid = waitpid (-1, &status, WNOHANG);
2543                 } while (pid == -1 && errno == EINTR);
2544
2545                 if (pid <= 0)
2546                         break;
2547
2548                 DEBUG ("child ended: %i", pid);
2549                 p = mono_processes;
2550                 while (p != NULL) {
2551                         if (p->pid == pid) {
2552                                 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2553                                 p->status = status;
2554                                 MONO_SEM_POST (&p->exit_sem);
2555                                 break;
2556                         }
2557                         p = p->next;
2558                 }
2559         } while (1);
2560
2561         InterlockedDecrement (&mono_processes_read_lock);
2562
2563         DEBUG ("SIG CHILD handler: done looping.");
2564 }
2565
2566 #endif
2567
2568 static void
2569 process_add_sigchld_handler (void)
2570 {
2571 #if HAVE_SIGACTION
2572         struct sigaction sa;
2573
2574         sa.sa_sigaction = mono_sigchld_signal_handler;
2575         sigemptyset (&sa.sa_mask);
2576         sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2577         g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2578         DEBUG ("Added SIGCHLD handler");
2579 #endif
2580 }
2581
2582 static guint32
2583 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2584 {
2585         WapiHandle_process *process_handle;
2586         pid_t pid, ret;
2587         int status;
2588         guint32 start;
2589         guint32 now;
2590         struct MonoProcess *mp;
2591
2592         /* FIXME: We can now easily wait on processes that aren't our own children,
2593          * but WaitFor*Object won't call us for pseudo handles. */
2594         g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2595
2596         DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2597
2598         process_handle = lookup_process_handle (handle);
2599         if (!process_handle) {
2600                 g_warning ("%s: error looking up process handle %p", __func__, handle);
2601                 return WAIT_FAILED;
2602         }
2603
2604         if (process_handle->exited) {
2605                 /* We've already done this one */
2606                 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2607                 return WAIT_OBJECT_0;
2608         }
2609
2610         pid = process_handle->id;
2611
2612         DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2613
2614         /* We don't need to lock mono_processes here, the entry
2615          * has a handle_count > 0 which means it will not be freed. */
2616         mp = process_handle->mono_process;
2617         g_assert (mp);
2618
2619         start = mono_msec_ticks ();
2620         now = start;
2621
2622         while (1) {
2623                 if (timeout != INFINITE) {
2624                         DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...", 
2625                                    __func__, handle, timeout, (timeout - (now - start)));
2626
2627                         ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2628                 } else {
2629                         DEBUG ("%s (%p, %u): waiting on semaphore forever...", 
2630                                    __func__, handle, timeout);
2631                         ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2632                 }
2633
2634                 if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2635                         DEBUG ("%s (%p, %u): sem_timedwait failure: %s", 
2636                                    __func__, handle, timeout, g_strerror (errno));
2637                         /* Should we return a failure here? */
2638                 }
2639
2640                 if (ret == 0) {
2641                         /* Success, process has exited */
2642                         MONO_SEM_POST (&mp->exit_sem);
2643                         break;
2644                 }
2645
2646                 if (timeout == 0) {
2647                         DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
2648                         return WAIT_TIMEOUT;
2649                 }
2650
2651                 now = mono_msec_ticks ();
2652                 if (now - start >= timeout) {
2653                         DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
2654                         return WAIT_TIMEOUT;
2655                 }
2656                 
2657                 if (alertable && _wapi_thread_cur_apc_pending ()) {
2658                         DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
2659                         return WAIT_IO_COMPLETION;
2660                 }
2661         }
2662
2663         /* Process must have exited */
2664         DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
2665
2666         ret = _wapi_handle_lock_shared_handles ();
2667         g_assert (ret == 0);
2668
2669         status = mp ? mp->status : 0;
2670         if (WIFSIGNALED (status))
2671                 process_handle->exitstatus = 128 + WTERMSIG (status);
2672         else
2673                 process_handle->exitstatus = WEXITSTATUS (status);
2674         _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
2675
2676         process_handle->exited = TRUE;
2677
2678         DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
2679                    __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
2680
2681         _wapi_handle_set_signal_state (handle, TRUE, TRUE);
2682
2683         _wapi_handle_unlock_shared_handles ();
2684
2685         return WAIT_OBJECT_0;
2686 }
2687
2688 void
2689 wapi_processes_cleanup (void)
2690 {
2691         g_free (cli_launcher);
2692 }