2007-07-22 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / io-layer / processes.c
index d8edc57bb3e23cceb9df096080f042cc1db8f008..928105c8f44cc827f27950ac337c0302e066e35e 100644 (file)
@@ -4,7 +4,7 @@
  * Author:
  *     Dick Porter (dick@ximian.com)
  *
- * (C) 2002 Ximian, Inc.
+ * (C) 2002-2006 Novell, Inc.
  */
 
 #include <config.h>
@@ -18,6 +18,7 @@
 #include <unistd.h>
 #include <signal.h>
 #include <sys/wait.h>
+#include <fcntl.h>
 
 #include <mono/io-layer/wapi.h>
 #include <mono/io-layer/wapi-private.h>
@@ -41,7 +42,8 @@ struct _WapiHandleOps _wapi_process_ops = {
        NULL,                           /* signal */
        NULL,                           /* own */
        NULL,                           /* is_owned */
-       process_wait                    /* special_wait */
+       process_wait,                   /* special_wait */
+       NULL                            /* prewait */   
 };
 
 static mono_once_t process_current_once=MONO_ONCE_INIT;
@@ -79,11 +81,24 @@ static gboolean process_set_termination_details (gpointer handle, int status)
                process_handle->exitstatus = WEXITSTATUS(status);
        }
        _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
+
+       /* Don't set process_handle->waited here, it needs to only
+        * happen in the parent when wait() has been called.
+        */
        
+#ifdef DEBUG
+       g_message ("%s: Setting handle %p signalled", __func__, handle);
+#endif
+
        _wapi_shared_handle_set_signal_state (handle, TRUE);
 
        _wapi_handle_unlock_shared_handles ();
 
+       /* Drop the reference we hold so we have somewhere to store
+        * the exit details, now the process has in fact exited
+        */
+       _wapi_handle_unref (handle);
+       
        return (ok);
 }
 
@@ -91,24 +106,24 @@ static gboolean process_set_termination_details (gpointer handle, int status)
  * updating process handle info.  This function is called from the
  * collection thread every few seconds.
  */
-static gboolean waitfor_pid (gpointer test, gpointer user_data G_GNUC_UNUSED)
+static gboolean waitfor_pid (gpointer test, gpointer user_data)
 {
        struct _WapiHandle_process *process;
        gboolean ok;
        int status;
        pid_t ret;
        
-       if (_wapi_handle_issignalled (test)) {
-               /* We've already done this one */
-               return (FALSE);
-       }
-       
        ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
                                  (gpointer *)&process);
        if (ok == FALSE) {
                /* The handle must have been too old and was reaped */
                return (FALSE);
        }
+
+       if (process->waited) {
+               /* We've already done this one */
+               return(FALSE);
+       }
        
        do {
                ret = waitpid (process->id, &status, WNOHANG);
@@ -128,19 +143,39 @@ static gboolean waitfor_pid (gpointer test, gpointer user_data G_GNUC_UNUSED)
        g_message ("%s: Process %d finished", __func__, ret);
 #endif
 
-       process_set_termination_details (test, status);
+       process->waited = TRUE;
+       
+       *(int *)user_data = status;
        
-       /* return FALSE to keep searching */
-       return (FALSE);
+       return (TRUE);
 }
 
 void _wapi_process_reap (void)
 {
+       gpointer proc;
+       int status;
+       
 #ifdef DEBUG
        g_message ("%s: Reaping child processes", __func__);
 #endif
 
-       _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid, NULL, NULL);
+       do {
+               proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
+                                           &status, NULL, FALSE);
+               if (proc != NULL) {
+#ifdef DEBUG
+                       g_message ("%s: process handle %p exit code %d",
+                                  __func__, proc, status);
+#endif
+                       
+                       process_set_termination_details (proc, status);
+
+                       /* _wapi_search_handle adds a reference, so
+                        * drop it here
+                        */
+                       _wapi_handle_unref (proc);
+               }
+       } while (proc != NULL);
 }
 
 /* Limitations: This can only wait for processes that are our own
@@ -166,16 +201,32 @@ static guint32 process_wait (gpointer handle, guint32 timeout)
                return(WAIT_FAILED);
        }
        
+       if (process_handle->waited) {
+               /* We've already done this one */
+#ifdef DEBUG
+               g_message ("%s: Process %p already signalled", __func__,
+                          handle);
+#endif
+
+               return (WAIT_OBJECT_0);
+       }
+       
        pid = process_handle->id;
        
 #ifdef DEBUG
