Merge pull request #924 from marcusva/master
[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_proc *result;
1354         int name[6];
1355         name[0] = CTL_KERN;
1356         name[1] = KERN_PROC;
1357         name[2] = KERN_PROC_ALL;
1358         name[3] = 0;
1359         name[4] = sizeof(struct kinfo_proc);
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_proc));
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         count = proclength / sizeof(struct kinfo_proc);
1410
1411         fit = len / sizeof(guint32);
1412         for (i = 0, j = 0; j< fit && i < count; i++) {
1413 #if defined(__OpenBSD__)
1414                 pids [j++] = result [i].p_pid;
1415 #else
1416                 if (result[i].kp_proc.p_pid > 0) /* Pid 0 not supported */
1417                         pids [j++] = result [i].kp_proc.p_pid;
1418 #endif
1419         }
1420         free (result);
1421         result = NULL;
1422         *needed = j * sizeof(guint32);
1423         
1424         return(TRUE);
1425 }
1426 #elif defined(__HAIKU__)
1427
1428 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1429 {
1430         guint32 fit, i = 0;
1431         int32 cookie = 0;
1432         team_info teamInfo;
1433
1434         mono_once (&process_current_once, process_set_current);
1435
1436         fit = len / sizeof (guint32);
1437         while (get_next_team_info (&cookie, &teamInfo) == B_OK && i < fit) {
1438                 pids [i++] = teamInfo.team;
1439         }
1440         *needed = i * sizeof (guint32);
1441
1442         return TRUE;
1443 }
1444 #else
1445 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1446 {
1447         guint32 fit, i;
1448         DIR *dir;
1449         struct dirent *entry;
1450         
1451         mono_once (&process_current_once, process_set_current);
1452
1453         dir = opendir ("/proc");
1454         if (dir == NULL) {
1455                 return(FALSE);
1456         }
1457
1458         i = 0;
1459         fit = len / sizeof (guint32);
1460         while(i < fit && (entry = readdir (dir)) != NULL) {
1461                 pid_t pid;
1462                 char *endptr;
1463
1464                 if (!isdigit (entry->d_name[0]))
1465                         continue;
1466
1467                 pid = (pid_t) strtol (entry->d_name, &endptr, 10);
1468                 if (*endptr == '\0')
1469                         pids [i++] = (guint32) pid;
1470         }
1471         closedir (dir);
1472         *needed = i * sizeof(guint32);
1473         
1474         return(TRUE);
1475 }
1476 #endif
1477
1478 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1479 {
1480         pid_t wanted_pid;
1481         pid_t checking_pid = signal_process_if_gone (handle);
1482
1483         if (checking_pid == 0) {
1484                 return(FALSE);
1485         }
1486         
1487         wanted_pid = GPOINTER_TO_UINT (user_data);
1488
1489         /* It's possible to have more than one process handle with the
1490          * same pid, but only the one running process can be
1491          * unsignalled
1492          */
1493         if (checking_pid == wanted_pid &&
1494             _wapi_handle_issignalled (handle) == FALSE) {
1495                 /* If the handle is blown away in the window between
1496                  * returning TRUE here and _wapi_search_handle pinging
1497                  * the timestamp, the search will continue
1498                  */
1499                 return(TRUE);
1500         } else {
1501                 return(FALSE);
1502         }
1503 }
1504
1505 gboolean CloseProcess(gpointer handle)
1506 {
1507         if ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1508                 /* This is a pseudo handle */
1509                 return(TRUE);
1510         }
1511
1512         return CloseHandle (handle);
1513 }
1514
1515 /*
1516  * The caller owns the returned handle and must call CloseProcess () on it to clean it up.
1517  */
1518 gpointer OpenProcess (guint32 req_access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1519 {
1520         /* Find the process handle that corresponds to pid */
1521         gpointer handle = NULL;
1522         
1523         mono_once (&process_current_once, process_set_current);
1524
1525         DEBUG ("%s: looking for process %d", __func__, pid);
1526
1527         handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1528                                       process_open_compare,
1529                                       GUINT_TO_POINTER (pid), NULL, TRUE);
1530         if (handle == 0) {
1531                 if (is_pid_valid (pid)) {
1532                         /* Return a pseudo handle for processes we
1533                          * don't have handles for
1534                          */
1535                         return GINT_TO_POINTER (_WAPI_PROCESS_UNHANDLED + pid);
1536                 } else {
1537                         DEBUG ("%s: Can't find pid %d", __func__, pid);
1538
1539                         SetLastError (ERROR_PROC_NOT_FOUND);
1540         
1541                         return(NULL);
1542                 }
1543         }
1544
1545         /* _wapi_search_handle () already added a ref */
1546         return(handle);
1547 }
1548
1549 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1550 {
1551         struct _WapiHandle_process *process_handle;
1552         gboolean ok;
1553         guint32 pid = -1;
1554         
1555         mono_once (&process_current_once, process_set_current);
1556
1557         if(code==NULL) {
1558                 return(FALSE);
1559         }
1560         
1561         pid = GPOINTER_TO_UINT (process) - _WAPI_PROCESS_UNHANDLED;
1562         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1563                 /* This is a pseudo handle, so we don't know what the
1564                  * exit code was, but we can check whether it's alive or not
1565                  */
1566                 if (is_pid_valid (pid)) {
1567                         *code = STILL_ACTIVE;
1568                         return TRUE;
1569                 } else {
1570                         return FALSE;
1571                 }
1572         }
1573
1574         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1575                                 (gpointer *)&process_handle);
1576         if(ok==FALSE) {
1577                 DEBUG ("%s: Can't find process %p", __func__, process);
1578                 
1579                 return(FALSE);
1580         }
1581         
1582         /* A process handle is only signalled if the process has exited
1583          * and has been waited for */
1584
1585         /* Make sure any process exit has been noticed, before
1586          * checking if the process is signalled.  Fixes bug 325463.
1587          */
1588         process_wait (process, 0, TRUE);
1589         
1590         if (_wapi_handle_issignalled (process) == TRUE) {
1591                 *code = process_handle->exitstatus;
1592         } else {
1593                 *code = STILL_ACTIVE;
1594         }
1595         
1596         return(TRUE);
1597 }
1598
1599 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1600                           WapiFileTime *exit_time, WapiFileTime *kernel_time,
1601                           WapiFileTime *user_time)
1602 {
1603         struct _WapiHandle_process *process_handle;
1604         gboolean ok;
1605         gboolean ku_times_set = FALSE;
1606         
1607         mono_once (&process_current_once, process_set_current);
1608
1609         if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1610            user_time==NULL) {
1611                 /* Not sure if w32 allows NULLs here or not */
1612                 return(FALSE);
1613         }
1614         
1615         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
1616                 /* This is a pseudo handle, so just fail for now
1617                  */
1618                 return(FALSE);
1619         }
1620         
1621         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1622                                 (gpointer *)&process_handle);
1623         if(ok==FALSE) {
1624                 DEBUG ("%s: Can't find process %p", __func__, process);
1625                 
1626                 return(FALSE);
1627         }
1628         
1629         *create_time=process_handle->create_time;
1630
1631         /* A process handle is only signalled if the process has
1632          * exited.  Otherwise exit_time isn't set
1633          */
1634         if(_wapi_handle_issignalled (process)==TRUE) {
1635                 *exit_time=process_handle->exit_time;
1636         }
1637
1638 #ifdef HAVE_GETRUSAGE
1639         if (process_handle->id == getpid ()) {
1640                 struct rusage time_data;
1641                 if (getrusage (RUSAGE_SELF, &time_data) == 0) {
1642                         guint64 tick_val;
1643                         ku_times_set = TRUE;
1644                         tick_val = (guint64)time_data.ru_utime.tv_sec * 10000000 + (guint64)time_data.ru_utime.tv_usec * 10;
1645                         _wapi_guint64_to_filetime (tick_val, user_time);
1646                         tick_val = (guint64)time_data.ru_stime.tv_sec * 10000000 + (guint64)time_data.ru_stime.tv_usec * 10;
1647                         _wapi_guint64_to_filetime (tick_val, kernel_time);
1648                 }
1649         }
1650 #endif
1651         if (!ku_times_set) {
1652                 memset (kernel_time, 0, sizeof (WapiFileTime));
1653                 memset (user_time, 0, sizeof (WapiFileTime));
1654         }
1655
1656         return(TRUE);
1657 }
1658
1659 typedef struct
1660 {
1661         gpointer address_start;
1662         gpointer address_end;
1663         gchar *perms;
1664         gpointer address_offset;
1665         dev_t device;
1666         ino_t inode;
1667         gchar *filename;
1668 } WapiProcModule;
1669
1670 static void free_procmodule (WapiProcModule *mod)
1671 {
1672         if (mod->perms != NULL) {
1673                 g_free (mod->perms);
1674         }
1675         if (mod->filename != NULL) {
1676                 g_free (mod->filename);
1677         }
1678         g_free (mod);
1679 }
1680
1681 static gint find_procmodule (gconstpointer a, gconstpointer b)
1682 {
1683         WapiProcModule *want = (WapiProcModule *)a;
1684         WapiProcModule *compare = (WapiProcModule *)b;
1685         
1686         if ((want->device == compare->device) &&
1687             (want->inode == compare->inode)) {
1688                 return(0);
1689         } else {
1690                 return(1);
1691         }
1692 }
1693
1694 #ifdef PLATFORM_MACOSX
1695 #include <mach-o/dyld.h>
1696 #include <mach-o/getsect.h>
1697
1698 static GSList *load_modules (void)
1699 {
1700         GSList *ret = NULL;
1701         WapiProcModule *mod;
1702         uint32_t count = _dyld_image_count ();
1703         int i = 0;
1704
1705         for (i = 0; i < count; i++) {
1706 #if SIZEOF_VOID_P == 8
1707                 const struct mach_header_64 *hdr;
1708                 const struct section_64 *sec;
1709 #else
1710                 const struct mach_header *hdr;
1711                 const struct section *sec;
1712 #endif
1713                 const char *name;
1714
1715                 name = _dyld_get_image_name (i);
1716 #if SIZEOF_VOID_P == 8
1717                 hdr = (const struct mach_header_64*)_dyld_get_image_header (i);
1718                 sec = getsectbynamefromheader_64 (hdr, SEG_DATA, SECT_DATA);
1719 #else
1720                 hdr = _dyld_get_image_header (i);
1721                 sec = getsectbynamefromheader (hdr, SEG_DATA, SECT_DATA);
1722 #endif
1723
1724                 /* Some dynlibs do not have data sections on osx (#533893) */
1725                 if (sec == 0) {
1726                         continue;
1727                 }
1728                         
1729                 mod = g_new0 (WapiProcModule, 1);
1730                 mod->address_start = GINT_TO_POINTER (sec->addr);
1731                 mod->address_end = GINT_TO_POINTER (sec->addr+sec->size);
1732                 mod->perms = g_strdup ("r--p");
1733                 mod->address_offset = 0;
1734                 mod->device = makedev (0, 0);
1735                 mod->inode = (ino_t) i;
1736                 mod->filename = g_strdup (name); 
1737                 
1738                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1739                         ret = g_slist_prepend (ret, mod);
1740                 } else {
1741                         free_procmodule (mod);
1742                 }
1743         }
1744
1745         ret = g_slist_reverse (ret);
1746         
1747         return(ret);
1748 }
1749 #elif defined(__OpenBSD__)
1750 #include <link.h>
1751 static int load_modules_callback (struct dl_phdr_info *info, size_t size, void *ptr)
1752 {
1753         if (size < offsetof (struct dl_phdr_info, dlpi_phnum)
1754             + sizeof (info->dlpi_phnum))
1755                 return (-1);
1756
1757         struct dl_phdr_info *cpy = calloc(1, sizeof(struct dl_phdr_info));
1758         if (!cpy)
1759                 return (-1);
1760
1761         memcpy(cpy, info, sizeof(*info));
1762
1763         g_ptr_array_add ((GPtrArray *)ptr, cpy);
1764
1765         return (0);
1766 }
1767
1768 static GSList *load_modules (void)
1769 {
1770         GSList *ret = NULL;
1771         WapiProcModule *mod;
1772         GPtrArray *dlarray = g_ptr_array_new();
1773         int i;
1774
1775         if (dl_iterate_phdr(load_modules_callback, dlarray) < 0)
1776                 return (ret);
1777
1778         for (i = 0; i < dlarray->len; i++) {
1779                 struct dl_phdr_info *info = g_ptr_array_index (dlarray, i);
1780
1781                 mod = g_new0 (WapiProcModule, 1);
1782                 mod->address_start = (gpointer)(info->dlpi_addr + info->dlpi_phdr[0].p_vaddr);
1783                 mod->address_end = (gpointer)(info->dlpi_addr +
1784                                        info->dlpi_phdr[info->dlpi_phnum - 1].p_vaddr);
1785                 mod->perms = g_strdup ("r--p");
1786                 mod->address_offset = 0;
1787                 mod->inode = (ino_t) i;
1788                 mod->filename = g_strdup (info->dlpi_name); 
1789
1790                 DEBUG ("%s: inode=%d, filename=%s, address_start=%p, address_end=%p", __func__,
1791                                    mod->inode, mod->filename, mod->address_start, mod->address_end);
1792
1793                 free(info);
1794
1795                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1796                         ret = g_slist_prepend (ret, mod);
1797                 } else {
1798                         free_procmodule (mod);
1799                 }
1800         }
1801
1802         g_ptr_array_free (dlarray, TRUE);
1803
1804         ret = g_slist_reverse (ret);
1805
1806         return(ret);
1807 }
1808 #elif defined(__HAIKU__)
1809
1810 static GSList *load_modules (void)
1811 {
1812         GSList *ret = NULL;
1813         WapiProcModule *mod;
1814         int32 cookie = 0;
1815         image_info imageInfo;
1816
1817         while (get_next_image_info (B_CURRENT_TEAM, &cookie, &imageInfo) == B_OK) {
1818                 mod = g_new0 (WapiProcModule, 1);
1819                 mod->device = imageInfo.device;
1820                 mod->inode = imageInfo.node;
1821                 mod->filename = g_strdup (imageInfo.name);
1822                 mod->address_start = MIN (imageInfo.text, imageInfo.data);
1823                 mod->address_end = MAX ((uint8_t*)imageInfo.text + imageInfo.text_size,
1824                         (uint8_t*)imageInfo.data + imageInfo.data_size);
1825                 mod->perms = g_strdup ("r--p");
1826                 mod->address_offset = 0;
1827
1828                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1829                         ret = g_slist_prepend (ret, mod);
1830                 } else {
1831                         free_procmodule (mod);
1832                 }
1833         }
1834
1835         ret = g_slist_reverse (ret);
1836
1837         return ret;
1838 }
1839 #else
1840 static GSList *load_modules (FILE *fp)
1841 {
1842         GSList *ret = NULL;
1843         WapiProcModule *mod;
1844         gchar buf[MAXPATHLEN + 1], *p, *endp;
1845         gchar *start_start, *end_start, *prot_start, *offset_start;
1846         gchar *maj_dev_start, *min_dev_start, *inode_start, prot_buf[5];
1847         gpointer address_start, address_end, address_offset;
1848         guint32 maj_dev, min_dev;
1849         ino_t inode;
1850         dev_t device;
1851         
1852         while (fgets (buf, sizeof(buf), fp)) {
1853                 p = buf;
1854                 while (g_ascii_isspace (*p)) ++p;
1855                 start_start = p;
1856                 if (!g_ascii_isxdigit (*start_start)) {
1857                         continue;
1858                 }
1859                 address_start = (gpointer)strtoul (start_start, &endp, 16);
1860                 p = endp;
1861                 if (*p != '-') {
1862                         continue;
1863                 }
1864                 
1865                 ++p;
1866                 end_start = p;
1867                 if (!g_ascii_isxdigit (*end_start)) {
1868                         continue;
1869                 }
1870                 address_end = (gpointer)strtoul (end_start, &endp, 16);
1871                 p = endp;
1872                 if (!g_ascii_isspace (*p)) {
1873                         continue;
1874                 }
1875                 
1876                 while (g_ascii_isspace (*p)) ++p;
1877                 prot_start = p;
1878                 if (*prot_start != 'r' && *prot_start != '-') {
1879                         continue;
1880                 }
1881                 memcpy (prot_buf, prot_start, 4);
1882                 prot_buf[4] = '\0';
1883                 while (!g_ascii_isspace (*p)) ++p;
1884                 
1885                 while (g_ascii_isspace (*p)) ++p;
1886                 offset_start = p;
1887                 if (!g_ascii_isxdigit (*offset_start)) {
1888                         continue;
1889                 }
1890                 address_offset = (gpointer)strtoul (offset_start, &endp, 16);
1891                 p = endp;
1892                 if (!g_ascii_isspace (*p)) {
1893                         continue;
1894                 }
1895                 
1896                 while(g_ascii_isspace (*p)) ++p;
1897                 maj_dev_start = p;
1898                 if (!g_ascii_isxdigit (*maj_dev_start)) {
1899                         continue;
1900                 }
1901                 maj_dev = strtoul (maj_dev_start, &endp, 16);
1902                 p = endp;
1903                 if (*p != ':') {
1904                         continue;
1905                 }
1906                 
1907                 ++p;
1908                 min_dev_start = p;
1909                 if (!g_ascii_isxdigit (*min_dev_start)) {
1910                         continue;
1911                 }
1912                 min_dev = strtoul (min_dev_start, &endp, 16);
1913                 p = endp;
1914                 if (!g_ascii_isspace (*p)) {
1915                         continue;
1916                 }
1917                 
1918                 while (g_ascii_isspace (*p)) ++p;
1919                 inode_start = p;
1920                 if (!g_ascii_isxdigit (*inode_start)) {
1921                         continue;
1922                 }
1923                 inode = (ino_t)strtol (inode_start, &endp, 10);
1924                 p = endp;
1925                 if (!g_ascii_isspace (*p)) {
1926                         continue;
1927                 }
1928
1929                 device = makedev ((int)maj_dev, (int)min_dev);
1930                 if ((device == 0) &&
1931                     (inode == 0)) {
1932                         continue;
1933                 }
1934                 
1935                 while(g_ascii_isspace (*p)) ++p;
1936                 /* p now points to the filename */
1937
1938                 mod = g_new0 (WapiProcModule, 1);
1939                 mod->address_start = address_start;
1940                 mod->address_end = address_end;
1941                 mod->perms = g_strdup (prot_buf);
1942                 mod->address_offset = address_offset;
1943                 mod->device = device;
1944                 mod->inode = inode;
1945                 mod->filename = g_strdup (g_strstrip (p));
1946                 
1947                 if (g_slist_find_custom (ret, mod, find_procmodule) == NULL) {
1948                         ret = g_slist_prepend (ret, mod);
1949                 } else {
1950                         free_procmodule (mod);
1951                 }
1952         }
1953
1954         ret = g_slist_reverse (ret);
1955         
1956         return(ret);
1957 }
1958 #endif
1959
1960 static gboolean match_procname_to_modulename (gchar *procname, gchar *modulename)
1961 {
1962         char* lastsep = NULL;
1963         char* lastsep2 = NULL;
1964         char* pname = NULL;
1965         char* mname = NULL;
1966         gboolean result = FALSE;
1967
1968         if (procname == NULL || modulename == NULL)
1969                 return (FALSE);
1970
1971         pname = mono_path_resolve_symlinks (procname);
1972         mname = mono_path_resolve_symlinks (modulename);
1973
1974         if (!strcmp (pname, mname))
1975                 result = TRUE;
1976
1977         if (!result) {
1978                 lastsep = strrchr (mname, '/');
1979                 if (lastsep)
1980                         if (!strcmp (lastsep+1, pname))
1981                                 result = TRUE;
1982                 if (!result) {
1983                         lastsep2 = strrchr (pname, '/');
1984                         if (lastsep2){
1985                                 if (lastsep) {
1986                                         if (!strcmp (lastsep+1, lastsep2+1))
1987                                                 result = TRUE;
1988                                 } else {
1989                                         if (!strcmp (mname, lastsep2+1))
1990                                                 result = TRUE;
1991                                 }
1992                         }
1993                 }
1994         }
1995
1996         g_free (pname);
1997         g_free (mname);
1998
1999         return result;
2000 }
2001
2002 #if !defined(__OpenBSD__)
2003 static FILE *
2004 open_process_map (int pid, const char *mode)
2005 {
2006         FILE *fp = NULL;
2007         const gchar *proc_path[] = {
2008                 "/proc/%d/maps",        /* GNU/Linux */
2009                 "/proc/%d/map",         /* FreeBSD */
2010                 NULL
2011         };
2012         int i;
2013         gchar *filename;
2014
2015         for (i = 0; fp == NULL && proc_path [i]; i++) {
2016                 filename = g_strdup_printf (proc_path[i], pid);
2017                 fp = fopen (filename, mode);
2018                 g_free (filename);
2019         }
2020
2021         return fp;
2022 }
2023 #endif
2024
2025 gboolean EnumProcessModules (gpointer process, gpointer *modules,
2026                              guint32 size, guint32 *needed)
2027 {
2028         struct _WapiHandle_process *process_handle;
2029         gboolean ok;
2030 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2031         FILE *fp;
2032 #endif
2033         GSList *mods = NULL;
2034         WapiProcModule *module;
2035         guint32 count, avail = size / sizeof(gpointer);
2036         int i;
2037         pid_t pid;
2038         gchar *proc_name = NULL;
2039         
2040         /* Store modules in an array of pointers (main module as
2041          * modules[0]), using the load address for each module as a
2042          * token.  (Use 'NULL' as an alternative for the main module
2043          * so that the simple implementation can just return one item
2044          * for now.)  Get the info from /proc/<pid>/maps on linux,
2045          * /proc/<pid>/map on FreeBSD, other systems will have to
2046          * implement /dev/kmem reading or whatever other horrid
2047          * technique is needed.
2048          */
2049         if (size < sizeof(gpointer)) {
2050                 return(FALSE);
2051         }
2052
2053         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2054                 /* This is a pseudo handle */
2055                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2056         } else {
2057                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2058                                           (gpointer *)&process_handle);
2059                 if (ok == FALSE) {
2060                         DEBUG ("%s: Can't find process %p", __func__, process);
2061                 
2062                         return(FALSE);
2063                 }
2064                 pid = process_handle->id;
2065                 proc_name = process_handle->proc_name;
2066         }
2067         
2068 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2069         {
2070                 mods = load_modules ();
2071 #else
2072         if ((fp = open_process_map (pid, "r")) == NULL) {
2073                 /* No /proc/<pid>/maps so just return the main module
2074                  * shortcut for now
2075                  */
2076                 modules[0] = NULL;
2077                 *needed = sizeof(gpointer);
2078         } else {
2079                 mods = load_modules (fp);
2080                 fclose (fp);
2081 #endif
2082                 count = g_slist_length (mods);
2083                 
2084                 /* count + 1 to leave slot 0 for the main module */
2085                 *needed = sizeof(gpointer) * (count + 1);
2086
2087                 /* Use the NULL shortcut, as the first line in
2088                  * /proc/<pid>/maps isn't the executable, and we need
2089                  * that first in the returned list. Check the module name 
2090                  * to see if it ends with the proc name and substitute 
2091                  * the first entry with it.  FIXME if this turns out to 
2092                  * be a problem.
2093                  */
2094                 modules[0] = NULL;
2095                 for (i = 0; i < (avail - 1) && i < count; i++) {
2096                         module = (WapiProcModule *)g_slist_nth_data (mods, i);
2097                         if (modules[0] != NULL)
2098                                 modules[i] = module->address_start;
2099                         else if (match_procname_to_modulename (proc_name, module->filename))
2100                                 modules[0] = module->address_start;
2101                         else
2102                                 modules[i + 1] = module->address_start;
2103                 }
2104                 
2105                 for (i = 0; i < count; i++) {
2106                         free_procmodule (g_slist_nth_data (mods, i));
2107                 }
2108                 g_slist_free (mods);
2109         }
2110
2111         return(TRUE);
2112 }
2113
2114 static gchar *get_process_name_from_proc (pid_t pid)
2115 {
2116 #if defined(__OpenBSD__)
2117         int mib [6];
2118         size_t size;
2119         struct kinfo_proc *pi;
2120 #elif defined(PLATFORM_MACOSX)
2121 #if !(!defined (__mono_ppc__) && defined (TARGET_OSX))
2122         size_t size;
2123         struct kinfo_proc *pi;
2124         int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
2125 #endif
2126 #else
2127         FILE *fp;
2128         gchar *filename = NULL;
2129 #endif
2130         gchar buf[256];
2131         gchar *ret = NULL;
2132
2133 #if defined(PLATFORM_SOLARIS)
2134         filename = g_strdup_printf ("/proc/%d/psinfo", pid);
2135         if ((fp = fopen (filename, "r")) != NULL) {
2136                 struct psinfo info;
2137                 int nread;
2138
2139                 nread = fread (&info, sizeof (info), 1, fp);
2140                 if (nread == 1) {
2141                         ret = g_strdup (info.pr_fname);
2142                 }
2143
2144                 fclose (fp);
2145         }
2146         g_free (filename);
2147 #elif defined(PLATFORM_MACOSX)
2148 #if !defined (__mono_ppc__) && defined (TARGET_OSX)
2149         /* No proc name on OSX < 10.5 nor ppc nor iOS */
2150         memset (buf, '\0', sizeof(buf));
2151         proc_name (pid, buf, sizeof(buf));
2152         if (strlen (buf) > 0)
2153                 ret = g_strdup (buf);
2154 #else
2155         if (sysctl(mib, 4, NULL, &size, NULL, 0) < 0)
2156                 return(ret);
2157
2158         if ((pi = malloc(size)) == NULL)
2159                 return(ret);
2160
2161         if (sysctl (mib, 4, pi, &size, NULL, 0) < 0) {
2162                 if (errno == ENOMEM) {
2163                         free(pi);
2164                         DEBUG ("%s: Didn't allocate enough memory for kproc info", __func__);
2165                 }
2166                 return(ret);
2167         }
2168
2169         if (strlen (pi->kp_proc.p_comm) > 0)
2170                 ret = g_strdup (pi->kp_proc.p_comm);
2171
2172         free(pi);
2173 #endif
2174 #elif defined(__OpenBSD__)
2175         mib [0] = CTL_KERN;
2176         mib [1] = KERN_PROC;
2177         mib [2] = KERN_PROC_PID;
2178         mib [3] = pid;
2179         mib [4] = sizeof(struct kinfo_proc);
2180         mib [5] = 0;
2181
2182 retry:
2183         if (sysctl(mib, 6, NULL, &size, NULL, 0) < 0)
2184                 return(ret);
2185
2186         if ((pi = malloc(size)) == NULL)
2187                 return(ret);
2188
2189         mib[5] = (int)(size / sizeof(struct kinfo_proc));
2190
2191         if ((sysctl (mib, 6, pi, &size, NULL, 0) < 0) ||
2192                 (size != sizeof (struct kinfo_proc))) {
2193                 if (errno == ENOMEM) {
2194                         free(pi);
2195                         goto retry;
2196                 }
2197                 return(ret);
2198         }
2199
2200         if (strlen (pi->p_comm) > 0)
2201                 ret = g_strdup (pi->p_comm);
2202
2203         free(pi);
2204 #elif defined(__HAIKU__)
2205         image_info imageInfo;
2206         int32 cookie = 0;
2207
2208         if (get_next_image_info ((team_id)pid, &cookie, &imageInfo) == B_OK) {
2209                 ret = g_strdup (imageInfo.name);
2210         }
2211 #else
2212         memset (buf, '\0', sizeof(buf));
2213         filename = g_strdup_printf ("/proc/%d/exe", pid);
2214         if (readlink (filename, buf, 255) > 0) {
2215                 ret = g_strdup (buf);
2216         }
2217         g_free (filename);
2218
2219         if (ret != NULL) {
2220                 return(ret);
2221         }
2222
2223         filename = g_strdup_printf ("/proc/%d/cmdline", pid);
2224         if ((fp = fopen (filename, "r")) != NULL) {
2225                 if (fgets (buf, 256, fp) != NULL) {
2226                         ret = g_strdup (buf);
2227                 }
2228                 
2229                 fclose (fp);
2230         }
2231         g_free (filename);
2232
2233         if (ret != NULL) {
2234                 return(ret);
2235         }
2236         
2237         filename = g_strdup_printf ("/proc/%d/stat", pid);
2238         if ((fp = fopen (filename, "r")) != NULL) {
2239                 if (fgets (buf, 256, fp) != NULL) {
2240                         gchar *start, *end;
2241                         
2242                         start = strchr (buf, '(');
2243                         if (start != NULL) {
2244                                 end = strchr (start + 1, ')');
2245                                 
2246                                 if (end != NULL) {
2247                                         ret = g_strndup (start + 1,
2248                                                          end - start - 1);
2249                                 }
2250                         }
2251                 }
2252                 
2253                 fclose (fp);
2254         }
2255         g_free (filename);
2256 #endif
2257
2258         return ret;
2259 }
2260
2261 /*
2262  * wapi_process_get_path:
2263  *
2264  *   Return the full path of the executable of the process PID, or NULL if it cannot be determined.
2265  * Returns malloc-ed memory.
2266  */
2267 gchar*
2268 wapi_process_get_path (pid_t pid)
2269 {
2270 #if defined(PLATFORM_MACOSX) && !defined(__mono_ppc__) && defined(TARGET_OSX)
2271         gchar buf [PROC_PIDPATHINFO_MAXSIZE];
2272         int res;
2273
2274         res = proc_pidpath (pid, buf, sizeof (buf));
2275         if (res <= 0)
2276                 return NULL;
2277         if (buf [0] == '\0')
2278                 return NULL;
2279         return g_strdup (buf);
2280 #else
2281         return get_process_name_from_proc (pid);
2282 #endif
2283 }
2284
2285 /*
2286  * wapi_process_set_cli_launcher:
2287  *
2288  *   Set the full path of the runtime executable used to launch managed exe's.
2289  */
2290 void
2291 wapi_process_set_cli_launcher (char *path)
2292 {
2293         g_free (cli_launcher);
2294         cli_launcher = path ? g_strdup (path) : NULL;
2295 }
2296
2297 static guint32 get_module_name (gpointer process, gpointer module,
2298                                 gunichar2 *basename, guint32 size,
2299                                 gboolean base)
2300 {
2301         struct _WapiHandle_process *process_handle;
2302         gboolean ok;
2303         pid_t pid;
2304         gunichar2 *procname;
2305         gchar *procname_ext = NULL;
2306         glong len;
2307         gsize bytes;
2308 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2309         FILE *fp;
2310 #endif
2311         GSList *mods = NULL;
2312         WapiProcModule *found_module;
2313         guint32 count;
2314         int i;
2315         gchar *proc_name = NULL;
2316         
2317         mono_once (&process_current_once, process_set_current);
2318
2319         DEBUG ("%s: Getting module base name, process handle %p module %p",
2320                    __func__, process, module);
2321
2322         size = size*sizeof(gunichar2); /* adjust for unicode characters */
2323
2324         if (basename == NULL || size == 0) {
2325                 return(0);
2326         }
2327         
2328         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2329                 /* This is a pseudo handle */
2330                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2331                 proc_name = get_process_name_from_proc (pid);
2332         } else {
2333                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2334                                           (gpointer *)&process_handle);
2335                 if (ok == FALSE) {
2336                         DEBUG ("%s: Can't find process %p", __func__,
2337                                    process);
2338                         
2339                         return(0);
2340                 }
2341                 pid = process_handle->id;
2342                 proc_name = g_strdup (process_handle->proc_name);
2343         }
2344
2345         /* Look up the address in /proc/<pid>/maps */
2346 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2347         {
2348                 mods = load_modules ();
2349 #else
2350         if ((fp = open_process_map (pid, "r")) == NULL) {
2351                 if (errno == EACCES && module == NULL && base == TRUE) {
2352                         procname_ext = get_process_name_from_proc (pid);
2353                 } else {
2354                         /* No /proc/<pid>/maps, so just return failure
2355                          * for now
2356                          */
2357                         g_free (proc_name);
2358                         return(0);
2359                 }
2360         } else {
2361                 mods = load_modules (fp);
2362                 fclose (fp);
2363 #endif
2364                 count = g_slist_length (mods);
2365
2366                 /* If module != NULL compare the address.
2367                  * If module == NULL we are looking for the main module.
2368                  * The best we can do for now check it the module name end with the process name.
2369                  */
2370                 for (i = 0; i < count; i++) {
2371                         found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2372                         if (procname_ext == NULL &&
2373                             ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||    
2374                              (module != NULL && found_module->address_start == module))) {
2375                                 if (base) {
2376                                         procname_ext = g_path_get_basename (found_module->filename);
2377                                 } else {
2378                                         procname_ext = g_strdup (found_module->filename);
2379                                 }
2380                         }
2381
2382                         free_procmodule (found_module);
2383                 }
2384
2385                 if (procname_ext == NULL)
2386                 {
2387                         /* If it's *still* null, we might have hit the
2388                          * case where reading /proc/$pid/maps gives an
2389                          * empty file for this user.
2390                          */
2391                         procname_ext = get_process_name_from_proc (pid);
2392                 }
2393
2394                 g_slist_free (mods);
2395                 g_free (proc_name);
2396         }
2397
2398         if (procname_ext != NULL) {
2399                 DEBUG ("%s: Process name is [%s]", __func__,
2400                            procname_ext);
2401
2402                 procname = mono_unicode_from_external (procname_ext, &bytes);
2403                 if (procname == NULL) {
2404                         /* bugger */
2405                         g_free (procname_ext);
2406                         return(0);
2407                 }
2408                 
2409                 len = (bytes / 2);
2410                 
2411                 /* Add the terminator */
2412                 bytes += 2;
2413                 
2414                 if (size < bytes) {
2415                         DEBUG ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
2416
2417                         memcpy (basename, procname, size);
2418                 } else {
2419                         DEBUG ("%s: Size %d larger than needed (%ld)",
2420                                    __func__, size, bytes);
2421
2422                         memcpy (basename, procname, bytes);
2423                 }
2424                 
2425                 g_free (procname);
2426                 g_free (procname_ext);
2427                 
2428                 return(len);
2429         }
2430         
2431         return(0);
2432 }
2433
2434 guint32 GetModuleBaseName (gpointer process, gpointer module,
2435                            gunichar2 *basename, guint32 size)
2436 {
2437         return(get_module_name (process, module, basename, size, TRUE));
2438 }
2439
2440 guint32 GetModuleFileNameEx (gpointer process, gpointer module,
2441                              gunichar2 *filename, guint32 size)
2442 {
2443         return(get_module_name (process, module, filename, size, FALSE));
2444 }
2445
2446 gboolean GetModuleInformation (gpointer process, gpointer module,
2447                                WapiModuleInfo *modinfo, guint32 size)
2448 {
2449         struct _WapiHandle_process *process_handle;
2450         gboolean ok;
2451         pid_t pid;
2452 #if !defined(__OpenBSD__) && !defined(PLATFORM_MACOSX)
2453         FILE *fp;
2454 #endif
2455         GSList *mods = NULL;
2456         WapiProcModule *found_module;
2457         guint32 count;
2458         int i;
2459         gboolean ret = FALSE;
2460         gchar *proc_name = NULL;
2461         
2462         mono_once (&process_current_once, process_set_current);
2463         
2464         DEBUG ("%s: Getting module info, process handle %p module %p",
2465                    __func__, process, module);
2466
2467         if (modinfo == NULL || size < sizeof(WapiModuleInfo)) {
2468                 return(FALSE);
2469         }
2470         
2471         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2472                 /* This is a pseudo handle */
2473                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2474                 proc_name = get_process_name_from_proc (pid);
2475         } else {
2476                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2477                                           (gpointer *)&process_handle);
2478                 if (ok == FALSE) {
2479                         DEBUG ("%s: Can't find process %p", __func__,
2480                                    process);
2481                         
2482                         return(FALSE);
2483                 }
2484                 pid = process_handle->id;
2485                 proc_name = g_strdup (process_handle->proc_name);
2486         }
2487
2488 #if defined(PLATFORM_MACOSX) || defined(__OpenBSD__) || defined(__HAIKU__)
2489         {
2490                 mods = load_modules ();
2491 #else
2492         /* Look up the address in /proc/<pid>/maps */
2493         if ((fp = open_process_map (pid, "r")) == NULL) {
2494                 /* No /proc/<pid>/maps, so just return failure
2495                  * for now
2496                  */
2497                 g_free (proc_name);
2498                 return(FALSE);
2499         } else {
2500                 mods = load_modules (fp);
2501                 fclose (fp);
2502 #endif
2503                 count = g_slist_length (mods);
2504
2505                 /* If module != NULL compare the address.
2506                  * If module == NULL we are looking for the main module.
2507                  * The best we can do for now check it the module name end with the process name.
2508                  */
2509                 for (i = 0; i < count; i++) {
2510                         found_module = (WapiProcModule *)g_slist_nth_data (mods, i);
2511                         if ( ret == FALSE &&
2512                              ((module == NULL && match_procname_to_modulename (proc_name, found_module->filename)) ||
2513                               (module != NULL && found_module->address_start == module))) {
2514                                 modinfo->lpBaseOfDll = found_module->address_start;
2515                                 modinfo->SizeOfImage = (gsize)(found_module->address_end) - (gsize)(found_module->address_start);
2516                                 modinfo->EntryPoint = found_module->address_offset;
2517                                 ret = TRUE;
2518                         }
2519
2520                         free_procmodule (found_module);
2521                 }
2522
2523                 g_slist_free (mods);
2524                 g_free (proc_name);
2525         }
2526
2527         return(ret);
2528 }
2529
2530 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
2531 {
2532         struct _WapiHandle_process *process_handle;
2533         gboolean ok;
2534         
2535         mono_once (&process_current_once, process_set_current);
2536
2537         if(min==NULL || max==NULL) {
2538                 /* Not sure if w32 allows NULLs here or not */
2539                 return(FALSE);
2540         }
2541         
2542         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2543                 /* This is a pseudo handle, so just fail for now
2544                  */
2545                 return(FALSE);
2546         }
2547         
2548         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2549                                 (gpointer *)&process_handle);
2550         if(ok==FALSE) {
2551                 DEBUG ("%s: Can't find process %p", __func__, process);
2552                 
2553                 return(FALSE);
2554         }
2555
2556         *min=process_handle->min_working_set;
2557         *max=process_handle->max_working_set;
2558         
2559         return(TRUE);
2560 }
2561
2562 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
2563 {
2564         struct _WapiHandle_process *process_handle;
2565         gboolean ok;
2566
2567         mono_once (&process_current_once, process_set_current);
2568         
2569         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2570                 /* This is a pseudo handle, so just fail for now
2571                  */
2572                 return(FALSE);
2573         }
2574
2575         ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2576                                 (gpointer *)&process_handle);
2577         if(ok==FALSE) {
2578                 DEBUG ("%s: Can't find process %p", __func__, process);
2579                 
2580                 return(FALSE);
2581         }
2582
2583         process_handle->min_working_set=min;
2584         process_handle->max_working_set=max;
2585         
2586         return(TRUE);
2587 }
2588
2589
2590 gboolean
2591 TerminateProcess (gpointer process, gint32 exitCode)
2592 {
2593         struct _WapiHandle_process *process_handle;
2594         gboolean ok;
2595         int signo;
2596         int ret;
2597         pid_t pid;
2598         
2599         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2600                 /* This is a pseudo handle */
2601                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2602         } else {
2603                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2604                                           (gpointer *) &process_handle);
2605
2606                 if (ok == FALSE) {
2607                         DEBUG ("%s: Can't find process %p", __func__,
2608                                    process);
2609                         SetLastError (ERROR_INVALID_HANDLE);
2610                         return FALSE;
2611                 }
2612                 pid = process_handle->id;
2613         }
2614
2615         signo = (exitCode == -1) ? SIGKILL : SIGTERM;
2616         ret = kill (pid, signo);
2617         if (ret == -1) {
2618                 switch (errno) {
2619                 case EINVAL:
2620                         SetLastError (ERROR_INVALID_PARAMETER);
2621                         break;
2622                 case EPERM:
2623                         SetLastError (ERROR_ACCESS_DENIED);
2624                         break;
2625                 case ESRCH:
2626                         SetLastError (ERROR_PROC_NOT_FOUND);
2627                         break;
2628                 default:
2629                         SetLastError (ERROR_GEN_FAILURE);
2630                 }
2631         }
2632         
2633         return (ret == 0);
2634 }
2635
2636 guint32
2637 GetPriorityClass (gpointer process)
2638 {
2639 #ifdef HAVE_GETPRIORITY
2640         struct _WapiHandle_process *process_handle;
2641         gboolean ok;
2642         int ret;
2643         pid_t pid;
2644         
2645         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2646                 /* This is a pseudo handle */
2647                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2648         } else {
2649                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2650                                           (gpointer *) &process_handle);
2651
2652                 if (!ok) {
2653                         SetLastError (ERROR_INVALID_HANDLE);
2654                         return FALSE;
2655                 }
2656                 pid = process_handle->id;
2657         }
2658
2659         errno = 0;
2660         ret = getpriority (PRIO_PROCESS, pid);
2661         if (ret == -1 && errno != 0) {
2662                 switch (errno) {
2663                 case EPERM:
2664                 case EACCES:
2665                         SetLastError (ERROR_ACCESS_DENIED);
2666                         break;
2667                 case ESRCH:
2668                         SetLastError (ERROR_PROC_NOT_FOUND);
2669                         break;
2670                 default:
2671                         SetLastError (ERROR_GEN_FAILURE);
2672                 }
2673                 return FALSE;
2674         }
2675
2676         if (ret == 0)
2677                 return NORMAL_PRIORITY_CLASS;
2678         else if (ret < -15)
2679                 return REALTIME_PRIORITY_CLASS;
2680         else if (ret < -10)
2681                 return HIGH_PRIORITY_CLASS;
2682         else if (ret < 0)
2683                 return ABOVE_NORMAL_PRIORITY_CLASS;
2684         else if (ret > 10)
2685                 return IDLE_PRIORITY_CLASS;
2686         else if (ret > 0)
2687                 return BELOW_NORMAL_PRIORITY_CLASS;
2688
2689         return NORMAL_PRIORITY_CLASS;
2690 #else
2691         SetLastError (ERROR_NOT_SUPPORTED);
2692         return 0;
2693 #endif
2694 }
2695
2696 gboolean
2697 SetPriorityClass (gpointer process, guint32  priority_class)
2698 {
2699 #ifdef HAVE_SETPRIORITY
2700         struct _WapiHandle_process *process_handle;
2701         gboolean ok;
2702         int ret;
2703         int prio;
2704         pid_t pid;
2705         
2706         if ((GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED) == _WAPI_PROCESS_UNHANDLED) {
2707                 /* This is a pseudo handle */
2708                 pid = (pid_t)(GPOINTER_TO_UINT (process) & _WAPI_PROCESS_UNHANDLED_PID_MASK);
2709         } else {
2710                 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
2711                                           (gpointer *) &process_handle);
2712
2713                 if (!ok) {
2714                         SetLastError (ERROR_INVALID_HANDLE);
2715                         return FALSE;
2716                 }
2717                 pid = process_handle->id;
2718         }
2719
2720         switch (priority_class) {
2721         case IDLE_PRIORITY_CLASS:
2722                 prio = 19;
2723                 break;
2724         case BELOW_NORMAL_PRIORITY_CLASS:
2725                 prio = 10;
2726                 break;
2727         case NORMAL_PRIORITY_CLASS:
2728                 prio = 0;
2729                 break;
2730         case ABOVE_NORMAL_PRIORITY_CLASS:
2731                 prio = -5;
2732                 break;
2733         case HIGH_PRIORITY_CLASS:
2734                 prio = -11;
2735                 break;
2736         case REALTIME_PRIORITY_CLASS:
2737                 prio = -20;
2738                 break;
2739         default:
2740                 SetLastError (ERROR_INVALID_PARAMETER);
2741                 return FALSE;
2742         }
2743
2744         ret = setpriority (PRIO_PROCESS, pid, prio);
2745         if (ret == -1) {
2746                 switch (errno) {
2747                 case EPERM:
2748                 case EACCES:
2749                         SetLastError (ERROR_ACCESS_DENIED);
2750                         break;
2751                 case ESRCH:
2752                         SetLastError (ERROR_PROC_NOT_FOUND);
2753                         break;
2754                 default:
2755                         SetLastError (ERROR_GEN_FAILURE);
2756                 }
2757         }
2758
2759         return ret == 0;
2760 #else
2761         SetLastError (ERROR_NOT_SUPPORTED);
2762         return FALSE;
2763 #endif
2764 }
2765
2766 static void
2767 mono_processes_cleanup (void)
2768 {
2769         struct MonoProcess *mp;
2770         struct MonoProcess *prev = NULL;
2771         struct MonoProcess *candidate = NULL;
2772         gpointer unref_handle;
2773         int spin;
2774
2775         DEBUG ("%s", __func__);
2776
2777         /* Ensure we're not in here in multiple threads at once, nor recursive. */
2778         if (InterlockedCompareExchange (&mono_processes_cleaning_up, 1, 0) != 0)
2779                 return;
2780
2781         mp = mono_processes;
2782         while (mp != NULL) {
2783                 if (mp->pid == 0 && mp->handle != NULL) {
2784                         /* This process has exited and we need to remove the artifical ref
2785                          * on the handle */
2786                         mono_mutex_lock (&mono_processes_mutex);
2787                         unref_handle = mp->handle;
2788                         mp->handle = NULL;
2789                         mono_mutex_unlock (&mono_processes_mutex);
2790                         if (unref_handle)
2791                                 _wapi_handle_unref (unref_handle);
2792                         continue;
2793                 }
2794                 mp = mp->next;
2795         }
2796
2797         mp = mono_processes;
2798         spin = 0;
2799         while (mp != NULL) {
2800                 if ((mp->handle_count == 0 && mp->pid == 0) || candidate != NULL) {
2801                         if (spin > 0) {
2802                                 _wapi_handle_spin (spin);
2803                                 spin <<= 1;
2804                         }
2805
2806                         /* We've found a candidate */
2807                         mono_mutex_lock (&mono_processes_mutex);
2808                         if (candidate == NULL) {
2809                                 /* unlink it */
2810                                 if (mp == mono_processes) {
2811                                         mono_processes = mp->next;
2812                                 } else {
2813                                         prev->next = mp->next;
2814                                 }
2815                                 candidate = mp;
2816                         }
2817
2818                         /* It's still safe to traverse the structure.*/
2819                         mono_memory_barrier ();
2820
2821                         if (mono_processes_read_lock != 0) {
2822                                 /* The sigchld handler is watching us. Spin a bit and try again */
2823                                 if (spin == 0) {
2824                                         spin = 1;
2825                                 } else if (spin >= 8) {
2826                                         /* Just give up for now */
2827                                         mono_mutex_unlock (&mono_processes_mutex);
2828                                         break;
2829                                 }
2830                         } else {
2831                                 /* We've modified the list of processes, and we know the sigchld handler
2832                                  * isn't executing, so even if it executes at any moment, it'll see the
2833                                  * new version of the list. So now we can free the candidate. */
2834                                 DEBUG ("%s: freeing candidate %p", __func__, candidate);
2835                                 mp = candidate->next;
2836                                 MONO_SEM_DESTROY (&candidate->exit_sem);
2837                                 g_free (candidate);
2838                                 candidate = NULL;
2839                         }
2840
2841                         mono_mutex_unlock (&mono_processes_mutex);
2842
2843                         continue;
2844                 }
2845                 spin = 0;
2846                 prev = mp;
2847                 mp = mp->next;
2848         }
2849
2850         DEBUG ("%s done", __func__);
2851
2852         InterlockedDecrement (&mono_processes_cleaning_up);
2853 }
2854
2855 static void
2856 process_close (gpointer handle, gpointer data)
2857 {
2858         struct _WapiHandle_process *process_handle;
2859
2860         DEBUG ("%s", __func__);
2861
2862         process_handle = (struct _WapiHandle_process *) data;
2863         if (process_handle->mono_process && process_handle->self == _wapi_getpid ())
2864                 InterlockedDecrement (&process_handle->mono_process->handle_count);
2865         mono_processes_cleanup ();
2866 }
2867
2868 #if HAVE_SIGACTION
2869 MONO_SIGNAL_HANDLER_FUNC (static, mono_sigchld_signal_handler, (int _dummy, siginfo_t *info, void *context))
2870 {
2871         int status;
2872         int pid;
2873         struct MonoProcess *p;
2874
2875 #if DEBUG       
2876         fprintf (stdout, "SIG CHILD handler for pid: %i\n", info->si_pid);
2877 #endif
2878
2879         InterlockedIncrement (&mono_processes_read_lock);
2880
2881         do {
2882                 do {
2883                         pid = waitpid (-1, &status, WNOHANG);
2884                 } while (pid == -1 && errno == EINTR);
2885
2886                 if (pid <= 0)
2887                         break;
2888
2889 #if DEBUG
2890                 fprintf (stdout, "child ended: %i", pid);
2891 #endif
2892                 p = mono_processes;
2893                 while (p != NULL) {
2894                         if (p->pid == pid) {
2895                                 p->pid = 0; /* this pid doesn't exist anymore, clear it */
2896                                 p->status = status;
2897                                 MONO_SEM_POST (&p->exit_sem);
2898                                 break;
2899                         }
2900                         p = p->next;
2901                 }
2902         } while (1);
2903
2904         InterlockedDecrement (&mono_processes_read_lock);
2905
2906 #if DEBUG
2907         fprintf (stdout, "SIG CHILD handler: done looping.");
2908 #endif
2909 }
2910
2911 #endif
2912
2913 static void process_add_sigchld_handler (void)
2914 {
2915 #if HAVE_SIGACTION
2916         struct sigaction sa;
2917
2918         sa.sa_sigaction = mono_sigchld_signal_handler;
2919         sigemptyset (&sa.sa_mask);
2920         sa.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
2921         g_assert (sigaction (SIGCHLD, &sa, &previous_chld_sa) != -1);
2922         DEBUG ("Added SIGCHLD handler");
2923 #endif
2924 }
2925
2926 static guint32 process_wait (gpointer handle, guint32 timeout, gboolean alertable)
2927 {
2928         struct _WapiHandle_process *process_handle;
2929         gboolean ok;
2930         pid_t pid, ret;
2931         int status;
2932         guint32 start;
2933         guint32 now;
2934         struct MonoProcess *mp;
2935         gboolean spin;
2936         gpointer current_thread;
2937
2938         current_thread = wapi_get_current_thread_handle ();
2939         if (current_thread == NULL) {
2940                 SetLastError (ERROR_INVALID_HANDLE);
2941                 return WAIT_FAILED;
2942         }
2943
2944         /* FIXME: We can now easily wait on processes that aren't our own children,
2945          * but WaitFor*Object won't call us for pseudo handles. */
2946         g_assert ((GPOINTER_TO_UINT (handle) & _WAPI_PROCESS_UNHANDLED) != _WAPI_PROCESS_UNHANDLED);
2947
2948         DEBUG ("%s (%p, %u)", __func__, handle, timeout);
2949
2950         ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS, (gpointer *)&process_handle);
2951         if (ok == FALSE) {
2952                 g_warning ("%s: error looking up process handle %p", __func__, handle);
2953                 return WAIT_FAILED;
2954         }
2955
2956         if (process_handle->exited) {
2957                 /* We've already done this one */
2958                 DEBUG ("%s (%p, %u): Process already exited", __func__, handle, timeout);
2959                 return WAIT_OBJECT_0;
2960         }
2961
2962         pid = process_handle->id;
2963
2964         DEBUG ("%s (%p, %u): PID: %d", __func__, handle, timeout, pid);
2965
2966         /* We don't need to lock mono_processes here, the entry
2967          * has a handle_count > 0 which means it will not be freed. */
2968         mp = process_handle->mono_process;
2969         if (mp && process_handle->self != _wapi_getpid ()) {
2970                 /* mono_process points to memory in another process' address space: we can't use it */
2971                 mp = NULL;
2972         }
2973
2974         start = mono_msec_ticks ();
2975         now = start;
2976         spin = mp == NULL;
2977
2978         while (1) {
2979                 if (mp != NULL) {
2980                         /* We have a semaphore we can wait on */
2981                         if (timeout != INFINITE) {
2982                                 DEBUG ("%s (%p, %u): waiting on semaphore for %li ms...", 
2983                                         __func__, handle, timeout, (timeout - (now - start)));
2984
2985                                 ret = MONO_SEM_TIMEDWAIT_ALERTABLE (&mp->exit_sem, (timeout - (now - start)), alertable);
2986                         } else {
2987                                 DEBUG ("%s (%p, %u): waiting on semaphore forever...", 
2988                                         __func__, handle, timeout);
2989                                 ret = MONO_SEM_WAIT_ALERTABLE (&mp->exit_sem, alertable);
2990                         }
2991
2992                         if (ret == -1 && errno != EINTR && errno != ETIMEDOUT) {
2993                                 DEBUG ("%s (%p, %u): sem_timedwait failure: %s", 
2994                                         __func__, handle, timeout, g_strerror (errno));
2995                                 /* Should we return a failure here? */
2996                         }
2997
2998                         if (ret == 0) {
2999                                 /* Success, process has exited */
3000                                 MONO_SEM_POST (&mp->exit_sem);
3001                                 break;
3002                         }
3003                 } else {
3004                         /* We did not create this process, so we can't waidpid / sem_wait it.
3005                          * We need to poll for the pid existence */
3006                         DEBUG ("%s (%p, %u): polling on pid...", __func__, handle, timeout);
3007                         if (!is_pid_valid (pid)) {
3008                                 /* Success, process has exited */
3009                                 break;
3010                         }
3011                 }
3012
3013                 if (timeout == 0) {
3014                         DEBUG ("%s (%p, %u): WAIT_TIMEOUT (timeout = 0)", __func__, handle, timeout);
3015                         return WAIT_TIMEOUT;
3016                 }
3017
3018                 now = mono_msec_ticks ();
3019                 if (now - start >= timeout) {
3020                         DEBUG ("%s (%p, %u): WAIT_TIMEOUT", __func__, handle, timeout);
3021                         return WAIT_TIMEOUT;
3022                 }
3023
3024                 if (spin) {
3025                         /* "timeout - (now - start)" will not underflow, since timeout is always >=0,
3026                          * and we passed the check just above */
3027                         _wapi_handle_spin (MIN (100, timeout - (now - start)));
3028                 }
3029                 
3030                 if (alertable && _wapi_thread_apc_pending (current_thread)) {
3031                         DEBUG ("%s (%p, %u): WAIT_IO_COMPLETION", __func__, handle, timeout);
3032                         return WAIT_IO_COMPLETION;
3033                 }
3034         }
3035
3036         /* Process must have exited */
3037         DEBUG ("%s (%p, %u): Waited successfully", __func__, handle, timeout);
3038
3039         ret = _wapi_handle_lock_shared_handles ();
3040         g_assert (ret == 0);
3041
3042         status = mp ? mp->status : 0;
3043         if (WIFSIGNALED (status)) {
3044                 process_handle->exitstatus = 128 + WTERMSIG (status);
3045         } else {
3046                 process_handle->exitstatus = WEXITSTATUS (status);
3047         }
3048         _wapi_time_t_to_filetime (time (NULL), &process_handle->exit_time);
3049
3050         process_handle->exited = TRUE;
3051
3052         DEBUG ("%s (%p, %u): Setting pid %d signalled, exit status %d",
3053                    __func__, handle, timeout, process_handle->id, process_handle->exitstatus);
3054
3055         _wapi_shared_handle_set_signal_state (handle, TRUE);
3056
3057         _wapi_handle_unlock_shared_handles ();
3058
3059         return WAIT_OBJECT_0;
3060 }
3061
3062 void
3063 wapi_processes_cleanup (void)
3064 {
3065         g_free (cli_launcher);
3066 }