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