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