2007-07-22 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / io-layer / processes.c
index 7b6f91979b21bb8b738537f6a04cbdfbe47c29c9..928105c8f44cc827f27950ac337c0302e066e35e 100644 (file)
@@ -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>
@@ -80,6 +81,10 @@ 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);
@@ -101,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);
@@ -138,20 +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;
        
-       /* return FALSE to keep searching */
-       return (FALSE);
+       *(int *)user_data = status;
+       
+       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,
-                            FALSE);
+       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
@@ -177,6 +201,16 @@ 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
@@ -184,9 +218,15 @@ static guint32 process_wait (gpointer handle, guint32 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) {
@@ -197,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
 
-                       _wapi_handle_spin (100);
-                       timeout -= 100;
-               } while (timeout > 0);
+                                       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
 
+                                               return(WAIT_OBJECT_0);
+                                       } else {
+                                               return(WAIT_FAILED);
+                                       }
+                               }
+
+                               _wapi_handle_spin (100);
+                               timeout -= 100;
+                       } while (timeout > 0);
+               }
+               
                if (timeout <= 0) {
                        return(WAIT_TIMEOUT);
                }
@@ -224,7 +293,8 @@ static guint32 process_wait (gpointer handle, guint32 timeout)
                SetLastError (ERROR_OUTOFMEMORY);
                return (WAIT_FAILED);
        }
-
+       process_handle->waited = TRUE;
+       
        return(WAIT_OBJECT_0);
 }
 
@@ -234,7 +304,6 @@ void _wapi_process_signal_self ()
                process_set_termination_details (current_process, 0);
        }
 }
-
        
 static void process_set_defaults (struct _WapiHandle_process *process_handle)
 {
@@ -242,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
@@ -271,49 +390,65 @@ gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
         * 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);
-       }
-       
-       if (sei->lpParameters != NULL) {
-               u8params = g_utf16_to_utf8 (sei->lpParameters, -1, NULL, NULL, NULL);
-               if (u8params == 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);
-       } else {
-               args = g_utf8_to_utf16 (u8file, -1, NULL, NULL, NULL);
-       }
-               
-       if (args == NULL) {
+       args = utf16_concat (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) {
-               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) {
@@ -325,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,
@@ -333,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;
@@ -420,8 +663,6 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
                                dir[i] = '/';
                        }
                }
-       } else {
-               dir = g_get_current_dir ();
        }
        
 
@@ -448,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;
@@ -460,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 */
@@ -469,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 {
@@ -563,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);
@@ -611,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;
 
@@ -738,15 +1003,19 @@ gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
        } else if (pid == 0) {
                /* Child */
                
-               /* 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 ()
-                */
-               thr_ret = _wapi_handle_lock_shared_handles ();
-               g_assert (thr_ret == 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 ();
+                       _wapi_handle_unlock_shared_handles ();
+               }
                
                /* should we detach from the process group? */
 
@@ -766,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]);
                }
@@ -777,7 +1046,7 @@ 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);
                }
@@ -808,7 +1077,7 @@ 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;
        }
 
@@ -819,6 +1088,9 @@ cleanup:
                g_free (cmd);
        }
        if (full_prog != NULL) {
+               g_free (full_prog);
+       }
+       if (prog != NULL) {
                g_free (prog);
        }
        if (args != NULL) {
@@ -830,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);
 }
                
@@ -872,6 +1152,8 @@ static void process_set_current (void)
        const char *handle_env;
        struct _WapiHandle_process process_handle = {0};
        
+       mono_once (&process_ops_once, process_ops_init);
+       
        handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
        g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");