-       g_message ("%s: PID is %d", __func__, pid);
+       g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
 #endif
 
        if (timeout == INFINITE) {
-               while ((ret = waitpid (pid, &status, 0)) != pid) {
-                       if (ret == (pid_t)-1 && errno != EINTR) {
-                               return(WAIT_FAILED);
+               if (pid == _wapi_getpid ()) {
+                       do {
+                               Sleep (10000);
+                       } while(1);
+               } else {
+                       while ((ret = waitpid (pid, &status, 0)) != pid) {
+                               if (ret == (pid_t)-1 && errno != EINTR) {
+                                       return(WAIT_FAILED);
+                               }
                        }
                }
        } else if (timeout == 0) {
@@ -186,18 +237,47 @@ static guint32 process_wait (gpointer handle, guint32 timeout)
                }
        } else {
                /* Poll in a loop */
-               do {
-                       ret = waitpid (pid, &status, WNOHANG);
-                       if (ret == pid) {
-                               break;
-                       } else if (ret == (pid_t)-1 && errno != EINTR) {
-                               return(WAIT_FAILED);
-                       }
+               if (pid == _wapi_getpid ()) {
+                       Sleep (timeout);
+                       return(WAIT_TIMEOUT);
+               } else {
+                       do {
+                               ret = waitpid (pid, &status, WNOHANG);
+#ifdef DEBUG
+                               g_message ("%s: waitpid returns: %d, timeout is %d", __func__, ret, timeout);
+#endif
+                               
+                               if (ret == pid) {
+                                       break;
+                               } else if (ret == (pid_t)-1 &&
+                                          errno != EINTR) {
+#ifdef DEBUG
+                                       g_message ("%s: waitpid failure: %s",
+                                                  __func__,
+                                                  g_strerror (errno));
+#endif
+
+                                       if (errno == ECHILD &&
+                                           process_handle->waited) {
+                                               /* The background
+                                                * process reaper must
+                                                * have got this one
+                                                */
+#ifdef DEBUG
+                                               g_message ("%s: Process %p already reaped", __func__, handle);
+#endif
 
-                       _wapi_handle_spin (100);
-                       timeout -= 100;
-               } while (timeout > 0);
+                                               return(WAIT_OBJECT_0);
+                                       } else {
+                                               return(WAIT_FAILED);
+                                       }
+                               }
 
+                               _wapi_handle_spin (100);
+                               timeout -= 100;
+                       } while (timeout > 0);
+               }
+               
                if (timeout <= 0) {
                        return(WAIT_TIMEOUT);
                }
@@ -205,7 +285,7 @@ static guint32 process_wait (gpointer handle, guint32 timeout)
 
        /* Process must have exited */
 #ifdef DEBUG
-       g_message ("%s: Wait done", __func__);
+       g_message ("%s: Wait done, status %d", __func__, status);
 #endif
 
        ok = process_set_termination_details (handle, status);
@@ -213,9 +293,17 @@ static guint32 process_wait (gpointer handle, guint32 timeout)
                SetLastError (ERROR_OUTOFMEMORY);
                return (WAIT_FAILED);
        }
-
+       process_handle->waited = TRUE;
+       
        return(WAIT_OBJECT_0);
 }
+
+void _wapi_process_signal_self ()
+{
+       if (current_process != NULL) {
+               process_set_termination_details (current_process, 0);
+       }
+}
        
 static void process_set_defaults (struct _WapiHandle_process *process_handle)
 {
@@ -223,16 +311,66 @@ static void process_set_defaults (struct _WapiHandle_process *process_handle)
        process_handle->min_working_set = 204800;
        process_handle->max_working_set = 1413120;
 
+       process_handle->waited = FALSE;
+       
        _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
 }
 
