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