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