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