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