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