+static int
+len16 (const gunichar2 *str)
+{
+       int len = 0;
+       
+       while (*str++ != 0)
+               len++;
+
+       return len;
+}
+
+static gunichar2 *
+utf16_concat (const gunichar2 *first, ...)
+{
+       va_list args;
+       int total = 0, i;
+       const gunichar2 *s;
+       gunichar2 *ret;
+
+       va_start (args, first);
+       total += len16 (first);
+        for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
+               total += len16 (s);
+        }
+       va_end (args);
+
+       ret = g_new (gunichar2, total + 1);
+       if (ret == NULL)
+               return NULL;
+
+       ret [total] = 0;
+       i = 0;
+       for (s = first; *s != 0; s++)
+               ret [i++] = *s;
+       va_start (args, first);
+       for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
+               const gunichar2 *p;
+               
+               for (p = s; *p != 0; p++)
+                       ret [i++] = *p;
+       }
+       va_end (args);
+       
+       return ret;
+}
+
+static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
+static const gunichar2 *utf16_space = utf16_space_bytes; 
+
 /* Implemented as just a wrapper around CreateProcess () */
 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
 {
        gboolean ret;
        WapiProcessInformation process_info;
        gunichar2 *args;
-       gchar *u8file, *u8params, *u8args;
        
        if (sei == NULL) {
                /* w2k just segfaults here, but we can do better than
@@ -241,51 +379,76 @@ gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
                SetLastError (ERROR_INVALID_PARAMETER);
                return (FALSE);
        }
+
+       if (sei->lpFile == NULL) {
+               /* w2k returns TRUE for this, for some reason. */
+               return (TRUE);
+       }
        
        /* Put both executable and parameters into the second argument
         * to CreateProcess (), so it searches $PATH.  The conversion
         * into and back out of utf8 is because there is no
         * g_strdup_printf () equivalent for gunichar2 :-(
         */
-       u8file = g_utf16_to_utf8 (sei->lpFile, -1, NULL, NULL, NULL);
-       if (u8file == NULL) {
-               SetLastError (ERROR_INVALID_DATA);
-               return (FALSE);
-       }
-       
-       u8params = g_utf16_to_utf8 (sei->lpParameters, -1, NULL, NULL, NULL);
-       if (u8params == NULL) {
+       args = utf16_concat (sei->lpFile, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
+       if (args == NULL){
                SetLastError (ERROR_INVALID_DATA);
-               g_free (u8file);
                return (FALSE);
        }
-       
-       u8args = g_strdup_printf ("%s %s", u8file, u8params);
-       if (u8args == NULL) {
-               SetLastError (ERROR_INVALID_DATA);
-               g_free (u8params);
-               g_free (u8file);
-               return (FALSE);
-       }
-       
-       args = g_utf8_to_utf16 (u8args, -1, NULL, NULL, NULL);
-       
-       g_free (u8file);
-       g_free (u8params);
-       g_free (u8args);
-
-       if (args == NULL) {
-               SetLastError (ERROR_INVALID_DATA);
-               return (FALSE);
-       }
-       
        ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
                             CREATE_UNICODE_ENVIRONMENT, NULL,
                             sei->lpDirectory, NULL, &process_info);
        g_free (args);
        
        if (!ret) {
-               return (FALSE);
+               static char *handler;
+               static gunichar2 *handler_utf16;
+               
+               if (handler_utf16 == (gunichar2 *)-1)
+                       return FALSE;
+
+#ifdef PLATFORM_MACOSX
+               handler = "/usr/bin/open";
+#else
+               /*
+                * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
+                * if that fails, try to use gnome-open, then kfmclient
+                */
+               handler = g_find_program_in_path ("xdg-open");
+               if (handler == NULL){
+                       handler = g_find_program_in_path ("gnome-open");
+                       if (handler == NULL){
+                               handler = g_find_program_in_path ("kfmclient");
+                               if (handler == NULL){
+                                       handler_utf16 = (gunichar2 *) -1;
+                                       return (FALSE);
+                               } else {
+                                       /* kfmclient needs exec argument */
+                                       char *old = handler;
+                                       handler = g_strconcat (old, " exec",
+                                                              NULL);
+                                       g_free (old);
+                               }
+                       }
+               }
+#endif
+               handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
+               g_free (handler);
+               args = utf16_concat (handler_utf16, utf16_space, sei->lpFile,
+                                    sei->lpParameters == NULL ? NULL : utf16_space,
+                                    sei->lpParameters, NULL);
+               if (args == NULL){
+                       SetLastError (ERROR_INVALID_DATA);
+                       return FALSE;
+               }
+               ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
+                                    CREATE_UNICODE_ENVIRONMENT, NULL,
+                                    sei->lpDirectory, NULL, &process_info);
+               g_free (args);
+               if (!ret){
+                       SetLastError (ERROR_INVALID_DATA);
+                       return FALSE;
+               }
        }
        
        if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
@@ -297,6 +460,114 @@ gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
        return (ret);
 }
 
