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