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