+static gboolean
+is_managed_binary (const gchar *filename)
+{
+       int original_errno = errno;
+#if defined(HAVE_LARGE_FILE_SUPPORT) && defined(O_LARGEFILE)
+       int file = open (filename, O_RDONLY | O_LARGEFILE);
+#else
+       int file = open (filename, O_RDONLY);
+#endif
+       off_t new_offset;
+       unsigned char buffer[8];
+       off_t file_size, optional_header_offset;
+       off_t pe_header_offset;
+       gboolean managed = FALSE;
+       int num_read;
+       guint32 first_word, second_word;
+       
+       /* If we are unable to open the file, then we definitely
+        * can't say that it is managed. The child mono process
+        * probably wouldn't be able to open it anyway.
+        */
+       if (file < 0) {
+               errno = original_errno;
+               return FALSE;
+       }
+
+       /* Retrieve the length of the file for future sanity checks. */
+       file_size = lseek (file, 0, SEEK_END);
+       lseek (file, 0, SEEK_SET);
+
+       /* We know we need to read a header field at offset 60. */
+       if (file_size < 64)
+               goto leave;
+
+       num_read = read (file, buffer, 2);
+
+       if ((num_read != 2) || (buffer[0] != 'M') || (buffer[1] != 'Z'))
+               goto leave;
+
+       new_offset = lseek (file, 60, SEEK_SET);
+
+       if (new_offset != 60)
+               goto leave;
+       
+       num_read = read (file, buffer, 4);
+
+       if (num_read != 4)
+               goto leave;
+       pe_header_offset =  buffer[0]
+               | (buffer[1] <<  8)
+               | (buffer[2] << 16)
+               | (buffer[3] << 24);
+       
+       if (pe_header_offset + 24 > file_size)
+               goto leave;
+
+       new_offset = lseek (file, pe_header_offset, SEEK_SET);
+
+       if (new_offset != pe_header_offset)
+               goto leave;
+
+       num_read = read (file, buffer, 4);
+
+       if ((num_read != 4) || (buffer[0] != 'P') || (buffer[1] != 'E') || (buffer[2] != 0) || (buffer[3] != 0))
+               goto leave;
+
+       /*
+        * Verify that the header we want in the optional header data
+        * is present in this binary.
+        */
+       new_offset = lseek (file, pe_header_offset + 20, SEEK_SET);
+
+       if (new_offset != pe_header_offset + 20)
+               goto leave;
+
+       num_read = read (file, buffer, 2);
+
+       if ((num_read != 2) || ((buffer[0] | (buffer[1] << 8)) < 216))
+               goto leave;
+
+       /* Read the CLR header address and size fields. These will be
+        * zero if the binary is not managed.
+        */
+       optional_header_offset = pe_header_offset + 24;
+       new_offset = lseek (file, optional_header_offset + 208, SEEK_SET);
+
+       if (new_offset != optional_header_offset + 208)
+               goto leave;
+
+       num_read = read (file, buffer, 8);
+       
+       /* We are not concerned with endianness, only with
+        * whether it is zero or not.
+        */
+       first_word = *(guint32 *)&buffer[0];
+       second_word = *(guint32 *)&buffer[4];
+       
+       if ((num_read != 8) || (first_word == 0) || (second_word == 0))
+               goto leave;
+       
+       managed = TRUE;
+
+leave:
+       close (file);
+       errno = original_errno;
+       return managed;
+}
+
 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                        WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
                        WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
