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