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