@@ -305,7 +576,7 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                        WapiStartupInfo *startup,
                        WapiProcessInformation *process_info)
 {
-       gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv;
+       gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
        guint32 i, env_count = 0;
        gboolean ret = FALSE;
        gpointer handle;
@@ -313,7 +584,6 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
        GError *gerr = NULL;
        int in_fd, out_fd, err_fd;
        pid_t pid;
-       int lockpipe [2];
        int thr_ret;
        
        mono_once (&process_ops_once, process_ops_init);
@@ -393,8 +663,6 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                                dir[i] = '/';
                        }
                }
-       } else {
-               dir = g_get_current_dir ();
        }
        
 
@@ -421,7 +689,6 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                                g_message ("%s: Couldn't find executable %s",
                                           __func__, prog);
 #endif
-                               g_free (prog);
                                g_free (unquoted);
                                SetLastError (ERROR_FILE_NOT_FOUND);
                                goto cleanup;
@@ -433,7 +700,6 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                        char *curdir = g_get_current_dir ();
 
                        prog = g_strdup_printf ("%s/%s", curdir, unquoted);
-                       g_free (unquoted);
                        g_free (curdir);
 
                        /* And make sure it's executable */
@@ -442,11 +708,12 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                                g_message ("%s: Couldn't find executable %s",
                                           __func__, prog);
 #endif
-                               g_free (prog);
+                               g_free (unquoted);
                                SetLastError (ERROR_FILE_NOT_FOUND);
                                goto cleanup;
                        }
                }
+               g_free (unquoted);
 
                args_after_prog = args;
        } else {
@@ -536,7 +803,6 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                        
                        /* Executable existing ? */
                        if (access (prog, X_OK) != 0) {
-                               g_free (prog);
 #ifdef DEBUG
                                g_message ("%s: Couldn't find executable %s",
                                           __func__, token);
@@ -584,6 +850,32 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                   args_after_prog);
 #endif
        
+       /* Check for CLR binaries; if found, we will try to invoke
+        * them using the same mono binary that started us.
+        */
+       if (is_managed_binary (prog) && (appname == NULL)) {
+               gsize bytes_ignored;
+
+               appname = mono_unicode_from_external ("mono", &bytes_ignored);
+
+               if (appname != NULL) {
+                       cmdline = utf16_concat (appname, utf16_space, cmdline, NULL);
+                       
+                       g_free ((gunichar2 *)appname);
+                       
+                       if (cmdline != NULL) {
+                               gboolean return_value = CreateProcess (
+                                       NULL, cmdline, process_attrs,
+                                       thread_attrs, inherit_handles, create_flags, new_environ,
+                                       cwd, startup, process_info);
+                               
+                               g_free ((gunichar2 *)cmdline);
+                               
+                               return return_value;
+                       }
+               }
+       }
+
        if (args_after_prog != NULL && *args_after_prog) {
                gchar *qprog;
 
@@ -622,6 +914,11 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                SetLastError (ERROR_PATH_NOT_FOUND);
                goto cleanup;
        }
+
+       /* Hold another reference so the process has somewhere to
+        * store its exit data even if we drop this handle
+        */
+       _wapi_handle_ref (handle);
        
        /* new_environ is a block of NULL-terminated strings, which
         * is itself NULL-terminated. Of course, passing an array of
@@ -693,8 +990,9 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                
                env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
        }
-       
-       pipe (lockpipe);
+
+       thr_ret = _wapi_handle_lock_shared_handles ();
+       g_assert (thr_ret == 0);
        
        pid = fork ();
        if (pid == -1) {
@@ -704,13 +1002,20 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                goto cleanup;
        } else if (pid == 0) {
                /* Child */
-               char c [1];
                
-               /* Wait for the parent to finish setting up the handle */
-               close (lockpipe [1]);
-               while (read (lockpipe [0], c, 1) == -1 &&
-                      errno == EINTR);
-               close (lockpipe [0]);
+               if (_wapi_shm_disabled == FALSE) {
+                       /* Wait for the parent to finish setting up
+                        * the handle.  The semaphore lock is safe
+                        * because the sem_undo structures of a
+                        * semaphore aren't inherited across a fork
+                        * (), but we can't do this if we're not using
+                        * the shared memory
+                        */
+                       thr_ret = _wapi_handle_lock_shared_handles ();
+                       g_assert (thr_ret == 0);
+       
+                       _wapi_handle_unlock_shared_handles ();
+               }
                
                /* should we detach from the process group? */
 
@@ -730,7 +1035,7 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
 
 #ifdef DEBUG
                g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
-                          dir);
+                          dir==NULL?".":dir);
                for (i = 0; argv[i] != NULL; i++) {
                        g_message ("arg %d: [%s]", i, argv[i]);
                }
