2 * processes.c: Process handles
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2006 Novell, Inc.
17 #include <sys/types.h>
22 #include <mono/io-layer/wapi.h>
23 #include <mono/io-layer/wapi-private.h>
24 #include <mono/io-layer/handles-private.h>
25 #include <mono/io-layer/misc-private.h>
26 #include <mono/io-layer/mono-mutex.h>
27 #include <mono/io-layer/process-private.h>
28 #include <mono/io-layer/threads.h>
29 #include <mono/utils/strenc.h>
30 #include <mono/io-layer/timefuncs-private.h>
32 /* The process' environment strings */
33 extern char **environ;
37 static guint32 process_wait (gpointer handle, guint32 timeout);
39 struct _WapiHandleOps _wapi_process_ops = {
40 NULL, /* close_shared */
44 process_wait, /* special_wait */
48 static mono_once_t process_current_once=MONO_ONCE_INIT;
49 static gpointer current_process=NULL;
51 static mono_once_t process_ops_once=MONO_ONCE_INIT;
53 static void process_ops_init (void)
55 _wapi_handle_register_capabilities (WAPI_HANDLE_PROCESS,
56 WAPI_HANDLE_CAP_WAIT |
57 WAPI_HANDLE_CAP_SPECIAL_WAIT);
60 static gboolean process_set_termination_details (gpointer handle, int status)
62 struct _WapiHandle_process *process_handle;
66 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
67 (gpointer *)&process_handle);
69 g_warning ("%s: error looking up process handle %p",
74 thr_ret = _wapi_handle_lock_shared_handles ();
75 g_assert (thr_ret == 0);
77 if (WIFSIGNALED(status)) {
78 process_handle->exitstatus = 128 + WTERMSIG(status);
80 process_handle->exitstatus = WEXITSTATUS(status);
82 _wapi_time_t_to_filetime (time(NULL), &process_handle->exit_time);
84 /* Don't set process_handle->waited here, it needs to only
85 * happen in the parent when wait() has been called.
89 g_message ("%s: Setting handle %p signalled", __func__, handle);
92 _wapi_shared_handle_set_signal_state (handle, TRUE);
94 _wapi_handle_unlock_shared_handles ();
96 /* Drop the reference we hold so we have somewhere to store
97 * the exit details, now the process has in fact exited
99 _wapi_handle_unref (handle);
104 /* See if any child processes have terminated and wait() for them,
105 * updating process handle info. This function is called from the
106 * collection thread every few seconds.
108 static gboolean waitfor_pid (gpointer test, gpointer user_data)
110 struct _WapiHandle_process *process;
115 ok = _wapi_lookup_handle (test, WAPI_HANDLE_PROCESS,
116 (gpointer *)&process);
118 /* The handle must have been too old and was reaped */
122 if (process->waited) {
123 /* We've already done this one */
128 ret = waitpid (process->id, &status, WNOHANG);
129 } while (errno == EINTR);
132 /* Process not ready for wait */
134 g_message ("%s: Process %d not ready for waiting for: %s",
135 __func__, process->id, g_strerror (errno));
142 g_message ("%s: Process %d finished", __func__, ret);
145 process->waited = TRUE;
147 *(int *)user_data = status;
152 void _wapi_process_reap (void)
158 g_message ("%s: Reaping child processes", __func__);
162 proc = _wapi_search_handle (WAPI_HANDLE_PROCESS, waitfor_pid,
163 &status, NULL, FALSE);
166 g_message ("%s: process handle %p exit code %d",
167 __func__, proc, status);
170 process_set_termination_details (proc, status);
172 /* _wapi_search_handle adds a reference, so
175 _wapi_handle_unref (proc);
177 } while (proc != NULL);
180 /* Limitations: This can only wait for processes that are our own
181 * children. Fixing this means resurrecting a daemon helper to manage
184 static guint32 process_wait (gpointer handle, guint32 timeout)
186 struct _WapiHandle_process *process_handle;
192 g_message ("%s: Waiting for process %p", __func__, handle);
195 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
196 (gpointer *)&process_handle);
198 g_warning ("%s: error looking up process handle %p", __func__,
203 if (process_handle->waited) {
204 /* We've already done this one */
206 g_message ("%s: Process %p already signalled", __func__,
210 return (WAIT_OBJECT_0);
213 pid = process_handle->id;
216 g_message ("%s: PID is %d, timeout %d", __func__, pid, timeout);
219 if (timeout == INFINITE) {
220 if (pid == _wapi_getpid ()) {
225 while ((ret = waitpid (pid, &status, 0)) != pid) {
226 if (ret == (pid_t)-1 && errno != EINTR) {
231 } else if (timeout == 0) {
233 ret = waitpid (pid, &status, WNOHANG);
235 return (WAIT_TIMEOUT);
239 if (pid == _wapi_getpid ()) {
241 return(WAIT_TIMEOUT);
244 ret = waitpid (pid, &status, WNOHANG);
246 g_message ("%s: waitpid returns: %d, timeout is %d", __func__, ret, timeout);
251 } else if (ret == (pid_t)-1 &&
254 g_message ("%s: waitpid failure: %s",
259 if (errno == ECHILD &&
260 process_handle->waited) {
262 * process reaper must
266 g_message ("%s: Process %p already reaped", __func__, handle);
269 return(WAIT_OBJECT_0);
275 _wapi_handle_spin (100);
277 } while (timeout > 0);
281 return(WAIT_TIMEOUT);
285 /* Process must have exited */
287 g_message ("%s: Wait done, status %d", __func__, status);
290 ok = process_set_termination_details (handle, status);
292 SetLastError (ERROR_OUTOFMEMORY);
293 return (WAIT_FAILED);
295 process_handle->waited = TRUE;
297 return(WAIT_OBJECT_0);
300 void _wapi_process_signal_self ()
302 if (current_process != NULL) {
303 process_set_termination_details (current_process, 0);
307 static void process_set_defaults (struct _WapiHandle_process *process_handle)
309 /* These seem to be the defaults on w2k */
310 process_handle->min_working_set = 204800;
311 process_handle->max_working_set = 1413120;
313 process_handle->waited = FALSE;
315 _wapi_time_t_to_filetime (time (NULL), &process_handle->create_time);
319 len16 (const gunichar2 *str)
330 utf16_concat (const gunichar2 *first, ...)
337 va_start (args, first);
338 total += len16 (first);
339 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg(args, gunichar2 *)){
344 ret = g_new (gunichar2, total + 1);
350 for (s = first; *s != 0; s++)
352 va_start (args, first);
353 for (s = va_arg (args, gunichar2 *); s != NULL; s = va_arg (args, gunichar2 *)){
356 for (p = s; *p != 0; p++)
364 static const gunichar2 utf16_space_bytes [2] = { 0x20, 0 };
365 static const gunichar2 *utf16_space = utf16_space_bytes;
367 /* Implemented as just a wrapper around CreateProcess () */
368 gboolean ShellExecuteEx (WapiShellExecuteInfo *sei)
371 WapiProcessInformation process_info;
375 /* w2k just segfaults here, but we can do better than
378 SetLastError (ERROR_INVALID_PARAMETER);
382 if (sei->lpFile == NULL) {
383 /* w2k returns TRUE for this, for some reason. */
387 /* Put both executable and parameters into the second argument
388 * to CreateProcess (), so it searches $PATH. The conversion
389 * into and back out of utf8 is because there is no
390 * g_strdup_printf () equivalent for gunichar2 :-(
392 args = utf16_concat (sei->lpFile, sei->lpParameters == NULL ? NULL : utf16_space, sei->lpParameters, NULL);
394 SetLastError (ERROR_INVALID_DATA);
397 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
398 CREATE_UNICODE_ENVIRONMENT, NULL,
399 sei->lpDirectory, NULL, &process_info);
403 static char *handler;
404 static gunichar2 *handler_utf16;
406 if (handler_utf16 == (gunichar2 *)-1)
409 #ifdef PLATFORM_MACOSX
410 handler = "/usr/bin/open";
413 * On Linux, try: xdg-open, the FreeDesktop standard way of doing it,
414 * if that fails, try to use gnome-open, then kfmclient
416 handler = g_find_program_in_path ("xdg-open");
417 if (handler == NULL){
418 handler = g_find_program_in_path ("gnome-open");
419 if (handler == NULL){
420 handler = g_find_program_in_path ("kfmclient");
421 if (handler == NULL){
422 handler_utf16 = (gunichar2 *) -1;
425 /* kfmclient needs exec argument */
427 handler = g_strconcat (old, " exec",
434 handler_utf16 = g_utf8_to_utf16 (handler, -1, NULL, NULL, NULL);
436 args = utf16_concat (handler_utf16, utf16_space, sei->lpFile,
437 sei->lpParameters == NULL ? NULL : utf16_space,
438 sei->lpParameters, NULL);
440 SetLastError (ERROR_INVALID_DATA);
443 ret = CreateProcess (NULL, args, NULL, NULL, TRUE,
444 CREATE_UNICODE_ENVIRONMENT, NULL,
445 sei->lpDirectory, NULL, &process_info);
448 SetLastError (ERROR_INVALID_DATA);
453 if (sei->fMask & SEE_MASK_NOCLOSEPROCESS) {
454 sei->hProcess = process_info.hProcess;
456 CloseHandle (process_info.hProcess);
462 gboolean CreateProcess (const gunichar2 *appname, const gunichar2 *cmdline,
463 WapiSecurityAttributes *process_attrs G_GNUC_UNUSED,
464 WapiSecurityAttributes *thread_attrs G_GNUC_UNUSED,
465 gboolean inherit_handles, guint32 create_flags,
466 gpointer new_environ, const gunichar2 *cwd,
467 WapiStartupInfo *startup,
468 WapiProcessInformation *process_info)
470 gchar *cmd=NULL, *prog = NULL, *full_prog = NULL, *args = NULL, *args_after_prog = NULL, *dir = NULL, **env_strings = NULL, **argv = NULL;
471 guint32 i, env_count = 0;
472 gboolean ret = FALSE;
474 struct _WapiHandle_process process_handle = {0}, *process_handle_data;
476 int in_fd, out_fd, err_fd;
480 mono_once (&process_ops_once, process_ops_init);
482 /* appname and cmdline specify the executable and its args:
484 * If appname is not NULL, it is the name of the executable.
485 * Otherwise the executable is the first token in cmdline.
487 * Executable searching:
489 * If appname is not NULL, it can specify the full path and
490 * file name, or else a partial name and the current directory
491 * will be used. There is no additional searching.
493 * If appname is NULL, the first whitespace-delimited token in
494 * cmdline is used. If the name does not contain a full
495 * directory path, the search sequence is:
497 * 1) The directory containing the current process
498 * 2) The current working directory
499 * 3) The windows system directory (Ignored)
500 * 4) The windows directory (Ignored)
503 * Just to make things more interesting, tokens can contain
504 * white space if they are surrounded by quotation marks. I'm
505 * beginning to understand just why windows apps are generally
506 * so crap, with an API like this :-(
508 if (appname != NULL) {
509 cmd = mono_unicode_to_external (appname);
512 g_message ("%s: unicode conversion returned NULL",
516 SetLastError (ERROR_PATH_NOT_FOUND);
520 /* Turn all the slashes round the right way */
521 for (i = 0; i < strlen (cmd); i++) {
522 if (cmd[i] == '\\') {
528 if (cmdline != NULL) {
529 args = mono_unicode_to_external (cmdline);
532 g_message ("%s: unicode conversion returned NULL", __func__);
535 SetLastError (ERROR_PATH_NOT_FOUND);
541 dir = mono_unicode_to_external (cwd);
544 g_message ("%s: unicode conversion returned NULL", __func__);
547 SetLastError (ERROR_PATH_NOT_FOUND);
551 /* Turn all the slashes round the right way */
552 for (i = 0; i < strlen (dir); i++) {
553 if (dir[i] == '\\') {
560 /* We can't put off locating the executable any longer :-( */
563 if (g_ascii_isalpha (cmd[0]) && (cmd[1] == ':')) {
564 /* Strip off the drive letter. I can't
565 * believe that CP/M holdover is still
568 g_memmove (cmd, cmd+2, strlen (cmd)-2);
569 cmd[strlen (cmd)-2] = '\0';
572 unquoted = g_shell_unquote (cmd, NULL);
573 if (unquoted[0] == '/') {
574 /* Assume full path given */
575 prog = g_strdup (unquoted);
577 /* Executable existing ? */
578 if (access (prog, X_OK) != 0) {
580 g_message ("%s: Couldn't find executable %s",
584 SetLastError (ERROR_FILE_NOT_FOUND);
588 /* Search for file named by cmd in the current
591 char *curdir = g_get_current_dir ();
593 prog = g_strdup_printf ("%s/%s", curdir, unquoted);
596 /* And make sure it's executable */
597 if (access (prog, X_OK) != 0) {
599 g_message ("%s: Couldn't find executable %s",
603 SetLastError (ERROR_FILE_NOT_FOUND);
609 args_after_prog = args;
614 /* Dig out the first token from args, taking quotation
618 /* First, strip off all leading whitespace */
619 args = g_strchug (args);
621 /* args_after_prog points to the contents of args
622 * after token has been set (otherwise argv[0] is
625 args_after_prog = args;
627 /* Assume the opening quote will always be the first
630 if (args[0] == '\"' || args [0] == '\'') {
632 for (i = 1; args[i] != '\0' && args[i] != quote; i++);
633 if (g_ascii_isspace (args[i+1])) {
634 /* We found the first token */
635 token = g_strndup (args+1, i-1);
636 args_after_prog = args + i;
638 /* Quotation mark appeared in the
639 * middle of the token. Just give the
640 * whole first token, quotes and all,
647 /* No quote mark, or malformed */
648 for (i = 0; args[i] != '\0'; i++) {
649 if (g_ascii_isspace (args[i])) {
650 token = g_strndup (args, i);
651 args_after_prog = args + i + 1;
657 if (token == NULL && args[0] != '\0') {
658 /* Must be just one token in the string */
659 token = g_strdup (args);
660 args_after_prog = NULL;
666 g_message ("%s: Couldn't find what to exec", __func__);
669 SetLastError (ERROR_PATH_NOT_FOUND);
673 /* Turn all the slashes round the right way. Only for
676 for (i = 0; i < strlen (token); i++) {
677 if (token[i] == '\\') {
682 if (g_ascii_isalpha (token[0]) && (token[1] == ':')) {
683 /* Strip off the drive letter. I can't
684 * believe that CP/M holdover is still
687 g_memmove (token, token+2, strlen (token)-2);
688 token[strlen (token)-2] = '\0';
691 if (token[0] == '/') {
692 /* Assume full path given */
693 prog = g_strdup (token);
695 /* Executable existing ? */
696 if (access (prog, X_OK) != 0) {
698 g_message ("%s: Couldn't find executable %s",
702 SetLastError (ERROR_FILE_NOT_FOUND);
707 char *curdir = g_get_current_dir ();
709 /* FIXME: Need to record the directory
710 * containing the current process, and check
711 * that for the new executable as the first
715 prog = g_strdup_printf ("%s/%s", curdir, token);
718 /* I assume X_OK is the criterion to use,
721 if (access (prog, X_OK) != 0) {
723 prog = g_find_program_in_path (token);
726 g_message ("%s: Couldn't find executable %s", __func__, token);
730 SetLastError (ERROR_FILE_NOT_FOUND);
740 g_message ("%s: Exec prog [%s] args [%s]", __func__, prog,
744 if (args_after_prog != NULL && *args_after_prog) {
747 qprog = g_shell_quote (prog);
748 full_prog = g_strconcat (qprog, " ", args_after_prog, NULL);
751 full_prog = g_shell_quote (prog);
754 ret = g_shell_parse_argv (full_prog, NULL, &argv, &gerr);
756 /* FIXME: Could do something with the GError here
760 if (startup != NULL && startup->dwFlags & STARTF_USESTDHANDLES) {
761 in_fd = GPOINTER_TO_UINT (startup->hStdInput);
762 out_fd = GPOINTER_TO_UINT (startup->hStdOutput);
763 err_fd = GPOINTER_TO_UINT (startup->hStdError);
765 in_fd = GPOINTER_TO_UINT (GetStdHandle (STD_INPUT_HANDLE));
766 out_fd = GPOINTER_TO_UINT (GetStdHandle (STD_OUTPUT_HANDLE));
767 err_fd = GPOINTER_TO_UINT (GetStdHandle (STD_ERROR_HANDLE));
770 g_strlcpy (process_handle.proc_name, prog,
771 _WAPI_PROC_NAME_MAX_LEN - 1);
773 process_set_defaults (&process_handle);
775 handle = _wapi_handle_new (WAPI_HANDLE_PROCESS, &process_handle);
776 if (handle == _WAPI_HANDLE_INVALID) {
777 g_warning ("%s: error creating process handle", __func__);
779 SetLastError (ERROR_PATH_NOT_FOUND);
783 /* Hold another reference so the process has somewhere to
784 * store its exit data even if we drop this handle
786 _wapi_handle_ref (handle);
788 /* new_environ is a block of NULL-terminated strings, which
789 * is itself NULL-terminated. Of course, passing an array of
790 * string pointers would have made things too easy :-(
792 * If new_environ is not NULL it specifies the entire set of
793 * environment variables in the new process. Otherwise the
794 * new process inherits the same environment.
796 if (new_environ != NULL) {
797 gunichar2 *new_environp;
799 /* Count the number of strings */
800 for (new_environp = (gunichar2 *)new_environ; *new_environp;
803 while (*new_environp) {
808 /* +2: one for the process handle value, and the last
811 env_strings = g_new0 (gchar *, env_count + 2);
813 /* Copy each environ string into 'strings' turning it
814 * into utf8 (or the requested encoding) at the same
818 for (new_environp = (gunichar2 *)new_environ; *new_environp;
820 env_strings[env_count] = mono_unicode_to_external (new_environp);
822 while (*new_environp) {
827 for (i = 0; environ[i] != NULL; i++) {
831 /* +2: one for the process handle value, and the last
834 env_strings = g_new0 (gchar *, env_count + 2);
836 /* Copy each environ string into 'strings' turning it
837 * into utf8 (or the requested encoding) at the same
841 for (i = 0; environ[i] != NULL; i++) {
842 env_strings[env_count] = g_strdup (environ[i]);
846 /* pass process handle info to the child, so it doesn't have
847 * to do an expensive search over the whole list
849 if (env_strings != NULL) {
850 struct _WapiHandleUnshared *handle_data;
851 struct _WapiHandle_shared_ref *ref;
853 handle_data = &_WAPI_PRIVATE_HANDLES(GPOINTER_TO_UINT(handle));
854 ref = &handle_data->u.shared;
856 env_strings[env_count] = g_strdup_printf ("_WAPI_PROCESS_HANDLE_OFFSET=%d", ref->offset);
859 thr_ret = _wapi_handle_lock_shared_handles ();
860 g_assert (thr_ret == 0);
865 SetLastError (ERROR_OUTOFMEMORY);
866 _wapi_handle_unref (handle);
868 } else if (pid == 0) {
871 /* Wait for the parent to finish setting up the
872 * handle. The semaphore lock is safe because the
873 * sem_undo structures of a semaphore aren't inherited
876 thr_ret = _wapi_handle_lock_shared_handles ();
877 g_assert (thr_ret == 0);
879 _wapi_handle_unlock_shared_handles ();
881 /* should we detach from the process group? */
883 /* Connect stdin, stdout and stderr */
888 if (inherit_handles != TRUE) {
889 /* FIXME: do something here */
892 /* Close all file descriptors */
893 for (i = getdtablesize () - 1; i > 2; i--) {
898 g_message ("%s: exec()ing [%s] in dir [%s]", __func__, cmd,
900 for (i = 0; argv[i] != NULL; i++) {
901 g_message ("arg %d: [%s]", i, argv[i]);
904 for (i = 0; env_strings[i] != NULL; i++) {
905 g_message ("env %d: [%s]", i, env_strings[i]);
910 if (dir != NULL && chdir (dir) == -1) {
916 execve (argv[0], argv, env_strings);
923 ret = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
924 (gpointer *)&process_handle_data);
926 g_warning ("%s: error looking up process handle %p", __func__,
928 _wapi_handle_unref (handle);
932 process_handle_data->id = pid;
934 if (process_info != NULL) {
935 process_info->hProcess = handle;
936 process_info->dwProcessId = pid;
938 /* FIXME: we might need to handle the thread info some
941 process_info->hThread = INVALID_HANDLE_VALUE;
942 process_info->dwThreadId = 0;
946 _wapi_handle_unlock_shared_handles ();
951 if (full_prog != NULL) {
963 if(env_strings != NULL) {
964 g_strfreev (env_strings);
971 g_message ("%s: returning handle %p for pid %d", __func__, handle,
978 static void process_set_name (struct _WapiHandle_process *process_handle)
980 gchar *progname, *utf8_progname, *slash;
982 progname=g_get_prgname ();
983 utf8_progname=mono_utf8_from_external (progname);
986 g_message ("%s: using [%s] as prog name", __func__, progname);
989 if(utf8_progname!=NULL) {
990 slash=strrchr (utf8_progname, '/');
992 g_strlcpy (process_handle->proc_name, slash+1,
993 _WAPI_PROC_NAME_MAX_LEN - 1);
995 g_strlcpy (process_handle->proc_name, utf8_progname,
996 _WAPI_PROC_NAME_MAX_LEN - 1);
999 g_free (utf8_progname);
1003 extern void _wapi_time_t_to_filetime (time_t timeval, WapiFileTime *filetime);
1005 #if !GLIB_CHECK_VERSION (2,4,0)
1006 #define g_setenv(a,b,c) setenv(a,b,c)
1007 #define g_unsetenv(a) unsetenv(a)
1010 static void process_set_current (void)
1012 pid_t pid = _wapi_getpid ();
1013 const char *handle_env;
1014 struct _WapiHandle_process process_handle = {0};
1016 mono_once (&process_ops_once, process_ops_init);
1018 handle_env = g_getenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1019 g_unsetenv ("_WAPI_PROCESS_HANDLE_OFFSET");
1021 if (handle_env != NULL) {
1022 struct _WapiHandle_process *process_handlep;
1023 gchar *procname = NULL;
1026 current_process = _wapi_handle_new_from_offset (WAPI_HANDLE_PROCESS, atoi (handle_env), TRUE);
1029 g_message ("%s: Found my process handle: %p (offset %d 0x%x)",
1030 __func__, current_process, atoi (handle_env),
1034 ok = _wapi_lookup_handle (current_process, WAPI_HANDLE_PROCESS,
1035 (gpointer *)&process_handlep);
1037 /* This test will probably break on linuxthreads, but
1038 * that should be ancient history on all distros we
1041 if (process_handlep->id == pid) {
1042 procname = process_handlep->proc_name;
1043 if (!strcmp (procname, "mono")) {
1044 /* Set a better process name */
1046 g_message ("%s: Setting better process name", __func__);
1049 process_set_name (process_handlep);
1052 g_message ("%s: Leaving process name: %s", __func__, procname);
1059 /* Wrong pid, so drop this handle and fall through to
1062 _wapi_handle_unref (current_process);
1066 /* We get here if the handle wasn't specified in the
1067 * environment, or if the process ID was wrong, or if the
1068 * handle lookup failed (eg if the parent process forked and
1069 * quit immediately, and deleted the shared data before the
1070 * child got a chance to attach it.)
1074 g_message ("%s: Need to create my own process handle", __func__);
1077 process_handle.id = pid;
1079 process_set_defaults (&process_handle);
1080 process_set_name (&process_handle);
1082 current_process = _wapi_handle_new (WAPI_HANDLE_PROCESS,
1084 if (current_process == _WAPI_HANDLE_INVALID) {
1085 g_warning ("%s: error creating process handle", __func__);
1090 gpointer _wapi_process_duplicate ()
1092 mono_once (&process_current_once, process_set_current);
1094 _wapi_handle_ref (current_process);
1096 return(current_process);
1099 /* Returns a pseudo handle that doesn't need to be closed afterwards */
1100 gpointer GetCurrentProcess (void)
1102 mono_once (&process_current_once, process_set_current);
1104 return(_WAPI_PROCESS_CURRENT);
1107 guint32 GetProcessId (gpointer handle)
1109 struct _WapiHandle_process *process_handle;
1112 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1113 (gpointer *)&process_handle);
1115 SetLastError (ERROR_INVALID_HANDLE);
1119 return (process_handle->id);
1122 guint32 GetCurrentProcessId (void)
1124 mono_once (&process_current_once, process_set_current);
1126 return (GetProcessId (current_process));
1129 /* Returns the process id as a convenience to the functions that call this */
1130 static pid_t signal_process_if_gone (gpointer handle)
1132 struct _WapiHandle_process *process_handle;
1135 /* Make sure the process is signalled if it has exited - if
1136 * the parent process didn't wait for it then it won't be
1138 ok = _wapi_lookup_handle (handle, WAPI_HANDLE_PROCESS,
1139 (gpointer *)&process_handle);
1141 /* It's possible that the handle has vanished during
1142 * the _wapi_search_handle before it gets here, so
1143 * don't spam the console with warnings.
1145 /* g_warning ("%s: error looking up process handle %p",
1146 __func__, handle);*/
1152 g_message ("%s: looking at process %d", __func__, process_handle->id);
1155 if (kill (process_handle->id, 0) == -1 &&
1158 /* The process is dead, (EPERM tells us a new process
1159 * has that ID, but as it's owned by someone else it
1160 * can't be the one listed in our shared memory file)
1162 _wapi_shared_handle_set_signal_state (handle, TRUE);
1165 return (process_handle->id);
1168 static gboolean process_enum (gpointer handle, gpointer user_data)
1170 GArray *processes=user_data;
1171 pid_t pid = signal_process_if_gone (handle);
1178 /* Ignore processes that have already exited (ie they are signalled) */
1179 if (_wapi_handle_issignalled (handle) == FALSE) {
1181 g_message ("%s: process %d added to array", __func__, pid);
1184 /* This ensures that duplicates aren't returned (see
1185 * the comment above _wapi_search_handle () for why
1188 for (i = 0; i < processes->len; i++) {
1189 if (g_array_index (processes, pid_t, i) == pid) {
1190 /* We've already got this one, return
1191 * FALSE to keep searching
1197 g_array_append_val (processes, pid);
1200 /* Return false to keep searching */
1204 gboolean EnumProcesses (guint32 *pids, guint32 len, guint32 *needed)
1206 GArray *processes = g_array_new (FALSE, FALSE, sizeof(pid_t));
1209 mono_once (&process_current_once, process_set_current);
1211 _wapi_search_handle (WAPI_HANDLE_PROCESS, process_enum, processes,
1214 fit=len/sizeof(guint32);
1215 for (i = 0, j = 0; j < fit && i < processes->len; i++) {
1216 pids[j++] = g_array_index (processes, pid_t, i);
1219 g_array_free (processes, TRUE);
1221 *needed = j * sizeof(guint32);
1226 static gboolean process_open_compare (gpointer handle, gpointer user_data)
1229 pid_t checking_pid = signal_process_if_gone (handle);
1231 if (checking_pid == 0) {
1235 wanted_pid = GPOINTER_TO_UINT (user_data);
1237 /* It's possible to have more than one process handle with the
1238 * same pid, but only the one running process can be
1241 if (checking_pid == wanted_pid &&
1242 _wapi_handle_issignalled (handle) == FALSE) {
1243 /* If the handle is blown away in the window between
1244 * returning TRUE here and _wapi_search_handle pinging
1245 * the timestamp, the search will continue
1253 gpointer OpenProcess (guint32 access G_GNUC_UNUSED, gboolean inherit G_GNUC_UNUSED, guint32 pid)
1255 /* Find the process handle that corresponds to pid */
1258 mono_once (&process_current_once, process_set_current);
1261 g_message ("%s: looking for process %d", __func__, pid);
1264 handle = _wapi_search_handle (WAPI_HANDLE_PROCESS,
1265 process_open_compare,
1266 GUINT_TO_POINTER (pid), NULL, TRUE);
1269 g_message ("%s: Can't find pid %d", __func__, pid);
1272 SetLastError (ERROR_PROC_NOT_FOUND);
1277 _wapi_handle_ref (handle);
1282 gboolean GetExitCodeProcess (gpointer process, guint32 *code)
1284 struct _WapiHandle_process *process_handle;
1287 mono_once (&process_current_once, process_set_current);
1293 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1294 (gpointer *)&process_handle);
1297 g_message ("%s: Can't find process %p", __func__, process);
1303 /* A process handle is only signalled if the process has exited
1304 * and has been waited for */
1305 if (_wapi_handle_issignalled (process) == TRUE ||
1306 process_wait (process, 0) == WAIT_OBJECT_0) {
1307 *code = process_handle->exitstatus;
1309 *code = STILL_ACTIVE;
1315 gboolean GetProcessTimes (gpointer process, WapiFileTime *create_time,
1316 WapiFileTime *exit_time, WapiFileTime *kernel_time,
1317 WapiFileTime *user_time)
1319 struct _WapiHandle_process *process_handle;
1322 mono_once (&process_current_once, process_set_current);
1324 if(create_time==NULL || exit_time==NULL || kernel_time==NULL ||
1326 /* Not sure if w32 allows NULLs here or not */
1330 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1331 (gpointer *)&process_handle);
1334 g_message ("%s: Can't find process %p", __func__, process);
1340 *create_time=process_handle->create_time;
1342 /* A process handle is only signalled if the process has
1343 * exited. Otherwise exit_time isn't set
1345 if(_wapi_handle_issignalled (process)==TRUE) {
1346 *exit_time=process_handle->exit_time;
1352 gboolean EnumProcessModules (gpointer process, gpointer *modules,
1353 guint32 size, guint32 *needed)
1355 /* Store modules in an array of pointers (main module as
1356 * modules[0]), using the load address for each module as a
1357 * token. (Use 'NULL' as an alternative for the main module
1358 * so that the simple implementation can just return one item
1359 * for now.) Get the info from /proc/<pid>/maps on linux,
1360 * other systems will have to implement /dev/kmem reading or
1361 * whatever other horrid technique is needed.
1363 if(size<sizeof(gpointer)) {
1369 *needed=sizeof(gpointer);
1372 *needed=sizeof(gpointer);
1378 guint32 GetModuleBaseName (gpointer process, gpointer module,
1379 gunichar2 *basename, guint32 size)
1381 struct _WapiHandle_process *process_handle;
1384 mono_once (&process_current_once, process_set_current);
1387 g_message ("%s: Getting module base name, process handle %p module %p",
1388 __func__, process, module);
1391 if(basename==NULL || size==0) {
1395 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1396 (gpointer *)&process_handle);
1399 g_message ("%s: Can't find process %p", __func__, process);
1406 /* Shorthand for the main module, which has the
1407 * process name recorded in the handle data
1410 gunichar2 *procname;
1411 gchar *procname_utf8 = NULL;
1415 g_message ("%s: Returning main module name", __func__);
1418 pid=process_handle->id;
1419 procname_utf8 = process_handle->proc_name;
1422 g_message ("%s: Process name is [%s]", __func__,
1426 procname = g_utf8_to_utf16 (procname_utf8, -1, NULL, &len,
1428 if (procname == NULL) {
1433 /* Add the terminator, and convert chars to bytes */
1434 bytes = (len + 1) * 2;
1438 g_message ("%s: Size %d smaller than needed (%ld); truncating", __func__, size, bytes);
1441 memcpy (basename, procname, size);
1444 g_message ("%s: Size %d larger than needed (%ld)",
1445 __func__, size, bytes);
1448 memcpy (basename, procname, bytes);
1455 /* Look up the address in /proc/<pid>/maps */
1461 gboolean GetProcessWorkingSetSize (gpointer process, size_t *min, size_t *max)
1463 struct _WapiHandle_process *process_handle;
1466 mono_once (&process_current_once, process_set_current);
1468 if(min==NULL || max==NULL) {
1469 /* Not sure if w32 allows NULLs here or not */
1473 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1474 (gpointer *)&process_handle);
1477 g_message ("%s: Can't find process %p", __func__, process);
1483 *min=process_handle->min_working_set;
1484 *max=process_handle->max_working_set;
1489 gboolean SetProcessWorkingSetSize (gpointer process, size_t min, size_t max)
1491 struct _WapiHandle_process *process_handle;
1494 mono_once (&process_current_once, process_set_current);
1496 ok=_wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1497 (gpointer *)&process_handle);
1500 g_message ("%s: Can't find process %p", __func__, process);
1506 process_handle->min_working_set=min;
1507 process_handle->max_working_set=max;
1514 TerminateProcess (gpointer process, gint32 exitCode)
1516 struct _WapiHandle_process *process_handle;
1521 ok = _wapi_lookup_handle (process, WAPI_HANDLE_PROCESS,
1522 (gpointer *) &process_handle);
1526 g_message ("%s: Can't find process %p", __func__, process);
1528 SetLastError (ERROR_INVALID_HANDLE);
1532 signo = (exitCode == -1) ? SIGKILL : SIGTERM;
1533 ret = kill (process_handle->id, signo);
1537 SetLastError (ERROR_INVALID_PARAMETER);
1540 SetLastError (ERROR_ACCESS_DENIED);
1543 SetLastError (ERROR_PROC_NOT_FOUND);
1546 SetLastError (ERROR_GEN_FAILURE);