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