@@ -741,21 +1046,18 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
 #endif
 
                /* set cwd */
-               if (chdir (dir) == -1) {
+               if (dir != NULL && chdir (dir) == -1) {
                        /* set error */
-                       exit (-1);
+                       _exit (-1);
                }
                
                /* exec */
                execve (argv[0], argv, env_strings);
                
                /* set error */
-               exit (-1);
+               _exit (-1);
        }
        /* parent */
-
-       thr_ret = _wapi_handle_lock_shared_handles ();
-       g_assert (thr_ret == 0);
        
        ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
                                   (gpointer *)&process_handle_data);
@@ -768,10 +1070,6 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
        
        process_handle_data->id = pid;
        
-       _wapi_handle_unlock_shared_handles ();
-       
-       write (lockpipe [1], cmd, 1);
-       
        if (process_info != NULL) {
                process_info->hProcess = handle;
                process_info->dwProcessId = pid;
@@ -779,18 +1077,20 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                /* FIXME: we might need to handle the thread info some
                 * day
                 */
-               process_info->hThread = NULL;
+               process_info->hThread = INVALID_HANDLE_VALUE;
                process_info->dwThreadId = 0;
        }
 
 cleanup:
-       close (lockpipe [0]);
-       close (lockpipe [1]);
-       
+       _wapi_handle_unlock_shared_handles ();
+
        if (cmd != NULL) {
                g_free (cmd);
        }
        if (full_prog != NULL) {
+               g_free (full_prog);
+       }
+       if (prog != NULL) {
                g_free (prog);
        }
        if (args != NULL) {
@@ -802,7 +1102,15 @@ cleanup:
        if(env_strings != NULL) {
                g_strfreev (env_strings);
        }
+       if (argv != NULL) {
+               g_strfreev (argv);
+       }
        
+#ifdef DEBUG
+       g_message ("%s: returning handle %p for pid %d", __func__, handle,
+                  pid);
+#endif
+
        return(ret);
 }
                
@@ -833,63 +1141,74 @@ static void process_set_name (struct _WapiHandle_process *process_handle)
 
 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
 
+#if !GLIB_CHECK_VERSION (2,4,0)
+#define g_setenv(a,b,c) setenv(a,b,c)
+#define g_unsetenv(a) unsetenv(a)
+#endif
+
 static void process_set_current (void)
 {
-       pid_t pid = getpid ();
-       char *handle_env;
+       pid_t pid = _wapi_getpid ();
+       const char *handle_env;
        struct _WapiHandle_process process_handle = {0};
        
-       handle_env = getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
+       mono_once (&process_ops_once, process_ops_init);
+       
+       handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
+       g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
+       
        if (handle_env != NULL) {
                struct _WapiHandle_process *process_handlep;
-               guchar *procname = NULL;
+               gchar *procname = NULL;
                gboolean ok;
                
                current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
                
 #ifdef DEBUG
-               g_message ("%s: Found my process handle: %p (offset %d)",
-                          __func__, current_process, atoi (handle_env));
+               g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
+                          __func__, current_process, atoi (handle_env),
+                          atoi (handle_env));
 #endif
 
                ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
                                          (gpointer *)&process_handlep);
