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