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