-               if (ok == FALSE) {
-                       g_warning ("%s: error looking up process handle %p",
-                                  __func__, current_process);
-                       return;
-               }
-
-               /* This test will break on linuxthreads, but that
-                * should be ancient history on all distros we care
-                * about by now
-                */
-               if (process_handlep->id == pid) {
-                       procname = process_handlep->proc_name;
-                       if (!strcmp (procname, "mono")) {
-                               /* Set a better process name */
+               if (ok) {
+                       /* This test will probably break on linuxthreads, but
+                        * that should be ancient history on all distros we
+                        * care about by now
+                        */
+                       if (process_handlep->id == pid) {
+                               procname = process_handlep->proc_name;
+                               if (!strcmp (procname, "mono")) {
+                                       /* Set a better process name */
 #ifdef DEBUG
-                               g_message ("%s: Setting better process name",
-                                          __func__);
+                                       g_message ("%s: Setting better process name", __func__);
 #endif
-
-                               process_set_name (process_handlep);
-                       } else {
+                                       
+                                       process_set_name (process_handlep);
+                               } else {
 #ifdef DEBUG
-                               g_message ("%s: Leaving process name: %s",
-                                          __func__, procname);
+                                       g_message ("%s: Leaving process name: %s", __func__, procname);
 #endif
+                               }
+
+                               return;
                        }
 
-                       return;
+                       /* Wrong pid, so drop this handle and fall through to
+                        * create a new one
+                        */
+                       _wapi_handle_unref (current_process);
                }
-
-               /* Wrong pid, so drop this handle and fall through to
-                * create a new one
-                */
-               _wapi_handle_unref (current_process);
        }
 
+       /* We get here if the handle wasn't specified in the
+        * environment, or if the process ID was wrong, or if the
+        * handle lookup failed (eg if the parent process forked and
+        * quit immediately, and deleted the shared data before the
+        * child got a chance to attach it.)
+        */
+
 #ifdef DEBUG
        g_message ("%s: Need to create my own process handle", __func__);
 #endif
@@ -905,11 +1224,15 @@ static void process_set_current (void)
                g_warning ("%s: error creating process handle", __func__);
                return;
        }
-               
-       /* Make sure the new handle has a reference so it wont go away
-        * until this process exits
-        */
+}
+
+gpointer _wapi_process_duplicate ()
+{
+       mono_once (&process_current_once, process_set_current);
+       
        _wapi_handle_ref (current_process);
+       
+       return(current_process);
 }
 
 /* Returns a pseudo handle that doesn't need to be closed afterwards */
@@ -917,7 +1240,7 @@ gpointer GetCurrentProcess (void)
 {
        mono_once (&process_current_once, process_set_current);
                
-       return((gpointer)-1);
+       return(_WAPI_PROCESS_CURRENT);
 }
 
 guint32 GetProcessId (gpointer handle)
@@ -1025,7 +1348,7 @@ gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
        mono_once (&process_current_once, process_set_current);
        
        _wapi_search_handle (WAPI_HANDLE_PROCESS, process_enum, processes,
-                            NULL);
+                            NULL, TRUE);
        
        fit=len/sizeof(guint32);
        for (i = 0, j = 0; j < fit && i < processes->len; i++) {
@@ -1079,7 +1402,7 @@ gpointer OpenProcess (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUS
 
        handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
                                      process_open_compare,
-                                     GUINT_TO_POINTER (pid), NULL);
+                                     GUINT_TO_POINTER (pid), NULL, TRUE);
        if (handle == 0) {
 #ifdef DEBUG
                g_message ("%s: Can't find pid %d", __func__, pid);
@@ -1224,7 +1547,7 @@ guint32 GetModuleBaseName (gpointer process, gpointer module,
                 */
                pid_t pid;
                gunichar2 *procname;
-               guchar *procname_utf8 = NULL;
+               gchar *procname_utf8 = NULL;
                glong len, bytes;
                
 #ifdef DEBUG