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